@adhdev/daemon-standalone 0.9.54 → 0.9.56

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 cd=Object.defineProperty;var ld=(e,t,r)=>t in e?cd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ve=(e,t,r)=>ld(e,typeof t!="symbol"?t+"":t,r);import{r as i,j as s,M as Sa,a as dd,b as ud,c as md,u as Ls,R as jt,d as Zs,t as fd,e as pd,D as hd,f as Qn,g as Zn,h as Na,i as xd,k as bd,B as gd,l as yd,m as Yt,N as ea,n as vd}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 wd(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 Ss=wd();function go(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 jd(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function kd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Mi(e,t){var m;if(!e)return t??null;if(!t)return e??null;const r=kd(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:void 0,a=e.status==="waiting_approval"||Array.isArray((m=e.activeModal)==null?void 0:m.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),u={...t,...e,activeModal:l,inputContent:e.inputContent??t.inputContent};return r?{...u,messages:c}:u}function zs(e,t){const r=jd(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:Mi(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 Ai(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?zs(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 yo(e){return!!e&&typeof e=="object"&&"text"in e}function Ca(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:yo(o)?String(o.text||""):"").join(r):yo(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Bt(e){return Ca(e,{normalizeWhitespace:!0})}const Li=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}),Ri=i.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function vo(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 _i(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,u=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),o&&(n.serverVersion=o),u&&(n.versionUpdateReason=u),a&&o&&a===o?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||c&&a&&o&&a!==o)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function Sd(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 xn(e){if(!e||typeof e!="object")return"";const t=e,r=Sd(Bt(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 Nd(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=xn(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:xn(e[0]),last:xn(e[e.length-1])}}function ta(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function sa(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(ta(e)&&ta(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)sa(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"&&sa(n[c],a[c],r)}function Gs(e,t){return Array.isArray(e)?e.map(r=>Gs(r,t)):!e||typeof e!="object"?e:ta(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Nd(a,t):Gs(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Gs(n,t)]))}function Cd(e,t){try{const r=new WeakSet;return sa(e,t,r),JSON.stringify(Gs(e,r))===JSON.stringify(Gs(t,r))}catch{return!1}}function ra(e,t,r){return Cd(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Pi(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Td(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function wo(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,o=Ai(e.childSessions,t.childSessions,{preserveMissing:n}),c=Mi(t.activeChat,e.activeChat);return _i(e,t,{...e,...t,chats:a,childSessions:o,activeChat:c,_lastUpdate:r})}function Id(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=Ai(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"])Td(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Md(e,t,r,n){const a=Id(e,t,n),o=Object.keys(a).length>0?_i(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return ra(e,o,r)}function Ad(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=Pi(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 Ld(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 Rd(e,t,r,n){return!!(r.has(t)&&e.transport&&!n.has(t))}function _d(e,t,r){var d,h;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(f=>({...f,_lastUpdate:n}));const o=new Map;for(const f of t)o.set(f.id,f);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:u,daemonIdsWithAuthoritativeSessionList:m}=Ad(e);for(const f of e){const w=o.get(f.id);if(!w){o.set(f.id,{...f,_lastUpdate:n});continue}const k=vo(f),p=vo(w),y=Pi(f),x=!a.has(y);if(k>p){const R=wo(w,f,n,x);o.set(f.id,ra(w,R,n));continue}if(k<p){o.set(f.id,Md(w,f,n,x));continue}const b=f.timestamp||n,v=w._lastUpdate||w.timestamp||0;if(b>=v){const R=wo(w,f,n,x);o.set(f.id,ra(w,R,n));continue}(d=f.chats)!=null&&d.length&&!((h=w.chats)!=null&&h.length)&&o.set(f.id,{...w,chats:f.chats})}for(const[f,w]of o){const k=w.daemonId||f.split(":")[0];if(!l.has(k))continue;if(a.has(k)&&m.has(k)&&!c.has(f)){o.delete(f);continue}const p=n-(w._lastUpdate||w.timestamp||0);Ld(w,k,p,c,a,u)&&o.delete(f)}for(const[f,w]of o){const k=w.daemonId||f.split(":")[0];if(Rd(w,k,l,u))continue;n-(w._lastUpdate||w.timestamp||0)>3e5&&w.status!=="online"&&o.delete(f)}return Array.from(o.values())}function Pd(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 Dd({children:e,connectionOverrides:t}){const[r,n]=i.useState([]),[a,o]=i.useState(!1),[c,l]=i.useState([]),[u,m]=i.useState(void 0),d=i.useRef(r);i.useEffect(()=>{d.current=r},[r]);const h=i.useCallback((x,b)=>{n(v=>{let R=!1;const g=v.map(M=>M.id!==x||M.chats===b?M:(R=!0,{...M,chats:b}));return R?g:v})},[]),f=i.useCallback((x,b)=>{n(v=>{const R=v.length===0?x:_d(x,v,b),g=!Pd(v,R);return g&&Ss.record({kind:"dashboard.entries_applied",payload:{incoming:go(x),next:go(R)}}),g?R:v})},[]),w=i.useCallback(()=>o(!0),[]),k=i.useMemo(()=>({injectEntries:f,markLoaded:w,getIdes:()=>d.current}),[f,w]),p=t,y=i.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(p==null?void 0:p.wsStatus)??"connected",isConnected:(p==null?void 0:p.isConnected)??!0,connectionStates:(p==null?void 0:p.connectionStates)??{},connectionTransports:(p==null?void 0:p.connectionTransports)??{},showReconnected:(p==null?void 0:p.showReconnected)??!1,retryConnection:p==null?void 0:p.retryConnection,retryServerConnection:p==null?void 0:p.retryServerConnection,connectionLoginUrl:p==null?void 0:p.connectionLoginUrl,isP2PActive:(p==null?void 0:p.isP2PActive)??!1,p2pStates:(p==null?void 0:p.p2pStates)??{},userRole:p==null?void 0:p.userRole,connectionRetryStatuses:p==null?void 0:p.connectionRetryStatuses,userName:u,setUserName:m}),[r,h,a,c,p==null?void 0:p.wsStatus,p==null?void 0:p.isConnected,p==null?void 0:p.connectionStates,p==null?void 0:p.connectionTransports,p==null?void 0:p.showReconnected,p==null?void 0:p.retryConnection,p==null?void 0:p.retryServerConnection,p==null?void 0:p.connectionLoginUrl,p==null?void 0:p.isP2PActive,p==null?void 0:p.p2pStates,p==null?void 0:p.userRole,p==null?void 0:p.connectionRetryStatuses,u]);return s.jsx(Ri.Provider,{value:k,children:s.jsx(Li.Provider,{value:y,children:e})})}function ls(){return i.useContext(Li)}function er(){return i.useContext(Ri)}function Di(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 u=r==null?void 0:r(),m=a(l),d=l.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return u&&d.searchParams.set("token",u),!l.startsWith("http")&&!t?`${d.pathname}${d.search}${d.hash}`:d.toString()}async function c(l,u={}){const m={"Content-Type":"application/json",...u.headers||{}},d=r==null?void 0:r();d&&(m.Authorization=`Bearer ${d}`);const h=a(l),f=new AbortController,w=setTimeout(()=>f.abort(),15e3);try{const k=await fetch(h,{...u,headers:m,signal:f.signal});if(k.status===401)throw n==null||n(),new Error("Unauthorized");if(!k.ok){const p=await k.json().catch(()=>({error:k.statusText}));throw new Error(p.error||`API Error: ${k.status}`)}return k.json()}finally{clearTimeout(w)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,u,m={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:m})}),execTerminal:(l,u,m)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:m})}),sendAgentMessage:(l,u,m)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:m})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,m)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:m?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,u,m={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:m})}),getMuxEventsUrl:l=>o(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>o(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Ed=Di({baseUrl:"http://localhost:3847"}),$d=i.createContext(Ed);function Bd({client:e,children:t}){return s.jsx($d.Provider,{value:e,children:t})}const Kd={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Ei=i.createContext(Kd);function Od({value:e,children:t}){return s.jsx(Ei.Provider,{value:e,children:t})}function vt(){return i.useContext(Ei)}function Wd(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 Hd(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function $i(e){return e?Wd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Hd(e.content)]):""}const Ke={size:18};function Bi({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Ta({size:e=Ke.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 ds({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Ki({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Fd({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Ud({size:e=Ke.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 Oi({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 zd({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 en({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Wi({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Vd({size:e=Ke.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 Ht({size:e=Ke.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 Nt({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Ia({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Gd({size:e=Ke.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Ns({size:e=Ke.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 or({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 tr({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 sr({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Hi({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Fi({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Ui({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 qd({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Ma({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Yd({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Aa({size:e=Ke.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=Ke.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function wt({size:e=Ke.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 Xd({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Jd({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Qd({size:e=Ke.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 Zd({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 tn({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 eu({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 tu({size:e=Ke.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 su({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 ru({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 nu({size:e=Ke.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 au({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 ou({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 iu({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 cu({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 lu({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 du({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 uu({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Vi=[dd,{singleTilde:!1}],Gi=[Vi,ud,md],mu=[Vi],La=200,fu=80,jo=650,Es=new Map;function Wr(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function pu(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}:${$i(n)}`}function hu(e,t,r,n){return e||!t?!1:Wr(r,n)}function xu({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=fu,bottomThresholdPx:a=La}){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 bu(e){return xu({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Vs(e,t=La){return!!e&&e.fromBottom>=t}function gu(e,t){return Wr(e,t)?!Vs(e):!0}function yu({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function vu({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function bn(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function qi(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function wu(e,t,r){return Number(e.receivedAt||r[Hr(e,t)]||0)||0}function Yi(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function ju(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function fr(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 gn(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 ko(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Yi(e)?s.jsx(Sa,{remarkPlugins:Gi,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function pr({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:ko(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=gn(r);return a?s.jsx("img",{src:a,alt:fr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=gn(r);return a?s.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=gn(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:fr(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||fr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=fr(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}),ko(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 Hr(e,t){const r=e,n=Ca(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 ku=i.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Sa,{remarkPlugins:mu,children:t.text}),s.jsx("span",{className:"action-time",children:qi(t.timestamp)})]})},(e,t)=>e.log===t.log),Su=i.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:c,onToggleTextExpanded:l}){var M,C,S;const u=(t.role||"").toLowerCase(),m=u==="user"||u==="human",d=t.kind||(u==="tool"?"tool":"standard"),h=ju(t.content)?t.content:null,f=!!(h!=null&&h.some(j=>j.type!=="text")),w=Ca(t.content,{joiner:`
4
- `});if(d==="thought"){const j=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(Qd,{size:13}),s.jsx("span",{children:j})]}),s.jsx("div",{className:"chat-msg-body",children:w})]})}if(d==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),f&&h?s.jsx("div",{className:"tool-text w-full",children:s.jsx(pr,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:w})]});if(d==="terminal"){const j=(C=t.meta)!=null&&C.isRunning?"⏳":"✅",W=typeof((S=t.meta)==null?void 0:S.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:j}),s.jsx("span",{children:W})]}),f&&h?s.jsx("div",{className:"chat-msg-body",children:s.jsx(pr,{parts:h,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:w})]})}if(d==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:f&&h?s.jsx(pr,{parts:h,renderAsPreformatted:!1}):w.slice(0,100)});const k=t.meta,y=(typeof(k==null?void 0:k.renderMode)=="string"?k.renderMode.trim():"")==="preformatted",x=w,b=!1,v=x,R=y,g=!R&&Yi(v);return s.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${m?"self-end":"self-start"}`,children:(x||f||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${x||f?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:m?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:qi(r)})]}),(x||f)&&s.jsx("div",{className:"chat-markdown",children:f&&h?s.jsx(pr,{parts:h,renderAsPreformatted:R}):R?s.jsx("pre",{className:"chat-preformatted",children:v}):g?s.jsx(Sa,{remarkPlugins:Gi,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),Nu=i.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},lastMessageHash:m,emptyState:d,onLoadMore:h,isLoadingMore:f,hasMoreHistory:w,hiddenLiveCount:k=0,loadError:p,scrollToBottomRequestNonce:y,isVisible:x=!0},b){const v=i.useRef(null),R=i.useRef(null),g=i.useRef(null),M=i.useRef(0),C=i.useRef(""),S=i.useRef(""),j=i.useRef(!1),W=i.useRef(null),L=i.useRef(!1),I=i.useRef(null),D=i.useRef(!1),[U,K]=i.useState(new Set),[N,A]=i.useState({showTop:!1,showBottom:!1}),z=i.useRef(!1),$=i.useRef(!1),B=i.useRef(x),V=i.useRef(x),G=i.useRef(null);V.current=x;const me=()=>{const q=v.current;return q?q.scrollHeight-q.scrollTop-q.clientHeight<La:!0},ne=i.useCallback(()=>{const q=v.current,X=q?bu(q):{showTop:!1,showBottom:!1};A(ae=>ae.showTop===X.showTop&&ae.showBottom===X.showBottom?ae:X)},[]),xe=i.useCallback((q="auto")=>{var ae;const X=v.current;X&&(X.scrollTo({top:X.scrollHeight,behavior:q}),(ae=X.ownerDocument.defaultView)==null||ae.requestAnimationFrame(()=>ne()))},[ne]),de=i.useCallback((q="auto")=>{var ae;const X=v.current;X&&(X.scrollTo({top:0,behavior:q}),(ae=X.ownerDocument.defaultView)==null||ae.requestAnimationFrame(()=>ne()))},[ne]),be=i.useCallback(()=>{var ke;const q=v.current,X=(ke=window.getSelection)==null?void 0:ke.call(window);if(!q||!X||X.rangeCount===0||X.isCollapsed){D.current=!1;return}const ae=X.anchorNode,je=X.focusNode;D.current=!!(ae&&je&&q.contains(ae)&&q.contains(je))},[]),he=pu(t,m),Y=i.useCallback(()=>{const q=v.current;if(!q||!l||!V.current)return;const X={top:q.scrollTop,fromBottom:Math.max(0,q.scrollHeight-q.scrollTop-q.clientHeight),messageFingerprint:he};G.current={contextKey:l,snapshot:X},Es.set(l,X)},[l,he]),oe=i.useCallback((q="auto")=>{W.current!=null&&cancelAnimationFrame(W.current),W.current=requestAnimationFrame(()=>{W.current=null,xe(q)})},[xe]),J=i.useCallback(()=>{z.current=!1,L.current=!0,$.current=!0,I.current!=null&&window.clearTimeout(I.current),I.current=window.setTimeout(()=>{L.current=!1,I.current=null},jo)},[]);i.useEffect(()=>{const q=!j.current,X=S.current!==l;if(S.current=l,q||X){j.current=!0;const je=l?Es.get(l):null,ke=!!je&&Wr(je,he);z.current=ke?Vs(je):!1,L.current=gu(je,he),D.current||(ke?requestAnimationFrame(()=>{const te=v.current;te&&(bn(te,je),z.current=Vs(je),ne(),$.current=!0)}):oe("auto")),M.current=t.length,C.current=he;return}t.length>M.current;const ae=he!==C.current;yu({hasSelection:D.current,userScrolledUp:z.current,hasChatContentChanged:ae})&&oe("auto"),M.current=t.length,C.current=he},[he,l,t.length,oe,ne]),i.useEffect(()=>{y&&(J(),D.current||oe("auto"))},[J,oe,y]),i.useEffect(()=>{const q=B.current;q&&!x&&Y(),V.current=x,B.current=x;const X=l?Es.get(l):null;if(hu(q,x,X,he)){if(!X)return;z.current=Vs(X),L.current=!1,D.current||requestAnimationFrame(()=>{const ae=v.current;ae&&(bn(ae,X),ne())});return}},[x,l,he,J,Y,oe,ne]),i.useEffect(()=>()=>{const q=G.current;q&&Es.set(q.contextKey,q.snapshot),W.current!=null&&cancelAnimationFrame(W.current),I.current!=null&&window.clearTimeout(I.current)},[]),i.useEffect(()=>{const q=R.current,X=v.current;if(!q||!X)return;const ae=()=>{I.current!=null&&window.clearTimeout(I.current),I.current=window.setTimeout(()=>{L.current=!1,I.current=null},jo)},je=new ResizeObserver(()=>{ne();const ke=L.current;vu({hasSelection:D.current,userScrolledUp:z.current,contextAutoScrollActive:ke})&&(oe("auto"),ke&&ae())});return je.observe(q),X!==q&&je.observe(X),()=>{je.disconnect(),I.current!=null&&(window.clearTimeout(I.current),I.current=null)}},[oe,l,ne]),i.useImperativeHandle(b,()=>({scrollToBottom:(q="smooth")=>{xe(q)}}),[xe]),i.useEffect(()=>{const q=v.current;if(!q)return;let X;const ae=()=>{Y(),clearTimeout(X),X=setTimeout(()=>{z.current=!me(),ne()},50)};return q.addEventListener("scroll",ae,{passive:!0}),()=>{q.removeEventListener("scroll",ae),clearTimeout(X)}},[Y,ne]),i.useEffect(()=>(document.addEventListener("selectionchange",be),()=>document.removeEventListener("selectionchange",be)),[be]);const ue=i.useRef(0),le=i.useRef(!1);i.useEffect(()=>{const q=v.current;if(!q||!le.current||ue.current===0)return;const X=q.scrollHeight-ue.current;X>0&&(q.scrollTop=X),ne(),Y(),ue.current=0,le.current=!1},[t.length,Y,ne]),i.useEffect(()=>{if($.current||!l)return;const q=Es.get(l),X=v.current;if(!(!q||!X)){if(!Wr(q,he)){xe("auto"),$.current=!0;return}bn(X,q),z.current=Vs(q),ne(),$.current=!0}},[l,he,t.length,xe,ne]);const Se=()=>{const q=v.current;q&&(ue.current=q.scrollHeight),le.current=!0,h==null||h()},ie=()=>{z.current=!0,de("smooth"),Y()},pe=()=>{J(),xe("smooth"),Y()},re=i.useMemo(()=>{const q=t.map((ke,te)=>({type:"message",data:ke,index:te,ts:wu(ke,te,u)}));if(!r||r.length===0)return q;const X=[...r].sort((ke,te)=>ke.timestamp-te.timestamp).map((ke,te)=>({type:"action",data:ke,index:te,ts:ke.timestamp})),ae=[];let je=0;for(const ke of q){for(;je<X.length&&ke.ts>0&&X[je].ts<ke.ts;)ae.push(X[je++]);ae.push(ke)}for(;je<X.length;)ae.push(X[je++]);return ae},[t,r,u]),Z=k>0||!!w,ee=k>0?`↑ Show ${Math.min(k,80)} earlier messages${k>80?` (${k} hidden)`:""}`:p?`↻ ${p}`:"↑ 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:R,className:"chat-container-content",children:[f&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),Z&&!f&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:Se,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${p&&k===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:ee})}),re.length===0&&!Z&&(d||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),re.map(q=>{if(q.type==="action"){const ve=q.data;return s.jsx(ku,{log:ve},`action-${q.index}`)}const X=q.data,ae=q.index,je=Hr(X,ae),ke=X.receivedAt||u[je],te=`${l}-${je}`,E=U.has(te);return s.jsx(Su,{message:X,receivedAt:ke,agentName:n,userName:a,isCliMode:o,isTextExpanded:E,onToggleTextExpanded:()=>K(ve=>{const Ce=new Set(ve);return E?Ce.delete(te):Ce.add(te),Ce})},`msg-${je}`)}),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})]})}),(N.showTop||N.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[N.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:ie,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),N.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:pe,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Cu=i.memo(Nu,(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),Tu="modulepreload",Iu=function(e){return"/"+e},So={},Mu=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(u=>{if(u=Iu(u),u in So)return;So[u]=!0;const m=u.endsWith(".css"),d=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const h=document.createElement("link");if(h.rel=m?"stylesheet":Tu,m||(h.as="script"),h.crossOrigin="",h.href=u,l&&h.setAttribute("nonce",l),document.head.appendChild(h),m)return new Promise((f,w)=>{h.addEventListener("load",f),h.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${u}`)))})}))}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 No=!1;const Xi=i.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},c)=>{const l=i.useRef(null),[u,m]=i.useState(null),d=i.useRef([]),h=i.useRef(!1),f=i.useRef(!1),w=i.useRef(!1),k=i.useRef(!1),p=()=>{const y=l.current;if(y){h.current&&(y.clear(),h.current=!1);for(const x of d.current)y.write(x.data,x.onProcessed);d.current=[],f.current&&(y.fit(),f.current=!1),w.current&&(y.bumpResize(),w.current=!1),k.current&&(y.scrollToTop(),k.current=!1)}};return i.useImperativeHandle(c,()=>({write:(y,x)=>{l.current?l.current.write(y,x):d.current.push({data:y,onProcessed:x})},clear:()=>{l.current?l.current.clear():(d.current=[],h.current=!0)},reset:()=>{l.current&&typeof l.current.reset=="function"?l.current.reset():(d.current=[],h.current=!0)},resize:(y,x)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(y,x)},fit:()=>{l.current?l.current.fit():f.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():w.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():k.current=!0},getSelection:()=>{var y,x;return((x=(y=l.current)==null?void 0:y.getSelection)==null?void 0:x.call(y))||""},getVisibleText:()=>{var y,x;return((x=(y=l.current)==null?void 0:y.getVisibleText)==null?void 0:x.call(y))||""}}),[]),i.useEffect(()=>{u&&p()},[u]),i.useEffect(()=>{let y=!1;return Mu(()=>import("./terminal-DbJP_JGY.js"),__vite__mapDeps([0,1,2])).then(x=>{No||(No=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),y||m(()=>x.GhosttyTerminalView)}).catch(x=>{console.error("[CliTerminal] failed to load terminal renderer",x)}),()=>{y=!0}},[]),u?s.jsx(u,{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"}})});Xi.displayName="CliTerminal";function hr({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 Co({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 Au({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,u=c/l,m=a.width/a.height;let d,h,f,w;u>m?(d=a.width,h=a.width/u,f=0,w=(a.height-h)/2):(h=a.height,d=a.height*u,f=(a.width-d)/2,w=0);const k=a.left-o.left+f+d*e.nx,p=a.top-o.top+w+h*e.ny,y=Math.max(8,Math.min(o.width-8,k)),x=Math.max(8,Math.min(o.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:y-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 Lu({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:m,zoom:d,isMobile:h,mobileFillZoom:f,onZoomOut:w,onZoomReset:k,onZoomIn:p,transportType:y,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=>{u(v)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{o(v=>!v),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:m?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),d>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),y==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),y==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),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: ",d<=(h?f:1)+.01?h?"FILL":"FIT":`${Math.round(d*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:v=>{v.stopPropagation(),w()},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(),k()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:h?"FILL":"FIT"}),s.jsx("button",{onClick:v=>{v.stopPropagation(),p()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function Ru({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 _u(){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 To(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 ir(e,t){const r=i.useRef(null),n=i.useRef(0);i.useEffect(()=>{if(!_u())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,To(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,To(t[c])]))}),r.current=t})}function Pu({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:c,panXRef:l,panYRef:u,setPanX:m,setPanY:d,setZoom:h,lastWheelTimeRef:f,onAction:w,setLastActionStatus:k,spawnRippleFromNormalized:p,clampPan:y,isMobile:x,mobileFillZoom:b}){const[v,R]=i.useState(null),g=i.useRef(null),M=i.useRef(null),C=i.useRef(null),S=i.useRef(!1),j=i.useRef(null),W=i.useRef(0),L=i.useRef(null),I=i.useRef(1),D=i.useRef({x:0,y:0}),U=i.useRef(!1),K=i.useRef(n),N=i.useRef(w),A=30,z=550,$=18,B=60,V=400,G=12,me=()=>{if(g.current)return;const de={nx:.5,ny:.5};g.current=de,R(de)};return i.useEffect(()=>{K.current=n,n==="mouse"&&me()},[n]),i.useEffect(()=>{N.current=w},[w]),i.useEffect(()=>{const de=e.current;if(!de)return;const be=le=>{if(!r.current)return null;const Se=r.current.getBoundingClientRect();return!Se.width||!Se.height?null:{nx:Math.max(0,Math.min(1,(le.clientX-Se.left)/Se.width)),ny:Math.max(0,Math.min(1,(le.clientY-Se.top)/Se.height))}},he=(le,Se)=>{if(!r.current)return{dnx:0,dny:0};const ie=r.current,pe=ie.getBoundingClientRect(),re=ie.naturalWidth||pe.width,Z=ie.naturalHeight||pe.height,ee=re/Z,q=pe.width/pe.height;let X,ae;return ee>q?(X=pe.width,ae=pe.width/ee):(ae=pe.height,X=pe.height*ee),{dnx:le/X,dny:Se/ae}},Y=(le,Se,ie)=>{if(ie<=1.05)return;const pe=-(le-.5)*100,re=-(Se-.5)*100,Z=y(pe,re,ie);(Math.abs(Z.x-l.current)>.1||Math.abs(Z.y-u.current)>.1)&&(m(Z.x),d(Z.y),l.current=Z.x,u.current=Z.y)},oe=le=>{const Se=t.current;if(Se&&le.target instanceof Node&&Se.contains(le.target))le.preventDefault();else return;if(le.touches.length===1){const ie=le.touches[0];M.current={x:ie.clientX,y:ie.clientY,time:Date.now()},C.current={x:ie.clientX,y:ie.clientY},U.current||(S.current=!1),j.current=setTimeout(()=>{if(!S.current&&!U.current)if(S.current=!0,K.current==="mouse"){const pe=g.current||{nx:.5,ny:.5};k("Right Click"),p(pe.nx,pe.ny,"right"),N.current("input_click",{...pe,button:"right"}).catch(()=>{})}else{const pe=be(ie);pe&&(k("Right Click"),p(pe.nx,pe.ny,"right"),N.current("input_click",{...pe,button:"right"}).catch(()=>{}))}},500);return}if(le.touches.length===2){j.current&&clearTimeout(j.current),S.current=!0,U.current=!0;const ie=le.touches[1].clientX-le.touches[0].clientX,pe=le.touches[1].clientY-le.touches[0].clientY;L.current=Math.sqrt(ie*ie+pe*pe),I.current=c.current,D.current={x:(le.touches[0].clientX+le.touches[1].clientX)/2,y:(le.touches[0].clientY+le.touches[1].clientY)/2}}},J=le=>{const Se=t.current;if(Se&&le.target instanceof Node&&Se.contains(le.target)&&le.preventDefault(),le.touches.length===1&&C.current){const ie=le.touches[0],pe=ie.clientX-C.current.x,re=ie.clientY-C.current.y;if(!S.current&&M.current){const Z=ie.clientX-M.current.x,ee=ie.clientY-M.current.y;Math.sqrt(Z*Z+ee*ee)>8&&(S.current=!0,j.current&&clearTimeout(j.current))}if(S.current)if(K.current==="mouse"){const Z=he(pe,re),ee=g.current||{nx:.5,ny:.5},q=Math.max(0,Math.min(1,ee.nx+Z.dnx)),X=Math.max(0,Math.min(1,ee.ny+Z.dny));g.current={nx:q,ny:X},R({nx:q,ny:X}),k(`Cursor: ${Math.round(q*100)}%, ${Math.round(X*100)}%`),Y(q,X,c.current);const ae=Date.now();ae-f.current>=30&&(f.current=ae,N.current("input_mouseMoved",{nx:q,ny:X}).catch(()=>{}))}else if(c.current>1){const Z=t.current;if(Z){const ee=Z.clientWidth,q=Z.clientHeight,X=l.current+pe/ee*100,ae=u.current+re/q*100,je=y(X,ae,c.current);m(je.x),d(je.y),l.current=je.x,u.current=je.y}}else{const Z=be(ie);if(Z){const ee=Date.now();ee-f.current>=40&&(f.current=ee,k("Scroll"),N.current("input_wheel",{nx:Z.nx,ny:Z.ny,deltaX:Math.round(-pe*2.5),deltaY:Math.round(-re*2.5)}).catch(()=>{}))}}C.current={x:ie.clientX,y:ie.clientY};return}if(le.touches.length===2&&L.current!==null){const ie=le.touches[1].clientX-le.touches[0].clientX,pe=le.touches[1].clientY-le.touches[0].clientY,Z=Math.sqrt(ie*ie+pe*pe)/L.current,ee=(le.touches[0].clientX+le.touches[1].clientX)/2,q=(le.touches[0].clientY+le.touches[1].clientY)/2,X=ee-D.current.x,ae=q-D.current.y,je=Math.abs(Z-1)>.03;if(K.current==="mouse"){if(je){const ke=Math.max(o,Math.min(5,I.current*Z));h(ke),c.current=ke}else if(Math.abs(X)>2||Math.abs(ae)>2){const ke=g.current||{nx:.5,ny:.5},te=Date.now();te-f.current>=30&&(f.current=te,k("Scroll"),N.current("input_wheel",{nx:ke.nx,ny:ke.ny,deltaX:Math.round(-X*3),deltaY:Math.round(-ae*3)}).catch(()=>{}))}}else{const ke=Math.max(o,Math.min(5,I.current*Z));h(ke),c.current=ke;const te=t.current;if(te&&ke>1){const E=te.clientWidth,ve=te.clientHeight,Ce=l.current+X/E*100,we=u.current+ae/ve*100,Pe=y(Ce,we,ke);m(Pe.x),d(Pe.y),l.current=Pe.x,u.current=Pe.y}}D.current={x:ee,y:q}}},ue=le=>{var Se;if(j.current&&clearTimeout(j.current),L.current=null,le.touches.length===1&&U.current){const ie=le.touches[0];M.current={x:ie.clientX,y:ie.clientY,time:Date.now()},C.current={x:ie.clientX,y:ie.clientY},S.current=!0;return}if(le.touches.length===0){if(U.current){U.current=!1,S.current=!1;return}if(le.changedTouches.length===1){const ie=le.changedTouches[0],pe=Date.now(),re=pe-(((Se=M.current)==null?void 0:Se.time)||0),Z=M.current?ie.clientX-M.current.x:0,ee=M.current?ie.clientY-M.current.y:0,q=Math.sqrt(Z*Z+ee*ee);if(K.current==="mouse"){if(re<A||re>z||q>$){S.current=!1;return}const X=g.current||be(ie);X&&(k(`Click: ${Math.round(X.nx*100)}%, ${Math.round(X.ny*100)}%`),p(X.nx,X.ny,"left"),N.current("input_click",{...X}).catch(()=>{}))}else{if(S.current){S.current=!1;return}if(re<B||re>V||q>G){S.current=!1;return}const X=be(ie);if(!X)return;pe-W.current<300?(k("Double tap"),p(X.nx,X.ny,"double"),N.current("input_click",{...X,clickCount:2}).catch(()=>{}),W.current=0):(k(`Tap: ${Math.round(X.nx*100)}%, ${Math.round(X.ny*100)}%`),p(X.nx,X.ny,"left"),N.current("input_click",{...X}).catch(()=>{}),W.current=pe)}}S.current=!1}};return de.addEventListener("touchstart",oe,{passive:!1}),de.addEventListener("touchmove",J,{passive:!1}),de.addEventListener("touchend",ue,{passive:!1}),()=>{de.removeEventListener("touchstart",oe),de.removeEventListener("touchmove",J),de.removeEventListener("touchend",ue),j.current&&clearTimeout(j.current)}},[e,t,r,o,c,l,u,m,d,h,f,k,p,y]),{cursorPos:v,cursorPosRef:g,handleToggleInputMode:()=>{a(de=>{const be=de==="touch"?"mouse":"touch";return be==="mouse"&&me(),be})},handleZoomReset:()=>{const de=x?b:1;h(de),c.current=de,m(0),d(0),l.current=0,u.current=0}}}function Ji({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const c=i.useRef(null),l=i.useRef(null),u=i.useRef(null),[m,d]=i.useState(null),[h,f]=i.useState(""),[,w]=i.useState(!1),[k,p]=i.useState([]),y=i.useRef(0),[x,b]=i.useState(!1),[v,R]=i.useState(!1),g=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[M,C]=i.useState(g?"mouse":"touch"),[S,j]=i.useState(1),W=i.useRef(!1),[L,I]=i.useState(1),[D,U]=i.useState(0),[K,N]=i.useState(0);ir("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:M,zoom:L,panX:D,panY:K,isMenuOpen:x,isImeOpen:v});const A=i.useRef(0),z=i.useRef(L),$=i.useRef(D),B=i.useRef(K);i.useEffect(()=>{z.current=L},[L]),i.useEffect(()=>{$.current=D},[D]),i.useEffect(()=>{B.current=K},[K]),i.useEffect(()=>{var re;(re=c.current)==null||re.focus()},[]);const V=r==="connected",G=n,me=V?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ne=V?"The remote stream is warming up":"Waiting for the remote stream to catch up";i.useEffect(()=>{if(!g||W.current||!G)return;const re=u.current,Z=l.current;if(!re||!Z)return;const ee=()=>{const q=Z.clientWidth,X=Z.clientHeight,ae=re.naturalWidth,je=re.naturalHeight;if(!ae||!je||!q||!X)return;const ke=Math.min(q/ae,X/je),E=Math.max(q/ae,X/je)/ke;E>1.01&&(j(E),I(E),z.current=E),W.current=!0};re.complete&&re.naturalWidth?ee():re.addEventListener("load",ee,{once:!0})},[G,g]);const xe=.5;i.useEffect(()=>{L<=xe&&(U(0),N(0))},[L,xe]);const de=(re,Z,ee)=>{if(ee<=xe)return{x:0,y:0};const q=(ee-1)/(2*ee)*100,X=(ee-1)/(2*ee)*100;return{x:Math.max(-q,Math.min(q,re)),y:Math.max(-X,Math.min(X,Z))}},be=(re,Z)=>{if(!u.current)return null;const ee=u.current.getBoundingClientRect();return!ee.width||!ee.height?null:{nx:Math.max(0,Math.min(1,(re-ee.left)/ee.width)),ny:Math.max(0,Math.min(1,(Z-ee.top)/ee.height))}},he=(re,Z,ee)=>{const q=l.current;if(!q)return;const X=q.getBoundingClientRect(),ae=++y.current;p(je=>[...je,{id:ae,x:re-X.left,y:Z-X.top,type:ee}]),setTimeout(()=>p(je=>je.filter(ke=>ke.id!==ae)),600)},Y=(re,Z,ee)=>{const q=u.current,X=l.current;if(!q||!X)return;const ae=q.getBoundingClientRect(),je=X.getBoundingClientRect(),ke=q.naturalWidth||ae.width,te=q.naturalHeight||ae.height,E=ke/te,ve=ae.width/ae.height;let Ce,we,Pe,Le;E>ve?(Ce=ae.width,we=ae.width/E,Pe=0,Le=(ae.height-we)/2):(we=ae.height,Ce=ae.height*E,Pe=(ae.width-Ce)/2,Le=0);const Oe=ae.left-je.left+Pe+Ce*re,ze=ae.top-je.top+Le+we*Z,tt=++y.current;p(Xe=>[...Xe,{id:tt,x:Oe,y:ze,type:ee}]),setTimeout(()=>p(Xe=>Xe.filter(Ye=>Ye.id!==tt)),600)},oe=async re=>{var ee;const Z=be(re.clientX,re.clientY);if(Z){d(`Click: ${Math.round(Z.nx*100)}%, ${Math.round(Z.ny*100)}%`),he(re.clientX,re.clientY,"left"),(ee=c.current)==null||ee.focus();try{const q=await e("input_click",{nx:Z.nx,ny:Z.ny});q!=null&&q.success||t(`❌ Click failed: ${q==null?void 0:q.error}`)}catch(q){t(`❌ Click error: ${q.message||q}`)}}},J=async(re,Z,ee,q=0)=>{try{await e("input_key",{type:ee?"char":"keyDown",key:re,code:Z,text:ee?re:void 0,unmodifiedText:ee?re:void 0,modifiers:q})}catch(X){t(`❌ Key error: ${X.message||X}`)}},ue=async re=>{if(re.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(re.key)&&re.preventDefault();let ee=0;re.altKey&&(ee|=1),re.ctrlKey&&(ee|=2),re.metaKey&&(ee|=4),re.shiftKey&&(ee|=8),d(`Key: ${re.key}`),await J(re.key,re.code,re.key.length===1,ee)},le=async re=>{if(re.key==="Enter"){if(re.nativeEvent.isComposing)return;if(h){const Z=h;f(""),d(`IME Sent: ${Z}`);try{const ee=await e("input_type",{text:Z});ee!=null&&ee.success||t(`❌ IME error: ${ee==null?void 0:ee.error}`)}catch(ee){t(`❌ IME error: ${ee.message}`)}}else d("Key: Enter"),await J("Enter","Enter",!1)}};i.useEffect(()=>{const re=c.current;if(!re)return;const Z=ee=>{var q;if((q=u.current)!=null&&q.contains(ee.target)){ee.preventDefault();const X=Date.now();if(X-A.current<40)return;A.current=X;const ae=be(ee.clientX,ee.clientY);if(!ae)return;d(`Scroll: ${Math.round(ee.deltaY)}`),e("input_wheel",{nx:ae.nx,ny:ae.ny,deltaX:Math.round(ee.deltaX),deltaY:Math.round(ee.deltaY)}).catch(()=>{})}};return re.addEventListener("wheel",Z,{passive:!1}),()=>re.removeEventListener("wheel",Z)},[e]);const{cursorPos:Se,handleToggleInputMode:ie,handleZoomReset:pe}=Pu({containerRef:c,viewportRef:l,imgRef:u,inputMode:M,setInputMode:C,minZoom:xe,zoomRef:z,panXRef:$,panYRef:B,setPanX:U,setPanY:N,setZoom:I,lastWheelTimeRef:A,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:Y,clampPan:de,isMobile:g,mobileFillZoom:S});return s.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ue,onContextMenu:re=>re.preventDefault(),onFocus:()=>w(!0),onBlur:()=>w(!1),tabIndex:0,children:[s.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[G?s.jsx("img",{ref:u,src:G,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${L}) translate(${D}%, ${K}%)`,transformOrigin:"center center",cursor:M==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:oe,onContextMenu:re=>re.preventDefault(),onDragStart:re=>re.preventDefault()}):s.jsx(Ru,{waitingLabel:me,waitingHint:ne,transportType:o}),M==="mouse"&&G&&s.jsx(Au,{cursorPos:Se,viewportRef:l,imgRef:u}),k.map(re=>{const ee={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[re.type];return s.jsxs("div",{style:{position:"absolute",left:re.x,top:re.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ee}, 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(${ee}, 0.9)`,boxShadow:`0 0 12px rgba(${ee}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},re.id)})]}),s.jsx(Lu,{inputMode:M,onToggleInputMode:ie,isImeOpen:v,setIsImeOpen:R,isMenuOpen:x,setIsMenuOpen:b,imeText:h,setImeText:f,handleImeSubmit:le,isConnActive:V,zoom:L,isMobile:g,mobileFillZoom:S,onZoomOut:()=>I(re=>Math.max(.5,re-.25)),onZoomReset:pe,onZoomIn:()=>I(re=>Math.min(5,re+.25)),transportType:o,screenshotUsage:a,lastActionStatus:m}),s.jsx("style",{children:`
2
+ var ud=Object.defineProperty;var md=(e,t,r)=>t in e?ud(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ve=(e,t,r)=>md(e,typeof t!="symbol"?t+"":t,r);import{r as i,j as s,M as Sa,a as fd,b as pd,c as hd,u as Ls,R as kt,d as Zs,t as xd,e as bd,D as gd,f as Zn,g as ea,h as Na,i as yd,k as vd,B as wd,l as kd,m as Yt,N as ta,n as jd}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 Sd(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 Ss=Sd();function go(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 Nd(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Cd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ai(e,t){var m;if(!e)return t??null;if(!t)return e??null;const r=Cd(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:void 0,a=e.status==="waiting_approval"||Array.isArray((m=e.activeModal)==null?void 0:m.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),u={...t,...e,activeModal:l,inputContent:e.inputContent??t.inputContent};return r?{...u,messages:c}:u}function zs(e,t){const r=Nd(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:Ai(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 Li(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?zs(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 yo(e){return!!e&&typeof e=="object"&&"text"in e}function Ca(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:yo(o)?String(o.text||""):"").join(r):yo(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Bt(e){return Ca(e,{normalizeWhitespace:!0})}const Ri=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}),_i=i.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function vo(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 Pi(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,u=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),o&&(n.serverVersion=o),u&&(n.versionUpdateReason=u),a&&o&&a===o?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||c&&a&&o&&a!==o)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function Td(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 bn(e){if(!e||typeof e!="object")return"";const t=e,r=Td(Bt(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 Md(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=bn(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:bn(e[0]),last:bn(e[e.length-1])}}function sa(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function ra(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(sa(e)&&sa(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)ra(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"&&ra(n[c],a[c],r)}function Gs(e,t){return Array.isArray(e)?e.map(r=>Gs(r,t)):!e||typeof e!="object"?e:sa(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Md(a,t):Gs(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Gs(n,t)]))}function Id(e,t){try{const r=new WeakSet;return ra(e,t,r),JSON.stringify(Gs(e,r))===JSON.stringify(Gs(t,r))}catch{return!1}}function na(e,t,r){return Id(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Di(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Ad(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function wo(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,o=Li(e.childSessions,t.childSessions,{preserveMissing:n}),c=Ai(t.activeChat,e.activeChat);return Pi(e,t,{...e,...t,chats:a,childSessions:o,activeChat:c,_lastUpdate:r})}function Ld(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=Li(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"])Ad(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Rd(e,t,r,n){const a=Ld(e,t,n),o=Object.keys(a).length>0?Pi(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return na(e,o,r)}function _d(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=Di(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 Pd(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 Dd(e,t,r,n){return!!(r.has(t)&&e.transport&&!n.has(t))}function Ed(e,t,r){var d,h;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(f=>({...f,_lastUpdate:n}));const o=new Map;for(const f of t)o.set(f.id,f);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:u,daemonIdsWithAuthoritativeSessionList:m}=_d(e);for(const f of e){const v=o.get(f.id);if(!v){o.set(f.id,{...f,_lastUpdate:n});continue}const j=vo(f),p=vo(v),y=Di(f),x=!a.has(y);if(j>p){const R=wo(v,f,n,x);o.set(f.id,na(v,R,n));continue}if(j<p){o.set(f.id,Rd(v,f,n,x));continue}const b=f.timestamp||n,w=v._lastUpdate||v.timestamp||0;if(b>=w){const R=wo(v,f,n,x);o.set(f.id,na(v,R,n));continue}(d=f.chats)!=null&&d.length&&!((h=v.chats)!=null&&h.length)&&o.set(f.id,{...v,chats:f.chats})}for(const[f,v]of o){const j=v.daemonId||f.split(":")[0];if(!l.has(j))continue;if(a.has(j)&&m.has(j)&&!c.has(f)){o.delete(f);continue}const p=n-(v._lastUpdate||v.timestamp||0);Pd(v,j,p,c,a,u)&&o.delete(f)}for(const[f,v]of o){const j=v.daemonId||f.split(":")[0];if(Dd(v,j,l,u))continue;n-(v._lastUpdate||v.timestamp||0)>3e5&&v.status!=="online"&&o.delete(f)}return Array.from(o.values())}function $d(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 Bd({children:e,connectionOverrides:t}){const[r,n]=i.useState([]),[a,o]=i.useState(!1),[c,l]=i.useState([]),[u,m]=i.useState(void 0),d=i.useRef(r);i.useEffect(()=>{d.current=r},[r]);const h=i.useCallback((x,b)=>{n(w=>{let R=!1;const g=w.map(I=>I.id!==x||I.chats===b?I:(R=!0,{...I,chats:b}));return R?g:w})},[]),f=i.useCallback((x,b)=>{n(w=>{const R=w.length===0?x:Ed(x,w,b),g=!$d(w,R);return g&&Ss.record({kind:"dashboard.entries_applied",payload:{incoming:go(x),next:go(R)}}),g?R:w})},[]),v=i.useCallback(()=>o(!0),[]),j=i.useMemo(()=>({injectEntries:f,markLoaded:v,getIdes:()=>d.current}),[f,v]),p=t,y=i.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(p==null?void 0:p.wsStatus)??"connected",isConnected:(p==null?void 0:p.isConnected)??!0,connectionStates:(p==null?void 0:p.connectionStates)??{},connectionTransports:(p==null?void 0:p.connectionTransports)??{},showReconnected:(p==null?void 0:p.showReconnected)??!1,retryConnection:p==null?void 0:p.retryConnection,retryServerConnection:p==null?void 0:p.retryServerConnection,connectionLoginUrl:p==null?void 0:p.connectionLoginUrl,isP2PActive:(p==null?void 0:p.isP2PActive)??!1,p2pStates:(p==null?void 0:p.p2pStates)??{},userRole:p==null?void 0:p.userRole,connectionRetryStatuses:p==null?void 0:p.connectionRetryStatuses,userName:u,setUserName:m}),[r,h,a,c,p==null?void 0:p.wsStatus,p==null?void 0:p.isConnected,p==null?void 0:p.connectionStates,p==null?void 0:p.connectionTransports,p==null?void 0:p.showReconnected,p==null?void 0:p.retryConnection,p==null?void 0:p.retryServerConnection,p==null?void 0:p.connectionLoginUrl,p==null?void 0:p.isP2PActive,p==null?void 0:p.p2pStates,p==null?void 0:p.userRole,p==null?void 0:p.connectionRetryStatuses,u]);return s.jsx(_i.Provider,{value:j,children:s.jsx(Ri.Provider,{value:y,children:e})})}function ls(){return i.useContext(Ri)}function er(){return i.useContext(_i)}function Ei(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 u=r==null?void 0:r(),m=a(l),d=l.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return u&&d.searchParams.set("token",u),!l.startsWith("http")&&!t?`${d.pathname}${d.search}${d.hash}`:d.toString()}async function c(l,u={}){const m={"Content-Type":"application/json",...u.headers||{}},d=r==null?void 0:r();d&&(m.Authorization=`Bearer ${d}`);const h=a(l),f=new AbortController,v=setTimeout(()=>f.abort(),15e3);try{const j=await fetch(h,{...u,headers:m,signal:f.signal});if(j.status===401)throw n==null||n(),new Error("Unauthorized");if(!j.ok){const p=await j.json().catch(()=>({error:j.statusText}));throw new Error(p.error||`API Error: ${j.status}`)}return j.json()}finally{clearTimeout(v)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,u,m={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:m})}),execTerminal:(l,u,m)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:m})}),sendAgentMessage:(l,u,m)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:m})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,m)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:m?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,u,m={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:m})}),getMuxEventsUrl:l=>o(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>o(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Kd=Ei({baseUrl:"http://localhost:3847"}),Od=i.createContext(Kd);function Wd({client:e,children:t}){return s.jsx(Od.Provider,{value:e,children:t})}const Hd={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},$i=i.createContext(Hd);function Fd({value:e,children:t}){return s.jsx($i.Provider,{value:e,children:t})}function vt(){return i.useContext($i)}function Ud(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 Bi(e){return e?Ud([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),zd(e.content)]):""}const Ke={size:18};function Ki({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Ta({size:e=Ke.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 ds({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Oi({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Vd({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Gd({size:e=Ke.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 Wi({size:e=Ke.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function qd({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 tn({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Hi({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Yd({size:e=Ke.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 Ht({size:e=Ke.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 Nt({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Ma({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Xd({size:e=Ke.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Ns({size:e=Ke.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 or({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 tr({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 sr({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Fi({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Ui({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 zi({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Jd({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Ia({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Qd({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Aa({size:e=Ke.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 Vi({size:e=Ke.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function wt({size:e=Ke.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 Zd({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 eu({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 tu({size:e=Ke.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 su({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 sn({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 ru({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 nu({size:e=Ke.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 au({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 ou({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 iu({size:e=Ke.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 cu({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 lu({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 du({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 uu({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 mu({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 fu({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 pu({size:e=Ke.size,className:t}){return s.jsxs("svg",{width: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 Gi=[fd,{singleTilde:!1}],qi=[Gi,pd,hd],hu=[Gi],La=200,xu=80,ko=650,Es=new Map;function Hr(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function bu(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}:${Bi(n)}`}function gu(e,t,r,n){return e||!t?!1:Hr(r,n)}function yu({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=xu,bottomThresholdPx:a=La}){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 vu(e){return yu({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Vs(e,t=La){return!!e&&e.fromBottom>=t}function wu(e,t){return Hr(e,t)?!Vs(e):!0}function ku({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function ju({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function gn(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function Yi(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Su(e,t,r){return Number(e.receivedAt||r[Fr(e,t)]||0)||0}function Xi(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Nu(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function fr(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 yn(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 jo(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Xi(e)?s.jsx(Sa,{remarkPlugins:qi,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function pr({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:jo(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=yn(r);return a?s.jsx("img",{src:a,alt:fr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=yn(r);return a?s.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=yn(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:fr(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||fr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=fr(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}),jo(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 Fr(e,t){const r=e,n=Ca(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 Cu=i.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Sa,{remarkPlugins:hu,children:t.text}),s.jsx("span",{className:"action-time",children:Yi(t.timestamp)})]})},(e,t)=>e.log===t.log),Tu=i.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:c,onToggleTextExpanded:l}){var I,C,S;const u=(t.role||"").toLowerCase(),m=u==="user"||u==="human",d=t.kind||(u==="tool"?"tool":"standard"),h=Nu(t.content)?t.content:null,f=!!(h!=null&&h.some(k=>k.type!=="text")),v=Ca(t.content,{joiner:`
4
+ `});if(d==="thought"){const k=typeof((I=t.meta)==null?void 0:I.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(tu,{size:13}),s.jsx("span",{children:k})]}),s.jsx("div",{className:"chat-msg-body",children:v})]})}if(d==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),f&&h?s.jsx("div",{className:"tool-text w-full",children:s.jsx(pr,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:v})]});if(d==="terminal"){const k=(C=t.meta)!=null&&C.isRunning?"⏳":"✅",W=typeof((S=t.meta)==null?void 0:S.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:k}),s.jsx("span",{children:W})]}),f&&h?s.jsx("div",{className:"chat-msg-body",children:s.jsx(pr,{parts:h,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:v})]})}if(d==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:f&&h?s.jsx(pr,{parts:h,renderAsPreformatted:!1}):v.slice(0,100)});const j=t.meta,y=(typeof(j==null?void 0:j.renderMode)=="string"?j.renderMode.trim():"")==="preformatted",x=v,b=!1,w=x,R=y,g=!R&&Xi(w);return s.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${m?"self-end":"self-start"}`,children:(x||f||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${x||f?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:m?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:Yi(r)})]}),(x||f)&&s.jsx("div",{className:"chat-markdown",children:f&&h?s.jsx(pr,{parts:h,renderAsPreformatted:R}):R?s.jsx("pre",{className:"chat-preformatted",children:w}):g?s.jsx(Sa,{remarkPlugins:qi,children:w}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:w})}),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),Mu=i.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},lastMessageHash:m,emptyState:d,onLoadMore:h,isLoadingMore:f,hasMoreHistory:v,hiddenLiveCount:j=0,loadError:p,scrollToBottomRequestNonce:y,isVisible:x=!0},b){const w=i.useRef(null),R=i.useRef(null),g=i.useRef(null),I=i.useRef(0),C=i.useRef(""),S=i.useRef(""),k=i.useRef(!1),W=i.useRef(null),L=i.useRef(!1),M=i.useRef(null),E=i.useRef(!1),[U,K]=i.useState(new Set),[N,A]=i.useState({showTop:!1,showBottom:!1}),z=i.useRef(!1),$=i.useRef(!1),B=i.useRef(x),G=i.useRef(x),V=i.useRef(null);G.current=x;const me=()=>{const q=w.current;return q?q.scrollHeight-q.scrollTop-q.clientHeight<La:!0},ae=i.useCallback(()=>{const q=w.current,X=q?vu(q):{showTop:!1,showBottom:!1};A(re=>re.showTop===X.showTop&&re.showBottom===X.showBottom?re:X)},[]),xe=i.useCallback((q="auto")=>{var re;const X=w.current;X&&(X.scrollTo({top:X.scrollHeight,behavior:q}),(re=X.ownerDocument.defaultView)==null||re.requestAnimationFrame(()=>ae()))},[ae]),de=i.useCallback((q="auto")=>{var re;const X=w.current;X&&(X.scrollTo({top:0,behavior:q}),(re=X.ownerDocument.defaultView)==null||re.requestAnimationFrame(()=>ae()))},[ae]),be=i.useCallback(()=>{var we;const q=w.current,X=(we=window.getSelection)==null?void 0:we.call(window);if(!q||!X||X.rangeCount===0||X.isCollapsed){E.current=!1;return}const re=X.anchorNode,je=X.focusNode;E.current=!!(re&&je&&q.contains(re)&&q.contains(je))},[]),he=bu(t,m),Y=i.useCallback(()=>{const q=w.current;if(!q||!l||!G.current)return;const X={top:q.scrollTop,fromBottom:Math.max(0,q.scrollHeight-q.scrollTop-q.clientHeight),messageFingerprint:he};V.current={contextKey:l,snapshot:X},Es.set(l,X)},[l,he]),oe=i.useCallback((q="auto")=>{W.current!=null&&cancelAnimationFrame(W.current),W.current=requestAnimationFrame(()=>{W.current=null,xe(q)})},[xe]),J=i.useCallback(()=>{z.current=!1,L.current=!0,$.current=!0,M.current!=null&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{L.current=!1,M.current=null},ko)},[]);i.useEffect(()=>{const q=!k.current,X=S.current!==l;if(S.current=l,q||X){k.current=!0;const je=l?Es.get(l):null,we=!!je&&Hr(je,he);z.current=we?Vs(je):!1,L.current=wu(je,he),E.current||(we?requestAnimationFrame(()=>{const te=w.current;te&&(gn(te,je),z.current=Vs(je),ae(),$.current=!0)}):oe("auto")),I.current=t.length,C.current=he;return}t.length>I.current;const re=he!==C.current;ku({hasSelection:E.current,userScrolledUp:z.current,hasChatContentChanged:re})&&oe("auto"),I.current=t.length,C.current=he},[he,l,t.length,oe,ae]),i.useEffect(()=>{y&&(J(),E.current||oe("auto"))},[J,oe,y]),i.useEffect(()=>{const q=B.current;q&&!x&&Y(),G.current=x,B.current=x;const X=l?Es.get(l):null;if(gu(q,x,X,he)){if(!X)return;z.current=Vs(X),L.current=!1,E.current||requestAnimationFrame(()=>{const re=w.current;re&&(gn(re,X),ae())});return}},[x,l,he,J,Y,oe,ae]),i.useEffect(()=>()=>{const q=V.current;q&&Es.set(q.contextKey,q.snapshot),W.current!=null&&cancelAnimationFrame(W.current),M.current!=null&&window.clearTimeout(M.current)},[]),i.useEffect(()=>{const q=R.current,X=w.current;if(!q||!X)return;const re=()=>{M.current!=null&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{L.current=!1,M.current=null},ko)},je=new ResizeObserver(()=>{ae();const we=L.current;ju({hasSelection:E.current,userScrolledUp:z.current,contextAutoScrollActive:we})&&(oe("auto"),we&&re())});return je.observe(q),X!==q&&je.observe(X),()=>{je.disconnect(),M.current!=null&&(window.clearTimeout(M.current),M.current=null)}},[oe,l,ae]),i.useImperativeHandle(b,()=>({scrollToBottom:(q="smooth")=>{xe(q)}}),[xe]),i.useEffect(()=>{const q=w.current;if(!q)return;let X;const re=()=>{Y(),clearTimeout(X),X=setTimeout(()=>{z.current=!me(),ae()},50)};return q.addEventListener("scroll",re,{passive:!0}),()=>{q.removeEventListener("scroll",re),clearTimeout(X)}},[Y,ae]),i.useEffect(()=>(document.addEventListener("selectionchange",be),()=>document.removeEventListener("selectionchange",be)),[be]);const ue=i.useRef(0),le=i.useRef(!1);i.useEffect(()=>{const q=w.current;if(!q||!le.current||ue.current===0)return;const X=q.scrollHeight-ue.current;X>0&&(q.scrollTop=X),ae(),Y(),ue.current=0,le.current=!1},[t.length,Y,ae]),i.useEffect(()=>{if($.current||!l)return;const q=Es.get(l),X=w.current;if(!(!q||!X)){if(!Hr(q,he)){xe("auto"),$.current=!0;return}gn(X,q),z.current=Vs(q),ae(),$.current=!0}},[l,he,t.length,xe,ae]);const Se=()=>{const q=w.current;q&&(ue.current=q.scrollHeight),le.current=!0,h==null||h()},ie=()=>{z.current=!0,de("smooth"),Y()},pe=()=>{J(),xe("smooth"),Y()},ne=i.useMemo(()=>{const q=t.map((we,te)=>({type:"message",data:we,index:te,ts:Su(we,te,u)}));if(!r||r.length===0)return q;const X=[...r].sort((we,te)=>we.timestamp-te.timestamp).map((we,te)=>({type:"action",data:we,index:te,ts:we.timestamp})),re=[];let je=0;for(const we of q){for(;je<X.length&&we.ts>0&&X[je].ts<we.ts;)re.push(X[je++]);re.push(we)}for(;je<X.length;)re.push(X[je++]);return re},[t,r,u]),Z=j>0||!!v,ee=j>0?`↑ Show ${Math.min(j,80)} earlier messages${j>80?` (${j} hidden)`:""}`:p?`↻ ${p}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:w,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:R,className:"chat-container-content",children:[f&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),Z&&!f&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:Se,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${p&&j===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:ee})}),ne.length===0&&!Z&&(d||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ne.map(q=>{if(q.type==="action"){const ve=q.data;return s.jsx(Cu,{log:ve},`action-${q.index}`)}const X=q.data,re=q.index,je=Fr(X,re),we=X.receivedAt||u[je],te=`${l}-${je}`,D=U.has(te);return s.jsx(Tu,{message:X,receivedAt:we,agentName:n,userName:a,isCliMode:o,isTextExpanded:D,onToggleTextExpanded:()=>K(ve=>{const Ce=new Set(ve);return D?Ce.delete(te):Ce.add(te),Ce})},`msg-${je}`)}),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})]})}),(N.showTop||N.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[N.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:ie,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),N.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:pe,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Iu=i.memo(Mu,(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),Au="modulepreload",Lu=function(e){return"/"+e},So={},Ru=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(u=>{if(u=Lu(u),u in So)return;So[u]=!0;const m=u.endsWith(".css"),d=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const h=document.createElement("link");if(h.rel=m?"stylesheet":Au,m||(h.as="script"),h.crossOrigin="",h.href=u,l&&h.setAttribute("nonce",l),document.head.appendChild(h),m)return new Promise((f,v)=>{h.addEventListener("load",f),h.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${u}`)))})}))}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 No=!1;const Ji=i.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},c)=>{const l=i.useRef(null),[u,m]=i.useState(null),d=i.useRef([]),h=i.useRef(!1),f=i.useRef(!1),v=i.useRef(!1),j=i.useRef(!1),p=()=>{const y=l.current;if(y){h.current&&(y.clear(),h.current=!1);for(const x of d.current)y.write(x.data,x.onProcessed);d.current=[],f.current&&(y.fit(),f.current=!1),v.current&&(y.bumpResize(),v.current=!1),j.current&&(y.scrollToTop(),j.current=!1)}};return i.useImperativeHandle(c,()=>({write:(y,x)=>{l.current?l.current.write(y,x):d.current.push({data:y,onProcessed:x})},clear:()=>{l.current?l.current.clear():(d.current=[],h.current=!0)},reset:()=>{l.current&&typeof l.current.reset=="function"?l.current.reset():(d.current=[],h.current=!0)},resize:(y,x)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(y,x)},fit:()=>{l.current?l.current.fit():f.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():v.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():j.current=!0},getSelection:()=>{var y,x;return((x=(y=l.current)==null?void 0:y.getSelection)==null?void 0:x.call(y))||""},getVisibleText:()=>{var y,x;return((x=(y=l.current)==null?void 0:y.getVisibleText)==null?void 0:x.call(y))||""}}),[]),i.useEffect(()=>{u&&p()},[u]),i.useEffect(()=>{let y=!1;return Ru(()=>import("./terminal-DbJP_JGY.js"),__vite__mapDeps([0,1,2])).then(x=>{No||(No=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),y||m(()=>x.GhosttyTerminalView)}).catch(x=>{console.error("[CliTerminal] failed to load terminal renderer",x)}),()=>{y=!0}},[]),u?s.jsx(u,{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"}})});Ji.displayName="CliTerminal";function hr({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 Co({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 _u({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,u=c/l,m=a.width/a.height;let d,h,f,v;u>m?(d=a.width,h=a.width/u,f=0,v=(a.height-h)/2):(h=a.height,d=a.height*u,f=(a.width-d)/2,v=0);const j=a.left-o.left+f+d*e.nx,p=a.top-o.top+v+h*e.ny,y=Math.max(8,Math.min(o.width-8,j)),x=Math.max(8,Math.min(o.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:y-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 Pu({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:m,zoom:d,isMobile:h,mobileFillZoom:f,onZoomOut:v,onZoomReset:j,onZoomIn:p,transportType:y,screenshotUsage:x,lastActionStatus:b}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:w=>w.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{n(w=>!w),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:w=>w.stopPropagation(),onChange:w=>l(w.target.value),onKeyDown:w=>{u(w)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{o(w=>!w),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:m?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),d>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),y==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),y==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),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:w=>w.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",d<=(h?f:1)+.01?h?"FILL":"FIT":`${Math.round(d*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:w=>{w.stopPropagation(),v()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:w=>{w.stopPropagation(),j()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:h?"FILL":"FIT"}),s.jsx("button",{onClick:w=>{w.stopPropagation(),p()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function Du({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 Eu(){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 To(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 ir(e,t){const r=i.useRef(null),n=i.useRef(0);i.useEffect(()=>{if(!Eu())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,To(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,To(t[c])]))}),r.current=t})}function $u({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:c,panXRef:l,panYRef:u,setPanX:m,setPanY:d,setZoom:h,lastWheelTimeRef:f,onAction:v,setLastActionStatus:j,spawnRippleFromNormalized:p,clampPan:y,isMobile:x,mobileFillZoom:b}){const[w,R]=i.useState(null),g=i.useRef(null),I=i.useRef(null),C=i.useRef(null),S=i.useRef(!1),k=i.useRef(null),W=i.useRef(0),L=i.useRef(null),M=i.useRef(1),E=i.useRef({x:0,y:0}),U=i.useRef(!1),K=i.useRef(n),N=i.useRef(v),A=30,z=550,$=18,B=60,G=400,V=12,me=()=>{if(g.current)return;const de={nx:.5,ny:.5};g.current=de,R(de)};return i.useEffect(()=>{K.current=n,n==="mouse"&&me()},[n]),i.useEffect(()=>{N.current=v},[v]),i.useEffect(()=>{const de=e.current;if(!de)return;const be=le=>{if(!r.current)return null;const Se=r.current.getBoundingClientRect();return!Se.width||!Se.height?null:{nx:Math.max(0,Math.min(1,(le.clientX-Se.left)/Se.width)),ny:Math.max(0,Math.min(1,(le.clientY-Se.top)/Se.height))}},he=(le,Se)=>{if(!r.current)return{dnx:0,dny:0};const ie=r.current,pe=ie.getBoundingClientRect(),ne=ie.naturalWidth||pe.width,Z=ie.naturalHeight||pe.height,ee=ne/Z,q=pe.width/pe.height;let X,re;return ee>q?(X=pe.width,re=pe.width/ee):(re=pe.height,X=pe.height*ee),{dnx:le/X,dny:Se/re}},Y=(le,Se,ie)=>{if(ie<=1.05)return;const pe=-(le-.5)*100,ne=-(Se-.5)*100,Z=y(pe,ne,ie);(Math.abs(Z.x-l.current)>.1||Math.abs(Z.y-u.current)>.1)&&(m(Z.x),d(Z.y),l.current=Z.x,u.current=Z.y)},oe=le=>{const Se=t.current;if(Se&&le.target instanceof Node&&Se.contains(le.target))le.preventDefault();else return;if(le.touches.length===1){const ie=le.touches[0];I.current={x:ie.clientX,y:ie.clientY,time:Date.now()},C.current={x:ie.clientX,y:ie.clientY},U.current||(S.current=!1),k.current=setTimeout(()=>{if(!S.current&&!U.current)if(S.current=!0,K.current==="mouse"){const pe=g.current||{nx:.5,ny:.5};j("Right Click"),p(pe.nx,pe.ny,"right"),N.current("input_click",{...pe,button:"right"}).catch(()=>{})}else{const pe=be(ie);pe&&(j("Right Click"),p(pe.nx,pe.ny,"right"),N.current("input_click",{...pe,button:"right"}).catch(()=>{}))}},500);return}if(le.touches.length===2){k.current&&clearTimeout(k.current),S.current=!0,U.current=!0;const ie=le.touches[1].clientX-le.touches[0].clientX,pe=le.touches[1].clientY-le.touches[0].clientY;L.current=Math.sqrt(ie*ie+pe*pe),M.current=c.current,E.current={x:(le.touches[0].clientX+le.touches[1].clientX)/2,y:(le.touches[0].clientY+le.touches[1].clientY)/2}}},J=le=>{const Se=t.current;if(Se&&le.target instanceof Node&&Se.contains(le.target)&&le.preventDefault(),le.touches.length===1&&C.current){const ie=le.touches[0],pe=ie.clientX-C.current.x,ne=ie.clientY-C.current.y;if(!S.current&&I.current){const Z=ie.clientX-I.current.x,ee=ie.clientY-I.current.y;Math.sqrt(Z*Z+ee*ee)>8&&(S.current=!0,k.current&&clearTimeout(k.current))}if(S.current)if(K.current==="mouse"){const Z=he(pe,ne),ee=g.current||{nx:.5,ny:.5},q=Math.max(0,Math.min(1,ee.nx+Z.dnx)),X=Math.max(0,Math.min(1,ee.ny+Z.dny));g.current={nx:q,ny:X},R({nx:q,ny:X}),j(`Cursor: ${Math.round(q*100)}%, ${Math.round(X*100)}%`),Y(q,X,c.current);const re=Date.now();re-f.current>=30&&(f.current=re,N.current("input_mouseMoved",{nx:q,ny:X}).catch(()=>{}))}else if(c.current>1){const Z=t.current;if(Z){const ee=Z.clientWidth,q=Z.clientHeight,X=l.current+pe/ee*100,re=u.current+ne/q*100,je=y(X,re,c.current);m(je.x),d(je.y),l.current=je.x,u.current=je.y}}else{const Z=be(ie);if(Z){const ee=Date.now();ee-f.current>=40&&(f.current=ee,j("Scroll"),N.current("input_wheel",{nx:Z.nx,ny:Z.ny,deltaX:Math.round(-pe*2.5),deltaY:Math.round(-ne*2.5)}).catch(()=>{}))}}C.current={x:ie.clientX,y:ie.clientY};return}if(le.touches.length===2&&L.current!==null){const ie=le.touches[1].clientX-le.touches[0].clientX,pe=le.touches[1].clientY-le.touches[0].clientY,Z=Math.sqrt(ie*ie+pe*pe)/L.current,ee=(le.touches[0].clientX+le.touches[1].clientX)/2,q=(le.touches[0].clientY+le.touches[1].clientY)/2,X=ee-E.current.x,re=q-E.current.y,je=Math.abs(Z-1)>.03;if(K.current==="mouse"){if(je){const we=Math.max(o,Math.min(5,M.current*Z));h(we),c.current=we}else if(Math.abs(X)>2||Math.abs(re)>2){const we=g.current||{nx:.5,ny:.5},te=Date.now();te-f.current>=30&&(f.current=te,j("Scroll"),N.current("input_wheel",{nx:we.nx,ny:we.ny,deltaX:Math.round(-X*3),deltaY:Math.round(-re*3)}).catch(()=>{}))}}else{const we=Math.max(o,Math.min(5,M.current*Z));h(we),c.current=we;const te=t.current;if(te&&we>1){const D=te.clientWidth,ve=te.clientHeight,Ce=l.current+X/D*100,ke=u.current+re/ve*100,Pe=y(Ce,ke,we);m(Pe.x),d(Pe.y),l.current=Pe.x,u.current=Pe.y}}E.current={x:ee,y:q}}},ue=le=>{var Se;if(k.current&&clearTimeout(k.current),L.current=null,le.touches.length===1&&U.current){const ie=le.touches[0];I.current={x:ie.clientX,y:ie.clientY,time:Date.now()},C.current={x:ie.clientX,y:ie.clientY},S.current=!0;return}if(le.touches.length===0){if(U.current){U.current=!1,S.current=!1;return}if(le.changedTouches.length===1){const ie=le.changedTouches[0],pe=Date.now(),ne=pe-(((Se=I.current)==null?void 0:Se.time)||0),Z=I.current?ie.clientX-I.current.x:0,ee=I.current?ie.clientY-I.current.y:0,q=Math.sqrt(Z*Z+ee*ee);if(K.current==="mouse"){if(ne<A||ne>z||q>$){S.current=!1;return}const X=g.current||be(ie);X&&(j(`Click: ${Math.round(X.nx*100)}%, ${Math.round(X.ny*100)}%`),p(X.nx,X.ny,"left"),N.current("input_click",{...X}).catch(()=>{}))}else{if(S.current){S.current=!1;return}if(ne<B||ne>G||q>V){S.current=!1;return}const X=be(ie);if(!X)return;pe-W.current<300?(j("Double tap"),p(X.nx,X.ny,"double"),N.current("input_click",{...X,clickCount:2}).catch(()=>{}),W.current=0):(j(`Tap: ${Math.round(X.nx*100)}%, ${Math.round(X.ny*100)}%`),p(X.nx,X.ny,"left"),N.current("input_click",{...X}).catch(()=>{}),W.current=pe)}}S.current=!1}};return de.addEventListener("touchstart",oe,{passive:!1}),de.addEventListener("touchmove",J,{passive:!1}),de.addEventListener("touchend",ue,{passive:!1}),()=>{de.removeEventListener("touchstart",oe),de.removeEventListener("touchmove",J),de.removeEventListener("touchend",ue),k.current&&clearTimeout(k.current)}},[e,t,r,o,c,l,u,m,d,h,f,j,p,y]),{cursorPos:w,cursorPosRef:g,handleToggleInputMode:()=>{a(de=>{const be=de==="touch"?"mouse":"touch";return be==="mouse"&&me(),be})},handleZoomReset:()=>{const de=x?b:1;h(de),c.current=de,m(0),d(0),l.current=0,u.current=0}}}function Qi({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const c=i.useRef(null),l=i.useRef(null),u=i.useRef(null),[m,d]=i.useState(null),[h,f]=i.useState(""),[,v]=i.useState(!1),[j,p]=i.useState([]),y=i.useRef(0),[x,b]=i.useState(!1),[w,R]=i.useState(!1),g=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[I,C]=i.useState(g?"mouse":"touch"),[S,k]=i.useState(1),W=i.useRef(!1),[L,M]=i.useState(1),[E,U]=i.useState(0),[K,N]=i.useState(0);ir("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:I,zoom:L,panX:E,panY:K,isMenuOpen:x,isImeOpen:w});const A=i.useRef(0),z=i.useRef(L),$=i.useRef(E),B=i.useRef(K);i.useEffect(()=>{z.current=L},[L]),i.useEffect(()=>{$.current=E},[E]),i.useEffect(()=>{B.current=K},[K]),i.useEffect(()=>{var ne;(ne=c.current)==null||ne.focus()},[]);const G=r==="connected",V=n,me=G?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ae=G?"The remote stream is warming up":"Waiting for the remote stream to catch up";i.useEffect(()=>{if(!g||W.current||!V)return;const ne=u.current,Z=l.current;if(!ne||!Z)return;const ee=()=>{const q=Z.clientWidth,X=Z.clientHeight,re=ne.naturalWidth,je=ne.naturalHeight;if(!re||!je||!q||!X)return;const we=Math.min(q/re,X/je),D=Math.max(q/re,X/je)/we;D>1.01&&(k(D),M(D),z.current=D),W.current=!0};ne.complete&&ne.naturalWidth?ee():ne.addEventListener("load",ee,{once:!0})},[V,g]);const xe=.5;i.useEffect(()=>{L<=xe&&(U(0),N(0))},[L,xe]);const de=(ne,Z,ee)=>{if(ee<=xe)return{x:0,y:0};const q=(ee-1)/(2*ee)*100,X=(ee-1)/(2*ee)*100;return{x:Math.max(-q,Math.min(q,ne)),y:Math.max(-X,Math.min(X,Z))}},be=(ne,Z)=>{if(!u.current)return null;const ee=u.current.getBoundingClientRect();return!ee.width||!ee.height?null:{nx:Math.max(0,Math.min(1,(ne-ee.left)/ee.width)),ny:Math.max(0,Math.min(1,(Z-ee.top)/ee.height))}},he=(ne,Z,ee)=>{const q=l.current;if(!q)return;const X=q.getBoundingClientRect(),re=++y.current;p(je=>[...je,{id:re,x:ne-X.left,y:Z-X.top,type:ee}]),setTimeout(()=>p(je=>je.filter(we=>we.id!==re)),600)},Y=(ne,Z,ee)=>{const q=u.current,X=l.current;if(!q||!X)return;const re=q.getBoundingClientRect(),je=X.getBoundingClientRect(),we=q.naturalWidth||re.width,te=q.naturalHeight||re.height,D=we/te,ve=re.width/re.height;let Ce,ke,Pe,Le;D>ve?(Ce=re.width,ke=re.width/D,Pe=0,Le=(re.height-ke)/2):(ke=re.height,Ce=re.height*D,Pe=(re.width-Ce)/2,Le=0);const Oe=re.left-je.left+Pe+Ce*ne,ze=re.top-je.top+Le+ke*Z,tt=++y.current;p(Xe=>[...Xe,{id:tt,x:Oe,y:ze,type:ee}]),setTimeout(()=>p(Xe=>Xe.filter(Ye=>Ye.id!==tt)),600)},oe=async ne=>{var ee;const Z=be(ne.clientX,ne.clientY);if(Z){d(`Click: ${Math.round(Z.nx*100)}%, ${Math.round(Z.ny*100)}%`),he(ne.clientX,ne.clientY,"left"),(ee=c.current)==null||ee.focus();try{const q=await e("input_click",{nx:Z.nx,ny:Z.ny});q!=null&&q.success||t(`❌ Click failed: ${q==null?void 0:q.error}`)}catch(q){t(`❌ Click error: ${q.message||q}`)}}},J=async(ne,Z,ee,q=0)=>{try{await e("input_key",{type:ee?"char":"keyDown",key:ne,code:Z,text:ee?ne:void 0,unmodifiedText:ee?ne:void 0,modifiers:q})}catch(X){t(`❌ Key error: ${X.message||X}`)}},ue=async ne=>{if(ne.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ne.key)&&ne.preventDefault();let ee=0;ne.altKey&&(ee|=1),ne.ctrlKey&&(ee|=2),ne.metaKey&&(ee|=4),ne.shiftKey&&(ee|=8),d(`Key: ${ne.key}`),await J(ne.key,ne.code,ne.key.length===1,ee)},le=async ne=>{if(ne.key==="Enter"){if(ne.nativeEvent.isComposing)return;if(h){const Z=h;f(""),d(`IME Sent: ${Z}`);try{const ee=await e("input_type",{text:Z});ee!=null&&ee.success||t(`❌ IME error: ${ee==null?void 0:ee.error}`)}catch(ee){t(`❌ IME error: ${ee.message}`)}}else d("Key: Enter"),await J("Enter","Enter",!1)}};i.useEffect(()=>{const ne=c.current;if(!ne)return;const Z=ee=>{var q;if((q=u.current)!=null&&q.contains(ee.target)){ee.preventDefault();const X=Date.now();if(X-A.current<40)return;A.current=X;const re=be(ee.clientX,ee.clientY);if(!re)return;d(`Scroll: ${Math.round(ee.deltaY)}`),e("input_wheel",{nx:re.nx,ny:re.ny,deltaX:Math.round(ee.deltaX),deltaY:Math.round(ee.deltaY)}).catch(()=>{})}};return ne.addEventListener("wheel",Z,{passive:!1}),()=>ne.removeEventListener("wheel",Z)},[e]);const{cursorPos:Se,handleToggleInputMode:ie,handleZoomReset:pe}=$u({containerRef:c,viewportRef:l,imgRef:u,inputMode:I,setInputMode:C,minZoom:xe,zoomRef:z,panXRef:$,panYRef:B,setPanX:U,setPanY:N,setZoom:M,lastWheelTimeRef:A,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:Y,clampPan:de,isMobile:g,mobileFillZoom:S});return s.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ue,onContextMenu:ne=>ne.preventDefault(),onFocus:()=>v(!0),onBlur:()=>v(!1),tabIndex:0,children:[s.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[V?s.jsx("img",{ref:u,src:V,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${L}) translate(${E}%, ${K}%)`,transformOrigin:"center center",cursor:I==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:oe,onContextMenu:ne=>ne.preventDefault(),onDragStart:ne=>ne.preventDefault()}):s.jsx(Du,{waitingLabel:me,waitingHint:ae,transportType:o}),I==="mouse"&&V&&s.jsx(_u,{cursorPos:Se,viewportRef:l,imgRef:u}),j.map(ne=>{const ee={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ne.type];return s.jsxs("div",{style:{position:"absolute",left:ne.x,top:ne.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ee}, 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(${ee}, 0.9)`,boxShadow:`0 0 12px rgba(${ee}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ne.id)})]}),s.jsx(Pu,{inputMode:I,onToggleInputMode:ie,isImeOpen:w,setIsImeOpen:R,isMenuOpen:x,setIsMenuOpen:b,imeText:h,setImeText:f,handleImeSubmit:le,isConnActive:G,zoom:L,isMobile:g,mobileFillZoom:S,onZoomOut:()=>M(ne=>Math.max(.5,ne-.25)),onZoomReset:pe,onZoomIn:()=>M(ne=>Math.min(5,ne+.25)),transportType:o,screenshotUsage:a,lastActionStatus:m}),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 cd=Object.defineProperty;var ld=(e,t,r)=>t in e?cd(e,t,{enumerable:!0,config
24
24
  50% { transform: translateY(-7px); }
25
25
  100% { transform: translateY(0px); }
26
26
  }
27
- `})]})}function sn(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 u=Math.floor(l/60);if(u<24)return`${u}h${r}`;const m=Math.floor(u/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const Qi=e=>sn(e);function Du(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 Rs(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 Eu(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...Du(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 Fr(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 rn(e,t,r){const n=Fr(e,t),a=Rs(e),o=a.isReconnecting,c=a.isConnecting,l=a.isGenerating,u=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||u,d=n.inboxBucket==="working"||l,f=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:f,requiresAction:m,isWorking:d,isReconnecting:o,isConnecting:c,isGenerating:l,isWaiting:u,inboxBucket:m?"needs_attention":d?"working":f?"task_complete":"idle"}}function $u(e,t,r){return rn(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Zi({activeConv:e,onModalButton:t}){const[r,n]=i.useState(null);if(i.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Rs(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(tr,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,u)=>{const m=c(l).toLowerCase(),d=/^(run|approve|accept|yes|allow|always)/.test(m),h=/^(reject|deny|delete|remove|abort)/.test(m),f=r===l,w=r!==null;return s.jsx("button",{onClick:()=>o(l),disabled:w,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${d?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${w&&!f?"opacity-40":"opacity-100"} ${w?"cursor-not-allowed":"cursor-pointer"}`,style:d?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:h?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:f?"⏳ ...":c(l)},u)})})]})]})}const Ra="adhdev_controls_bar_visible",na="adhdev:controlsbarvisibilitychange";function yn(e){if(!e)return!1;try{return e.getItem(Ra)==="1"}catch{return!1}}function Bu(e,t){if(t)try{t.setItem(Ra,e?"1":"0")}catch{}}function Ku(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(na,{detail:{visible:e}}))}function _a(){const[e,t]=i.useState(()=>typeof window>"u"?!1:yn(window.localStorage)),r=i.useRef(e),n=i.useCallback((c,l=!0)=>{r.current=c,t(c),typeof window<"u"&&Bu(c,window.localStorage),l&&Ku(c)},[]);i.useEffect(()=>{const c=u=>{const m=u.detail,d=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:yn(window.localStorage);r.current=d,t(d)},l=u=>{if(u.key!==Ra)return;const m=yn(window.localStorage);r.current=m,t(m)};return window.addEventListener(na,c),window.addEventListener("storage",l),()=>{window.removeEventListener(na,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 Ou=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Wu(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function bt(e,t){if(Wu(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Ou.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 ec(e){return bt(e)==="generating"}function ot(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Hu(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 vn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function nn(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 Fu(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 Uu(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function zu(e){return Fu(e.trim().replace(/\.local$/i,""))}function Vu(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function tc(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&&!Uu(c));if(r&&r!=="Unknown")return zu(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function St(e,t={}){return Vu(e)||tc(e,t)}function sc(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 rc(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 us(e,t){return sc(e).join(" · ")}function rr(e){return e.transport==="pty"}function ws(e){return e.transport==="acp"}function Gu(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:ot(e)}function Io(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),c=ot(r||"").trim().toLowerCase();return n===a||n===o||n===c}function qu(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Yu(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=bt(n.status);if(!o){t.set(a,{...n,status:c});continue}const l=r.indexOf(o.status||"idle"),u=r.indexOf(c||"idle");u>=0&&(l<0||u<l)&&t.set(a,{...n,status:c})}return Array.from(t.values())}function Xu(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 Ju(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&&Xu(t.receivedAt)||0}function Qu(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function aa(e){return Math.max(Qu(e),Ju(e.activeChat))}function Zu(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 Pa(e,t){return Zu(aa(e),aa(t),St(e,{fallbackId:e.id}),St(t,{fallbackId:t.id}),e.id,t.id)}const nc="adhdev_notification_prefs",Mo={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function em(){try{const e=localStorage.getItem(nc);if(e){const t=JSON.parse(e);return{...Mo,...t}}}catch{}return{...Mo}}function tm(e){try{localStorage.setItem(nc,JSON.stringify(e))}catch{}}let Ot=em(),Ar=[];function sm(){Ar.forEach(e=>e())}function rm(e){Ot={...Ot,...e},tm(Ot),sm()}function nm(){const[,e]=i.useState(0);i.useEffect(()=>{const r=()=>e(n=>n+1);return Ar.push(r),()=>{Ar=Ar.filter(n=>n!==r)}},[]);const t=i.useCallback(r=>{rm(r)},[]);return[{...Ot},t]}function qs(e){if(!Ot.globalEnabled)return!1;switch(e){case"disconnect":return Ot.disconnectAlert;case"completion":return Ot.completionAlert;case"approval":return Ot.approvalAlert;case"browser":return Ot.browserNotifications;default:return!0}}const am={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function ac(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function oc(){return"Notification"in window&&Notification.permission==="granted"}let Xt=null;function om(e){return e!==!1}async function im(){if(Xt!==null)return Xt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Xt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Xt=!!await e.pushManager.getSubscription(),Xt):(Xt=!1,!1)}catch{return Xt=!1,!1}}function oa(e,t,r){if(oc())try{const n=new Notification(e,{body:t,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function cm(e,t={}){const r={...am,...t},n=i.useRef(new Map),a=i.useRef(0),[o,c]=i.useState(null);i.useEffect(()=>{let u=!1;return im().then(m=>{u||c(m)}),()=>{u=!0}},[]);const l=i.useCallback((u,m,d)=>{const h=Date.now();h-a.current<r.throttleMs||(a.current=h,oa(u,m,d))},[r.throttleMs]);i.useEffect(()=>{var u;if(!(!r.enabled||!oc())&&qs("browser")&&!om(o)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,bt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const d=n.current.get(m.id),h=bt(m.status,{activeModal:m.activeModal}),f=m.name||m.id;if(r.onApproval&&qs("approval")&&h==="waiting_approval"&&d!=="waiting_approval"){const w=((u=m.activeModal)==null?void 0:u.message)||"Action requires your approval";l(`🔔 ${f} — Approval needed`,w.slice(0,120),`approval-${m.id}`)}r.onComplete&&qs("completion")&&ec(d)&&h==="idle"&&l(`✅ ${f} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&h==="error"&&d!=="error"&&l(`⚠️ ${f} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,h)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,l])}const lm=/^(run|approve|accept|yes|allow|always)/,dm=/^(run|approve|accept|yes|allow|always|proceed|save)/,um=/^(reject|deny|delete|remove|abort|cancel|no)/;function Da(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function mm(e){const t=Da(e).toLowerCase();return lm.test(t)?"primary":um.test(t)?"danger":"default"}function fm(e){return dm.test(Da(e).toLowerCase())?"approve":"reject"}function pm(e){return e.map((t,r)=>({label:Da(t),variant:mm(t),action:fm(t),button:t,buttonIndex:r}))}function hm(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function xm(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 bm{constructor(){Ve(this,"dedupMap",new Map);Ve(this,"DEDUP_WINDOW_MS",5e3);Ve(this,"DEDUP_MAX_SIZE",50);Ve(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ve(this,"toastCallbacks",[]);Ve(this,"resolveActionFn",null);Ve(this,"viewRequestRespondFn",null);Ve(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 k;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 u=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(u==null?void 0:u.type)||"";let d=ot(m);const h=this.resolveOwningDaemon(t);if(h){const p=St(h,{fallbackId:h.id});p&&(d=!m||m==="adhdev-daemon"?p:`${p}/${d}`)}let f="",w="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";f=`✅ ${d} agent task completed${p}`,w="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(f=`⚡ ${d} approval needed`,w="warning",(k=t.modalButtons)!=null&&k.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const y=this.resolveActionFn,x=pm(t.modalButtons).map(R=>({label:R.label,variant:R.variant,onClick:()=>{y(p,"resolve_action",{action:R.action,button:R.button,buttonIndex:R.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),b=hm(d,t.modalMessage,f),v=Date.now();this.emitToast({id:v,message:b,type:w,timestamp:v,targetKey:n||p,actions:x,duration:15e3}),f=""}}else if(t.event==="monitor:long_generating"){const p=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";f=`⚠️ ${d} agent is taking a long time${p}`,w="warning",qs("browser")&&!document.hasFocus()&&oa(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const p=t.requesterName||"A team member",y=t.requestId,x=t.orgId;if(f=`👁️ ${p} wants to view your session`,w="warning",y&&x&&this.viewRequestRespondFn){const b=Date.now(),v=xm(x,y,this.viewRequestRespondFn,(R,g)=>console.error(`[EventManager] ${R} view request failed:`,g));this.emitToast({id:b,message:f,type:w,timestamp:b,actions:v,duration:3e4}),f=""}qs("browser")&&!document.hasFocus()&&oa("👁️ View Request",`${p} wants to view your session`,`view-request-${y}`)}else t.event==="team:view_request_approved"?(f="✅ View request approved",w="success"):t.event==="team:view_request_rejected"&&(f=`❌ ${t.targetName||"Team member"} declined your view request`,w="warning");if(f){const p=Date.now();this.emitToast({id:p,message:f,type:w,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const et=new bm,Ao=new Map;function Ur(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function js(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function an(e){return Ur(e)?Ur(e.result)?e.result:e:null}function gm(e){const t=an(e);return!t||!Ur(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function xr(e){const t=an(e);return!t||!Ur(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function $s(e){const t=an(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function br(e){const t=an(e);return!!t&&t.success===!1}function ym(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";et.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";et.showToast(n.notification.body,a)}}}function vm(e,t){return e&&js(e.currentValue)?e.currentValue:t}function wm(e,t){return js(t)?js(e)?typeof e=="string"&&e.trim()==="":!0:!1}function jm(e,t){var o,c;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(js(l))return l}const n=(o=t.controlValues)==null?void 0:o[e];if(js(n))return n;const a=(c=t.defaultValues)==null?void 0:c[e];return js(a)?a:void 0}function Lr(e,t){return e.options||t[e.id]||[]}const km={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 Sm(e,t,r){var n;return((n=km[t])==null?void 0:n.has(r.id))===!0}function Ea(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Sm(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function wn(e,t){return{value:t}}function Nm(e,t,r){var a;return r?((a=Lr(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const Cm={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Tm({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:c}){const{sendCommand:l}=vt(),u=`${e}:${t||n}`,m=Cm[n]||"#94a3b8",[d,h]=i.useState({}),f=i.useRef({}),w=i.useRef(c);f.current=d,w.current=c;const k=i.useRef(0),p={};for(const A of o||[])A.defaultValue!==void 0&&(p[A.id]=A.defaultValue);const y={...p,...c||{},...Date.now()<k.current?d:{}};i.useEffect(()=>{c&&Date.now()>k.current&&h({})},[c]);const[x,b]=i.useState(Ao.get(u)||{}),[v,R]=i.useState(null),[g,M]=i.useState(null),C=i.useCallback(async(A,z={})=>{const $={...z,...t&&{targetSessionId:t}};return await l(e,A,$)},[e,t,l]),S=i.useCallback(async(A,z={})=>{const $=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await C("invoke_provider_script",{...$,scriptName:A,...z})},[C,n,r,t]),j=i.useCallback((A,z,$)=>{const B=vm($,z);h(V=>({...V,[A.id]:B})),ym($==null?void 0:$.effects)},[]),W=i.useCallback((A,z)=>{h($=>{const B={...$};return z===void 0?delete B[A.id]:B[A.id]=z,B}),k.current=0},[]);if(!o||o.length===0)return null;const L=Ea(o,{hostIdeType:r,providerType:n});if(L.length===0)return null;const I=async A=>{if(v===A.id){R(null);return}if(Lr(A,x).length>0){R(A.id);return}if(A.dynamic&&A.listScript){M(A.id);try{const $=await S(A.listScript,{}),B=gm($);if(!B){const me=$s($);me&&et.showToast(me,"warning");return}const V=B.options;b(me=>{const ne={...me,[A.id]:V};return Ao.set(u,ne),ne});const G=jm(A.id,{localOverrideUntil:k.current,localValues:f.current,controlValues:w.current,defaultValues:p});if(wm(G,B.currentValue)){const me=B.currentValue;h(ne=>({...ne,[A.id]:me}))}R(A.id)}catch($){const B=$ instanceof Error?$.message:`Could not load ${A.label}`;et.showToast(B,"warning")}finally{M(null)}}},D=async(A,z)=>{R(null);const $=(c==null?void 0:c[A.id])??p[A.id];h(B=>({...B,[A.id]:z})),k.current=Date.now()+5e3;try{if(!A.setScript)return;const B=await S(A.setScript,wn(A,z)),V=xr(B);if(V&&!V.ok||br(B))throw new Error((V==null?void 0:V.error)||$s(B)||`Could not update ${A.label}`);j(A,z,V)}catch(B){W(A,$);const V=B instanceof Error?B.message:`Could not update ${A.label}`;et.showToast(V,"warning")}},U=async A=>{const z=Lr(A,x).map(ne=>ne.value);if(z.length===0)return;const $=String(y[A.id]||""),V=(z.indexOf($)+1)%z.length,G=z[V];if(typeof G!="string")return;const me=(c==null?void 0:c[A.id])??p[A.id];h(ne=>({...ne,[A.id]:G})),k.current=Date.now()+5e3;try{if(!A.setScript)return;const ne=await S(A.setScript,wn(A,G)),xe=xr(ne);if(xe&&!xe.ok||br(ne))throw new Error((xe==null?void 0:xe.error)||$s(ne)||`Could not update ${A.label}`);j(A,G,xe)}catch(ne){W(A,me);const xe=ne instanceof Error?ne.message:`Could not update ${A.label}`;et.showToast(xe,"warning")}},K=async A=>{const $=!y[A.id],B=(c==null?void 0:c[A.id])??p[A.id];h(V=>({...V,[A.id]:$})),k.current=Date.now()+5e3;try{if(!A.setScript)return;const V=await S(A.setScript,wn(A,$)),G=xr(V);if(G&&!G.ok||br(V))throw new Error((G==null?void 0:G.error)||$s(V)||`Could not update ${A.label}`);j(A,$,G)}catch(V){W(A,B);const G=V instanceof Error?V.message:`Could not update ${A.label}`;et.showToast(G,"warning")}},N=async A=>{if(!A.invokeScript)return;if(A.confirmMessage){const $=[A.confirmTitle,A.confirmMessage,A.confirmLabel].filter(V=>typeof V=="string"&&V.trim().length>0);if(!window.confirm($.join(`
27
+ `})]})}function rn(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 u=Math.floor(l/60);if(u<24)return`${u}h${r}`;const m=Math.floor(u/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const Zi=e=>rn(e);function Bu(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 Rs(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 Ku(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...Bu(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 Ur(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 nn(e,t,r){const n=Ur(e,t),a=Rs(e),o=a.isReconnecting,c=a.isConnecting,l=a.isGenerating,u=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||u,d=n.inboxBucket==="working"||l,f=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:f,requiresAction:m,isWorking:d,isReconnecting:o,isConnecting:c,isGenerating:l,isWaiting:u,inboxBucket:m?"needs_attention":d?"working":f?"task_complete":"idle"}}function Ou(e,t,r){return nn(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function ec({activeConv:e,onModalButton:t}){const[r,n]=i.useState(null);if(i.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Rs(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(tr,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,u)=>{const m=c(l).toLowerCase(),d=/^(run|approve|accept|yes|allow|always)/.test(m),h=/^(reject|deny|delete|remove|abort)/.test(m),f=r===l,v=r!==null;return s.jsx("button",{onClick:()=>o(l),disabled:v,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${d?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${v&&!f?"opacity-40":"opacity-100"} ${v?"cursor-not-allowed":"cursor-pointer"}`,style:d?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:h?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:f?"⏳ ...":c(l)},u)})})]})]})}const Ra="adhdev_controls_bar_visible",aa="adhdev:controlsbarvisibilitychange";function vn(e){if(!e)return!1;try{return e.getItem(Ra)==="1"}catch{return!1}}function Wu(e,t){if(t)try{t.setItem(Ra,e?"1":"0")}catch{}}function Hu(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(aa,{detail:{visible:e}}))}function _a(){const[e,t]=i.useState(()=>typeof window>"u"?!1:vn(window.localStorage)),r=i.useRef(e),n=i.useCallback((c,l=!0)=>{r.current=c,t(c),typeof window<"u"&&Wu(c,window.localStorage),l&&Hu(c)},[]);i.useEffect(()=>{const c=u=>{const m=u.detail,d=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:vn(window.localStorage);r.current=d,t(d)},l=u=>{if(u.key!==Ra)return;const m=vn(window.localStorage);r.current=m,t(m)};return window.addEventListener(aa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(aa,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 Fu=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Uu(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function bt(e,t){if(Uu(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Fu.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 tc(e){return bt(e)==="generating"}function ot(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 wn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function an(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 Vu(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 Gu(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function qu(e){return Vu(e.trim().replace(/\.local$/i,""))}function Yu(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function sc(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&&!Gu(c));if(r&&r!=="Unknown")return qu(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function St(e,t={}){return Yu(e)||sc(e,t)}function rc(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 nc(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 us(e,t){return rc(e).join(" · ")}function rr(e){return e.transport==="pty"}function ws(e){return e.transport==="acp"}function Xu(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:ot(e)}function Mo(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),c=ot(r||"").trim().toLowerCase();return n===a||n===o||n===c}function Ju(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Qu(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=bt(n.status);if(!o){t.set(a,{...n,status:c});continue}const l=r.indexOf(o.status||"idle"),u=r.indexOf(c||"idle");u>=0&&(l<0||u<l)&&t.set(a,{...n,status:c})}return Array.from(t.values())}function Zu(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 em(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&&Zu(t.receivedAt)||0}function tm(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function oa(e){return Math.max(tm(e),em(e.activeChat))}function sm(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 Pa(e,t){return sm(oa(e),oa(t),St(e,{fallbackId:e.id}),St(t,{fallbackId:t.id}),e.id,t.id)}const ac="adhdev_notification_prefs",Io={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function rm(){try{const e=localStorage.getItem(ac);if(e){const t=JSON.parse(e);return{...Io,...t}}}catch{}return{...Io}}function nm(e){try{localStorage.setItem(ac,JSON.stringify(e))}catch{}}let Ot=rm(),Ar=[];function am(){Ar.forEach(e=>e())}function om(e){Ot={...Ot,...e},nm(Ot),am()}function im(){const[,e]=i.useState(0);i.useEffect(()=>{const r=()=>e(n=>n+1);return Ar.push(r),()=>{Ar=Ar.filter(n=>n!==r)}},[]);const t=i.useCallback(r=>{om(r)},[]);return[{...Ot},t]}function qs(e){if(!Ot.globalEnabled)return!1;switch(e){case"disconnect":return Ot.disconnectAlert;case"completion":return Ot.completionAlert;case"approval":return Ot.approvalAlert;case"browser":return Ot.browserNotifications;default:return!0}}const cm={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function oc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function ic(){return"Notification"in window&&Notification.permission==="granted"}let Xt=null;function lm(e){return e!==!1}async function dm(){if(Xt!==null)return Xt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Xt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Xt=!!await e.pushManager.getSubscription(),Xt):(Xt=!1,!1)}catch{return Xt=!1,!1}}function ia(e,t,r){if(ic())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 um(e,t={}){const r={...cm,...t},n=i.useRef(new Map),a=i.useRef(0),[o,c]=i.useState(null);i.useEffect(()=>{let u=!1;return dm().then(m=>{u||c(m)}),()=>{u=!0}},[]);const l=i.useCallback((u,m,d)=>{const h=Date.now();h-a.current<r.throttleMs||(a.current=h,ia(u,m,d))},[r.throttleMs]);i.useEffect(()=>{var u;if(!(!r.enabled||!ic())&&qs("browser")&&!lm(o)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,bt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const d=n.current.get(m.id),h=bt(m.status,{activeModal:m.activeModal}),f=m.name||m.id;if(r.onApproval&&qs("approval")&&h==="waiting_approval"&&d!=="waiting_approval"){const v=((u=m.activeModal)==null?void 0:u.message)||"Action requires your approval";l(`🔔 ${f} — Approval needed`,v.slice(0,120),`approval-${m.id}`)}r.onComplete&&qs("completion")&&tc(d)&&h==="idle"&&l(`✅ ${f} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&h==="error"&&d!=="error"&&l(`⚠️ ${f} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,h)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,l])}const mm=/^(run|approve|accept|yes|allow|always)/,fm=/^(run|approve|accept|yes|allow|always|proceed|save)/,pm=/^(reject|deny|delete|remove|abort|cancel|no)/;function Da(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function hm(e){const t=Da(e).toLowerCase();return mm.test(t)?"primary":pm.test(t)?"danger":"default"}function xm(e){return fm.test(Da(e).toLowerCase())?"approve":"reject"}function bm(e){return e.map((t,r)=>({label:Da(t),variant:hm(t),action:xm(t),button:t,buttonIndex:r}))}function gm(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function ym(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 vm{constructor(){Ve(this,"dedupMap",new Map);Ve(this,"DEDUP_WINDOW_MS",5e3);Ve(this,"DEDUP_MAX_SIZE",50);Ve(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ve(this,"toastCallbacks",[]);Ve(this,"resolveActionFn",null);Ve(this,"viewRequestRespondFn",null);Ve(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 j;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 u=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(u==null?void 0:u.type)||"";let d=ot(m);const h=this.resolveOwningDaemon(t);if(h){const p=St(h,{fallbackId:h.id});p&&(d=!m||m==="adhdev-daemon"?p:`${p}/${d}`)}let f="",v="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";f=`✅ ${d} agent task completed${p}`,v="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(f=`⚡ ${d} approval needed`,v="warning",(j=t.modalButtons)!=null&&j.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const y=this.resolveActionFn,x=bm(t.modalButtons).map(R=>({label:R.label,variant:R.variant,onClick:()=>{y(p,"resolve_action",{action:R.action,button:R.button,buttonIndex:R.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),b=gm(d,t.modalMessage,f),w=Date.now();this.emitToast({id:w,message:b,type:v,timestamp:w,targetKey:n||p,actions:x,duration:15e3}),f=""}}else if(t.event==="monitor:long_generating"){const p=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";f=`⚠️ ${d} agent is taking a long time${p}`,v="warning",qs("browser")&&!document.hasFocus()&&ia(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const p=t.requesterName||"A team member",y=t.requestId,x=t.orgId;if(f=`👁️ ${p} wants to view your session`,v="warning",y&&x&&this.viewRequestRespondFn){const b=Date.now(),w=ym(x,y,this.viewRequestRespondFn,(R,g)=>console.error(`[EventManager] ${R} view request failed:`,g));this.emitToast({id:b,message:f,type:v,timestamp:b,actions:w,duration:3e4}),f=""}qs("browser")&&!document.hasFocus()&&ia("👁️ View Request",`${p} wants to view your session`,`view-request-${y}`)}else t.event==="team:view_request_approved"?(f="✅ View request approved",v="success"):t.event==="team:view_request_rejected"&&(f=`❌ ${t.targetName||"Team member"} declined your view request`,v="warning");if(f){const p=Date.now();this.emitToast({id:p,message:f,type:v,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const et=new vm,Ao=new Map;function zr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ks(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function on(e){return zr(e)?zr(e.result)?e.result:e:null}function wm(e){const t=on(e);return!t||!zr(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function xr(e){const t=on(e);return!t||!zr(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function $s(e){const t=on(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function br(e){const t=on(e);return!!t&&t.success===!1}function km(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";et.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";et.showToast(n.notification.body,a)}}}function jm(e,t){return e&&ks(e.currentValue)?e.currentValue:t}function Sm(e,t){return ks(t)?ks(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Nm(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 Lr(e,t){return e.options||t[e.id]||[]}const Cm={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 Tm(e,t,r){var n;return((n=Cm[t])==null?void 0:n.has(r.id))===!0}function Ea(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Tm(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function kn(e,t){return{value:t}}function Mm(e,t,r){var a;return r?((a=Lr(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const Im={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Am({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:c}){const{sendCommand:l}=vt(),u=`${e}:${t||n}`,m=Im[n]||"#94a3b8",[d,h]=i.useState({}),f=i.useRef({}),v=i.useRef(c);f.current=d,v.current=c;const j=i.useRef(0),p={};for(const A of o||[])A.defaultValue!==void 0&&(p[A.id]=A.defaultValue);const y={...p,...c||{},...Date.now()<j.current?d:{}};i.useEffect(()=>{c&&Date.now()>j.current&&h({})},[c]);const[x,b]=i.useState(Ao.get(u)||{}),[w,R]=i.useState(null),[g,I]=i.useState(null),C=i.useCallback(async(A,z={})=>{const $={...z,...t&&{targetSessionId:t}};return await l(e,A,$)},[e,t,l]),S=i.useCallback(async(A,z={})=>{const $=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await C("invoke_provider_script",{...$,scriptName:A,...z})},[C,n,r,t]),k=i.useCallback((A,z,$)=>{const B=jm($,z);h(G=>({...G,[A.id]:B})),km($==null?void 0:$.effects)},[]),W=i.useCallback((A,z)=>{h($=>{const B={...$};return z===void 0?delete B[A.id]:B[A.id]=z,B}),j.current=0},[]);if(!o||o.length===0)return null;const L=Ea(o,{hostIdeType:r,providerType:n});if(L.length===0)return null;const M=async A=>{if(w===A.id){R(null);return}if(Lr(A,x).length>0){R(A.id);return}if(A.dynamic&&A.listScript){I(A.id);try{const $=await S(A.listScript,{}),B=wm($);if(!B){const me=$s($);me&&et.showToast(me,"warning");return}const G=B.options;b(me=>{const ae={...me,[A.id]:G};return Ao.set(u,ae),ae});const V=Nm(A.id,{localOverrideUntil:j.current,localValues:f.current,controlValues:v.current,defaultValues:p});if(Sm(V,B.currentValue)){const me=B.currentValue;h(ae=>({...ae,[A.id]:me}))}R(A.id)}catch($){const B=$ instanceof Error?$.message:`Could not load ${A.label}`;et.showToast(B,"warning")}finally{I(null)}}},E=async(A,z)=>{R(null);const $=(c==null?void 0:c[A.id])??p[A.id];h(B=>({...B,[A.id]:z})),j.current=Date.now()+5e3;try{if(!A.setScript)return;const B=await S(A.setScript,kn(A,z)),G=xr(B);if(G&&!G.ok||br(B))throw new Error((G==null?void 0:G.error)||$s(B)||`Could not update ${A.label}`);k(A,z,G)}catch(B){W(A,$);const G=B instanceof Error?B.message:`Could not update ${A.label}`;et.showToast(G,"warning")}},U=async A=>{const z=Lr(A,x).map(ae=>ae.value);if(z.length===0)return;const $=String(y[A.id]||""),G=(z.indexOf($)+1)%z.length,V=z[G];if(typeof V!="string")return;const me=(c==null?void 0:c[A.id])??p[A.id];h(ae=>({...ae,[A.id]:V})),j.current=Date.now()+5e3;try{if(!A.setScript)return;const ae=await S(A.setScript,kn(A,V)),xe=xr(ae);if(xe&&!xe.ok||br(ae))throw new Error((xe==null?void 0:xe.error)||$s(ae)||`Could not update ${A.label}`);k(A,V,xe)}catch(ae){W(A,me);const xe=ae instanceof Error?ae.message:`Could not update ${A.label}`;et.showToast(xe,"warning")}},K=async A=>{const $=!y[A.id],B=(c==null?void 0:c[A.id])??p[A.id];h(G=>({...G,[A.id]:$})),j.current=Date.now()+5e3;try{if(!A.setScript)return;const G=await S(A.setScript,kn(A,$)),V=xr(G);if(V&&!V.ok||br(G))throw new Error((V==null?void 0:V.error)||$s(G)||`Could not update ${A.label}`);k(A,$,V)}catch(G){W(A,B);const V=G instanceof Error?G.message:`Could not update ${A.label}`;et.showToast(V,"warning")}},N=async A=>{if(!A.invokeScript)return;if(A.confirmMessage){const $=[A.confirmTitle,A.confirmMessage,A.confirmLabel].filter(G=>typeof G=="string"&&G.trim().length>0);if(!window.confirm($.join(`
28
28
 
29
- `)))return}const z=(c==null?void 0:c[A.id])??p[A.id];try{const $=await S(A.invokeScript),B=xr($);if(B&&!B.ok||br($))throw new Error((B==null?void 0:B.error)||$s($)||`Could not run ${A.label}`);B&&j(A,z??!0,B)}catch($){W(A,z);const B=$ instanceof Error?$.message:`Could not run ${A.label}`;et.showToast(B,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${m}33`,background:`${m}12`,color:m},children:a}),L.map(A=>{const z=String(y[A.id]||""),$=Nm(A,x,z),B=v===A.id,V=g===A.id,G=Lr(A,x),me="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(A.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${me} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:B?`${m}55`:"var(--border-default)",background:B?`${m}10`:"var(--surface-tertiary)",color:z?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void I(A),title:A.label,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:V?"Loading…":$||A.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),B&&G.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>R(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:A.label}),G.map(ne=>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:ne.value===z?`${m}14`:"transparent",color:ne.value===z?"var(--text-primary)":"var(--text-secondary)",borderLeft:ne.value===z?`2px solid ${m}`:"2px solid transparent"},title:ne.description||ne.label,onMouseEnter:xe=>{xe.currentTarget.style.background=`${m}10`},onMouseLeave:xe=>{xe.currentTarget.style.background=ne.value===z?`${m}14`:"transparent"},onClick:()=>void D(A,ne.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ne.label}),ne.value===z&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},ne.value))]})]})]},A.id);case"cycle":return s.jsxs("button",{type:"button",className:`${me} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:z?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void U(A),title:`Click to cycle: ${G.map(ne=>ne.label).join(" → ")}`,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$||A.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},A.id);case"toggle":return s.jsxs("button",{type:"button",className:`${me} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:z?`${m}44`:"var(--border-default)",background:z?`${m}14`:"var(--surface-tertiary)",color:z?m:"var(--text-muted)"},onClick:()=>void K(A),"aria-pressed":!!z,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),A.label]},A.id);case"action":return s.jsxs("button",{type:"button",className:`${me} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void N(A),children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:A.resultDisplay==="inline"&&z?`${A.label}: ${z}`:A.label})]},A.id);case"display":return s.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:z?"var(--text-primary)":"var(--text-muted)"},children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:z?`${A.label}: ${z}`:A.label})]},A.id);default:return null}})]})})}function Im({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:c,controls:l,controlValues:u}){const{isVisible:m}=_a(),d=Ea(l,{hostIdeType:a,providerType:o});return!e||t||d.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(Tm,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:c,controls:d,controlValues:u})})}function Mm({hasDraft:e,isBusy:t=!1}){return!e||t}const ic=i.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1,animateVisibility:m=!0,onControlsToggle:d}){const h=i.useRef(null),[f,w]=i.useState(""),{isVisible:k,toggleVisibility:p}=_a();i.useEffect(()=>{w("")},[t]),i.useEffect(()=>{var x;l&&((x=h.current)==null||x.focus({preventScroll:!0}))},[t,l]);const y=async()=>{const x=f.trim();if(!x||a)return;await c(x)!==!1&&w("")};return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"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:[u&&s.jsx("button",{type:"button",onClick:()=>{p(),d==null||d()},"aria-label":k?"Hide controls":"Show controls","aria-pressed":k,title:k?"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:h,type:"text",placeholder:o||`Send message to ${r}...`,value:f,onChange:x=>w(x.target.value),onPaste:x=>{const b=x.clipboardData.getData("text");b&&w(v=>v+b),x.preventDefault()},onKeyDown:x=>{if(x.key==="Enter"){if(x.nativeEvent.isComposing){x.preventDefault();return}x.preventDefault(),y()}},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:()=>{y()},disabled:Mm({hasDraft:!!f.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${f.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:f.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:f.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})]})}),Ze=e=>e.transport==="pty",_s=(e,t)=>Ze(e)?e.mode||"terminal":"chat",cc=(e,t)=>Ze(e)&&_s(e)==="terminal",qe=e=>e.transport==="acp",Am=180;function Vt(e){return e.streamSource!=="agent-stream"}function hs(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function lc(e){return e.machineName||""}function Ps(e){return hs(e)}function $t(e){return e.agentType||""}function zr(e){return e.hostIdeType||""}function $a(e){return e.displayPrimary||e.agentName||"Agent"}function dc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Lm(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function uc(e){const t=Lm(e),r=Bt(t==null?void 0:t.content),n=Bt(e.lastMessagePreview);return r||n||""}function Rm(e,t=Am){const r=Bt(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 _m(e){return Rm(uc(e)||e.displaySecondary||"")}function mc(e){return[e.displaySecondary,lc(e)].filter(Boolean)}function Cs(e){return e.agentName||ot($t(e))}function Pm(e){var t,r;if(!Vt(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return ot(zr(e)||$t(e))}function fc(e){return Vt(e)?e.sessionId:e.nativeSessionId}function Lo(e){return Vt(e)?"native":e.tabKey}function Dm(e){return e.sessionId}function Em(e,t){if(t)return Vt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function $m(e,t){const r=$t(e),n=Vt(e),a=Ze(e)||qe(e),o=n?a?Cs(e)||(t==null?void 0:t.cliName)||ot(zr(e)||r):t!=null&&t.type?ot(t.type):ot(zr(e)||r):Cs(e);return{isNativeConversation:n,isCli:Ze(e),isAcp:qe(e),isCliTerminal:cc(e),providerType:r,displayLabel:o,targetEntry:Em(e,t)}}function es(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:Ze(e)||qe(e)?{agentType:$t(e)}:e.streamSource==="agent-stream"?{agentType:$t(e)}:t}function Ts(e){return e?Ps(e):""}function Bs(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Ba(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Bm(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 pc(){return"select_session"}function Km(){return"open_panel"}function Om({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Wm(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Ro(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Vr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ka(e){return e instanceof Error?e.message:String(e||"")}function _o(e){const t=Ka(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Po(e,t){const r=Ka(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function on({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=i.useState(!1),[c,l]=i.useState(!1),[u,m]=i.useState(null),d=i.useRef(!1),h=i.useRef(null);i.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const f=i.useCallback(async y=>{if(!t)return!1;const x=y.trim(),b=Ba(t);if(Om({hasMessage:!!x,blockedMessage:b,sendInFlight:d.current}))return b&&m(b),!1;const v=Date.now(),R={tabKey:t.tabKey,message:x,timestamp:v};if(Wm(h.current,R))return m(null),!0;d.current=!0,l(!0),m(null),h.current=R;try{const g=Ts(t);if(!g)return h.current=Ro(h.current,R),m("Unable to send message right now."),!1;const M=await e(g,"send_chat",{message:x,...es(t)}),C=Vr(M);if(C!=null&&C.deduplicated)return m(null),!0;if((C==null?void 0:C.sent)===!1)throw new Error((C==null?void 0:C.error)||"Send failed");if((C==null?void 0:C.success)===!1)throw new Error((C==null?void 0:C.error)||"Send failed");return m(null),!0}catch(g){const M=Ka(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),h.current=Ro(h.current,R),m(Bm(g)),!1}finally{d.current=!1,l(!1)}},[t,e]),w=i.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(y){console.error("Relaunch failed",y)}},[t,e]),k=i.useCallback(async y=>{if(t)try{const b=(t.modalButtons||[]).indexOf(y),v=y.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),R=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(v),g=Ts(t);if(!g)return;const M=await e(g,"resolve_action",{button:y,action:R?"approve":"reject",...b>=0&&{buttonIndex:b},...es(t)}),C=Vr(M);C.success||r(S=>[...S,{routeId:t.tabKey,text:Po(y,C==null?void 0:C.error),timestamp:Date.now()}])}catch(x){_o(x)||console.error("[ModalButton] Error:",x),r(b=>[...b,{routeId:t.tabKey,text:_o(x)?Po(y,x):`❌ **${y}** error`,timestamp:Date.now()}])}},[t,e,r]),p=i.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,Km(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(y){console.error("Focus agent failed",y)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:u,isFocusingAgent:a,handleSendChat:f,handleRelaunch:w,handleModalButton:k,handleFocusAgent:p}}const Hm=10,Fm=8e3,Um=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function zm(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 ia(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(Um.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=zm(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=>ia(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,ia(a,n,r+1)]))}function gr(e,t){return Array.isArray(e)?e.slice(-t):[]}function Vm(e,t=Date.now()){const r=e&&t-e.firstAt<=Fm,n=r?e.count+1:1;return n>=Hm?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function hc(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:gr(t.messages,10),visibleMessagesTail:gr(e.visibleMessages,5),historyMessagesTail:gr(e.chatTailState.historyMessages,5),actionLogsTail:gr(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 ia(r)}function xc(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 bc(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 z=(c==null?void 0:c[A.id])??p[A.id];try{const $=await S(A.invokeScript),B=xr($);if(B&&!B.ok||br($))throw new Error((B==null?void 0:B.error)||$s($)||`Could not run ${A.label}`);B&&k(A,z??!0,B)}catch($){W(A,z);const B=$ instanceof Error?$.message:`Could not run ${A.label}`;et.showToast(B,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${m}33`,background:`${m}12`,color:m},children:a}),L.map(A=>{const z=String(y[A.id]||""),$=Mm(A,x,z),B=w===A.id,G=g===A.id,V=Lr(A,x),me="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(A.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${me} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:B?`${m}55`:"var(--border-default)",background:B?`${m}10`:"var(--surface-tertiary)",color:z?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void M(A),title:A.label,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:G?"Loading…":$||A.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),B&&V.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>R(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:A.label}),V.map(ae=>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:ae.value===z?`${m}14`:"transparent",color:ae.value===z?"var(--text-primary)":"var(--text-secondary)",borderLeft:ae.value===z?`2px solid ${m}`:"2px solid transparent"},title:ae.description||ae.label,onMouseEnter:xe=>{xe.currentTarget.style.background=`${m}10`},onMouseLeave:xe=>{xe.currentTarget.style.background=ae.value===z?`${m}14`:"transparent"},onClick:()=>void E(A,ae.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ae.label}),ae.value===z&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},ae.value))]})]})]},A.id);case"cycle":return s.jsxs("button",{type:"button",className:`${me} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:z?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void U(A),title:`Click to cycle: ${V.map(ae=>ae.label).join(" → ")}`,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$||A.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},A.id);case"toggle":return s.jsxs("button",{type:"button",className:`${me} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:z?`${m}44`:"var(--border-default)",background:z?`${m}14`:"var(--surface-tertiary)",color:z?m:"var(--text-muted)"},onClick:()=>void K(A),"aria-pressed":!!z,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),A.label]},A.id);case"action":return s.jsxs("button",{type:"button",className:`${me} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void N(A),children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:A.resultDisplay==="inline"&&z?`${A.label}: ${z}`:A.label})]},A.id);case"display":return s.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:z?"var(--text-primary)":"var(--text-muted)"},children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:z?`${A.label}: ${z}`:A.label})]},A.id);default:return null}})]})})}function Lm({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:c,controls:l,controlValues:u}){const{isVisible:m}=_a(),d=Ea(l,{hostIdeType:a,providerType:o});return!e||t||d.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(Am,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:c,controls:d,controlValues:u})})}function Rm({hasDraft:e,isBusy:t=!1}){return!e||t}const cc=i.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1,animateVisibility:m=!0,onControlsToggle:d}){const h=i.useRef(null),[f,v]=i.useState(""),{isVisible:j,toggleVisibility:p}=_a();i.useEffect(()=>{v("")},[t]),i.useEffect(()=>{var x;l&&((x=h.current)==null||x.focus({preventScroll:!0}))},[t,l]);const y=async()=>{const x=f.trim();if(!x||a)return;await c(x)!==!1&&v("")};return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"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:[u&&s.jsx("button",{type:"button",onClick:()=>{p(),d==null||d()},"aria-label":j?"Hide controls":"Show controls","aria-pressed":j,title:j?"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:h,type:"text",placeholder:o||`Send message to ${r}...`,value:f,onChange:x=>v(x.target.value),onPaste:x=>{const b=x.clipboardData.getData("text");b&&v(w=>w+b),x.preventDefault()},onKeyDown:x=>{if(x.key==="Enter"){if(x.nativeEvent.isComposing){x.preventDefault();return}x.preventDefault(),y()}},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:()=>{y()},disabled:Rm({hasDraft:!!f.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${f.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:f.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:f.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})]})}),Ze=e=>e.transport==="pty",_s=(e,t)=>Ze(e)?e.mode||"terminal":"chat",lc=(e,t)=>Ze(e)&&_s(e)==="terminal",qe=e=>e.transport==="acp",_m=180;function Vt(e){return e.streamSource!=="agent-stream"}function hs(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function dc(e){return e.machineName||""}function Ps(e){return hs(e)}function $t(e){return e.agentType||""}function Vr(e){return e.hostIdeType||""}function $a(e){return e.displayPrimary||e.agentName||"Agent"}function uc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Pm(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function mc(e){const t=Pm(e),r=Bt(t==null?void 0:t.content),n=Bt(e.lastMessagePreview);return r||n||""}function Dm(e,t=_m){const r=Bt(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 Em(e){return Dm(mc(e)||e.displaySecondary||"")}function fc(e){return[e.displaySecondary,dc(e)].filter(Boolean)}function Cs(e){return e.agentName||ot($t(e))}function $m(e){var t,r;if(!Vt(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return ot(Vr(e)||$t(e))}function pc(e){return Vt(e)?e.sessionId:e.nativeSessionId}function Lo(e){return Vt(e)?"native":e.tabKey}function Bm(e){return e.sessionId}function Km(e,t){if(t)return Vt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function Om(e,t){const r=$t(e),n=Vt(e),a=Ze(e)||qe(e),o=n?a?Cs(e)||(t==null?void 0:t.cliName)||ot(Vr(e)||r):t!=null&&t.type?ot(t.type):ot(Vr(e)||r):Cs(e);return{isNativeConversation:n,isCli:Ze(e),isAcp:qe(e),isCliTerminal:lc(e),providerType:r,displayLabel:o,targetEntry:Km(e,t)}}function es(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:Ze(e)||qe(e)?{agentType:$t(e)}:e.streamSource==="agent-stream"?{agentType:$t(e)}:t}function Ts(e){return e?Ps(e):""}function Bs(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Ba(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Wm(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 hc(){return"select_session"}function Hm(){return"open_panel"}function Fm({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Um(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Ro(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Gr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ka(e){return e instanceof Error?e.message:String(e||"")}function _o(e){const t=Ka(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Po(e,t){const r=Ka(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function cn({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=i.useState(!1),[c,l]=i.useState(!1),[u,m]=i.useState(null),d=i.useRef(!1),h=i.useRef(null);i.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const f=i.useCallback(async y=>{if(!t)return!1;const x=y.trim(),b=Ba(t);if(Fm({hasMessage:!!x,blockedMessage:b,sendInFlight:d.current}))return b&&m(b),!1;const w=Date.now(),R={tabKey:t.tabKey,message:x,timestamp:w};if(Um(h.current,R))return m(null),!0;d.current=!0,l(!0),m(null),h.current=R;try{const g=Ts(t);if(!g)return h.current=Ro(h.current,R),m("Unable to send message right now."),!1;const I=await e(g,"send_chat",{message:x,...es(t)}),C=Gr(I);if(C!=null&&C.deduplicated)return m(null),!0;if((C==null?void 0:C.sent)===!1)throw new Error((C==null?void 0:C.error)||"Send failed");if((C==null?void 0:C.success)===!1)throw new Error((C==null?void 0:C.error)||"Send failed");return m(null),!0}catch(g){const I=Ka(g);return I.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",I):console.warn("Send blocked/failed",g),h.current=Ro(h.current,R),m(Wm(g)),!1}finally{d.current=!1,l(!1)}},[t,e]),v=i.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(y){console.error("Relaunch failed",y)}},[t,e]),j=i.useCallback(async y=>{if(t)try{const b=(t.modalButtons||[]).indexOf(y),w=y.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),R=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(w),g=Ts(t);if(!g)return;const I=await e(g,"resolve_action",{button:y,action:R?"approve":"reject",...b>=0&&{buttonIndex:b},...es(t)}),C=Gr(I);C.success||r(S=>[...S,{routeId:t.tabKey,text:Po(y,C==null?void 0:C.error),timestamp:Date.now()}])}catch(x){_o(x)||console.error("[ModalButton] Error:",x),r(b=>[...b,{routeId:t.tabKey,text:_o(x)?Po(y,x):`❌ **${y}** error`,timestamp:Date.now()}])}},[t,e,r]),p=i.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,Hm(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(y){console.error("Focus agent failed",y)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:u,isFocusingAgent:a,handleSendChat:f,handleRelaunch:v,handleModalButton:j,handleFocusAgent:p}}const zm=10,Vm=8e3,Gm=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function qm(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 ca(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(Gm.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=qm(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=>ca(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,ca(a,n,r+1)]))}function gr(e,t){return Array.isArray(e)?e.slice(-t):[]}function Ym(e,t=Date.now()){const r=e&&t-e.firstAt<=Vm,n=r?e.count+1:1;return n>=zm?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function xc(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:gr(t.messages,10),visibleMessagesTail:gr(e.visibleMessages,5),historyMessagesTail:gr(e.chatTailState.historyMessages,5),actionLogsTail:gr(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 ca(r)}function bc(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 gc(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,58 +35,58 @@ ${JSON.stringify(t.bundle,null,2)}
35
35
 
36
36
  \`\`\`json
37
37
  ${JSON.stringify(t,null,2)}
38
- \`\`\``}function gt(e){return(typeof e=="string"?e.trim():"")||void 0}function Wt(e,t){const r=gt(t);return r?`${e}:${r}`:void 0}function zt(e,t,r){const n=Wt(t,r),a=gt(r);n&&e.push(n),a&&e.push(a)}function vs(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function gc(e){return gt(e.providerSessionId)||gt(e.sessionId)||gt(e.tabKey)||gt(e.routeId)}function Oa(e){return vs([gt(e.providerSessionId),gt(e.sessionId)])}function ks(e){const t=[];return zt(t,"provider",e.providerSessionId),zt(t,"session",e.sessionId),zt(t,"tab",e.tabKey),zt(t,"route",e.routeId),vs(t)}function Gm(e){const t=[];return gt(e.providerSessionId)?(zt(t,"provider",e.providerSessionId),vs(t)):gt(e.sessionId)?(zt(t,"session",e.sessionId),vs(t)):gt(e.tabKey)?(zt(t,"tab",e.tabKey),vs(t)):gt(e.routeId)?(zt(t,"route",e.routeId),vs(t)):[]}function Wa(e){return Wt("provider",e.providerSessionId)||Wt("session",e.sessionId)||Wt("tab",e.tabKey)||Wt("route",e.routeId)||"unknown:"}function cr(e){return Oa(e)[0]}function qm(e){const t=gt(e.providerSessionId),r=gt(e.sessionId),n=gt(e.tabKey),a=gt(e.routeId),o=[Wt("provider",t),Wt("session",r),Wt("tab",n),Wt("route",a)].filter(u=>typeof u=="string"),c=ks({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=Wa({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:gc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:cr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:c}}function ca(e,t){const r=qm(e);return Gm(t).some(n=>r.lookupKeys.includes(n))}function Do(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 ts(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=Do(t==null?void 0:t.receivedAt)||Do(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function la(e,t=0){return ts(e)||e.lastUpdated||t||0}function yc(e){return ts(e)||e.lastUpdated||0}function vc(e,t,r=yc){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 da(e){var r;const t=bt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Ym(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!da(e)&&!e.title.trim()}function Xm(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(da(r))-Number(da(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:vc(t,r)})[0]||null}function _t(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=Xm(a);return n?o&&Ym(n)?o:n:o||r[0]||null}function Gt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ha(e){return cr(e)||e.tabKey||e.routeId||null}function wc(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=_t(e.conversations,n)||e.conversations.find(o=>o.routeId===n);return a?Ha(a):null}function jc({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const o=Ls(),c=hs(e),l=lc(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",m=e.streamSource==="agent-stream"&&!!e.agentName,d=!m&&(e.transport==="pty"||e.transport==="acp"),h=Cs(e),f=Pm(e),w=i.useCallback(()=>{if(n){n();return}c&&o("/dashboard",{state:{openMachineId:c}})},[c,o,n]),k=i.useCallback(()=>{if(r){r();return}const p=Ha(e);p&&o(Gt(p))},[e,o,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:k,title:f,children:[s.jsx(Nt,{size:12}),s.jsx("span",{children:f})]}):s.jsxs("span",{className:"conversation-meta-chip",title:f,children:[s.jsx(Nt,{size:12}),s.jsx("span",{children:f})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(sr,{size:12}),s.jsx("span",{children:h})]}),d&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(sr,{size:12}),s.jsx("span",{children:h})]}),l&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:l,children:[s.jsx(ds,{size:12}),s.jsx("span",{children:l})]}):s.jsxs("span",{className:"conversation-meta-chip",title:l,children:[s.jsx(ds,{size:12}),s.jsx("span",{children:l})]}))]})}function jn(e,t){return`${e}:${t}`}function Jm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Ks(e,t){Jm()&&console.debug(`[subscription-manager] ${e}`,t)}class Qm{constructor(){Ve(this,"active",new Map);Ve(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var d;const c=jn(n.topic,n.key),l=this.active.get(c);let u=!0;if(l)l.handlers.add(a),l.lastUpdate&&a(l.lastUpdate);else{const h={daemonId:r,request:n,handlers:new Set([a])};this.active.set(c,h),Ks("subscribe",{daemonId:r,topic:n.topic,key:n.key}),u=((d=t.sendData)==null?void 0:d.call(t,r,n))??!1,!u&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(c,t,o.retryIntervalMs)}const m=()=>{var w;this.clearRetry(c);const h=this.active.get(c);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(c);const f={type:"unsubscribe",topic:n.topic,key:n.key};Ks("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(w=t.sendData)==null||w.call(t,r,f)};return m.initialSendAccepted=u,m}publish(t){const r=jn(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Ss.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),Ss.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=jn(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;Ks("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);Ks("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;Ks("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 qt=new Qm;function Zm(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 ef(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 Gr(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:c}=t,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:m,childrenByParent:d}=ef(u),h=Zm(o,n),f=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,w=m.filter(y=>y.kind==="workspace"&&y.transport==="cdp-page"),k=m.filter(y=>y.kind==="agent"&&y.transport==="pty"),p=m.filter(y=>y.kind==="agent"&&y.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...f&&{machine:f,platform:f.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:w.some(y=>!!y.cdpConnected)});for(const y of w){const x=h.get(y.id),b=zs(y,x),v=(d.get(y.id)||[]).map(R=>zs(R,h.get(R.id)));r.push({id:`${n}:ide:${y.id}`,sessionId:y.id,providerSessionId:y.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:y.id,workspace:b.workspace,terminals:0,childSessions:v,agents:v.map(R=>({id:R.id,name:R.providerName||R.providerType,type:R.providerType,status:R.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 y of k){const x=h.get(y.id),b=zs(y,x);r.push({id:`${n}:cli:${y.id}`,sessionId:y.id,providerSessionId:y.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:y.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 y of p){const x=h.get(y.id),b=zs(y,x);r.push({id:`${n}:acp:${y.id}`,sessionId:y.id,providerSessionId:y.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:y.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 tf=15e3,sf=15e3,rf=6e4,nf=1200,Eo=12,af=8e3,of=4e3,kn=new Map,Sn=new Map,yr=new Set,Ys=new Map;function cf(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 $o(e,t){const r=Ys.get(e);!r||r.size===0||(Ys.delete(e),r.forEach(n=>n(t)))}function lf(e,t){return new Promise(r=>{const n=Ys.get(e)||new Set;Ys.set(e,n);const a=c=>{clearTimeout(o),n.delete(a),n.size===0&&Ys.delete(e),r(c)},o=setTimeout(()=>a(!1),t);n.add(a)})}function lr(){const{sendCommand:e,sendData:t}=vt(),{injectEntries:r,getIdes:n}=er();return i.useCallback(async(a,o)=>{if(!a)return;const c=(o==null?void 0:o.minFreshMs)??rf,l=Sn.get(a)||0;if(!(o!=null&&o.force)&&yr.has(a)&&l>0||!(o!=null&&o.force)&&l>0&&Date.now()-l<c)return;const u=kn.get(a);if(u)return u;const m=(async()=>{if(t&&!yr.has(a)){const p=qt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},y=>{const x=n(),b=x.find(R=>R.id===a),v=Gr(y.status,{daemonId:a,existingDaemon:b,existingEntries:x,timestamp:y.timestamp});v.length>0&&r(v),Sn.set(a,Date.now()),$o(a,!0)});if(p.initialSendAccepted?yr.add(a):yr.delete(a),!(o!=null&&o.force)&&p.initialSendAccepted&&await lf(a,nf))return}const d=await e(a,"get_status_metadata"),h=cf(d);if(!h)return;const f=n(),w=f.find(p=>p.id===a),k=Gr(h,{daemonId:a,existingDaemon:w,existingEntries:f,timestamp:h.timestamp||Date.now()});k.length>0&&r(k,{authoritativeDaemonIds:[a]}),Sn.set(a,Date.now()),$o(a,!0)})().finally(()=>{kn.delete(a)});return kn.set(a,m),m},[n,r,e,t])}function nr(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 Ft(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}function df(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=Bt(e.content),o=Bt(t.content);if(!a||!o||!(a===o||ma(a,o)||ma(o,a)))return!1;const l=Ft(e),u=Ft(t);return l&&u?Math.abs(l-u)<=15e3:!!e._localId!=!!t._localId}function ua(e){return Bt(e==null?void 0:e.content)}function ma(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 Bo(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=ua(e),o=Ft(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 uf(e,t,r=df){const n=new Map,a=o=>{for(const c of Bo(o)){const l=n.get(c);l?l.push(o):n.set(c,[o])}};return t.forEach(a),e.filter(o=>{const c=ua(o),l=String((o==null?void 0:o.role)||"").toLowerCase(),u=Ft(o),m=new Set;for(const h of Bo(o)){const f=n.get(h);f&&f.forEach(w=>m.add(w))}return!(m.size>0?Array.from(m):t).some(h=>{if(r(o,h))return!0;const f=String((h==null?void 0:h.role)||"").toLowerCase();if(!c||!l||l!==f)return!1;const w=ua(h);if(!ma(w,c)&&w!==c)return!1;const k=Ft(h);return u&&k?Math.abs(u-k)<=15e3:!0})})}const mf=60,ff=1e3;function kc(e={}){return e.isCliLike?ff:mf}function pf(e={}){return kc(e)}const dr=60,hf=1e3,Fa=12e4,xf=new Set(["generating","waiting_approval","starting","streaming","working"]),Ko=new Map;function Ua(e,t){return`${e}::${t}`}function fa(e=dr){return{liveMessages:[],cursor:Sc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function pa(e){return $i(e)}function Sc(e,t=dr){return{knownMessageCount:e.length,lastMessageSignature:pa(e[e.length-1]),tailLimit:t}}function vr(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 Oo(e){for(let t=e.length-1;t>=0;t-=1){const r=Ft(e[t]);if(r>0)return r}return 0}function bf(e,t){if(t.length===0)return!1;if(e.length===0)return!0;const r=Oo(e),n=Oo(t);return!(r>0&&n<=0||r>0&&n>0&&n<r||r>0&&n===r&&t.length<e.length)}function gf(e,t){if(t.length===0)return e;const r=[...e],n=new Map,a=(o,c)=>{for(const l of nr(o))n.set(l,c)};r.forEach(a);for(const o of t){const l=nr(o).map(u=>n.get(u)).find(u=>u!==void 0);if(l!==void 0){r[l]=o,a(o,l);continue}r.push(o),a(o,r.length-1)}return r}function yf(e,t){const r=Array.isArray(t.messages)?t.messages:[];switch(t.syncMode){case"noop":return e;case"append":return gf(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 vf{constructor(t){Ve(this,"manager");Ve(this,"sendData");Ve(this,"daemonId");Ve(this,"sessionId");Ve(this,"historySessionId");Ve(this,"subscriptionKey");Ve(this,"snapshot");Ve(this,"transportSubscription",null);Ve(this,"listeners",new Set);Ve(this,"retainCount",0);Ve(this,"loadHistoryPromise",null);Ve(this,"pendingDisconnectTimer",null);this.manager=t.manager||qt,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=fa(Math.max(0,t.tailLimit??dr))}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(!bf(this.snapshot.liveMessages,r))return;const n=r,a=Sc(n,this.snapshot.cursor.tailLimit);vr(this.snapshot.liveMessages)===vr(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=uf(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:hf}))}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=pa(this.snapshot.liveMessages[this.snapshot.liveMessages.length-1]);if(t.syncMode!=="full"&&r&&n===r){const u={knownMessageCount:Math.max(this.snapshot.cursor.knownMessageCount,Number(t.totalMessages||0)),lastMessageSignature:r,tailLimit:this.snapshot.cursor.tailLimit};this.snapshot.cursor.knownMessageCount===u.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===u.lastMessageSignature||(this.snapshot={...this.snapshot,cursor:u},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:u.knownMessageCount,lastMessageSignature:u.lastMessageSignature}));return}const a=yf(this.snapshot.liveMessages,t),o={knownMessageCount:a.length,lastMessageSignature:typeof t.lastMessageSignature=="string"?t.lastMessageSignature:pa(a[a.length-1]),tailLimit:this.snapshot.cursor.tailLimit};vr(this.snapshot.liveMessages)===vr(a)&&this.snapshot.cursor.knownMessageCount===o.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===o.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:a,cursor:o},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:o.knownMessageCount,lastMessageSignature:o.lastMessageSignature}),this.emit())}}function Nc(e){const t=Ua(e.daemonId,e.sessionId),r=Ko.get(t);if(r)return r.updateOptions(e),r;const n=new vf(e);return Ko.set(t,n),n}function wf(e,t){return{...e,loadHistoryPage:t}}function jf(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function kf(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(xf.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??Fa)),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 Sf(e=Fa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Nf(e,t={}){const r=new Set,n=[];for(const a of e){if(!kf(a,t))continue;const o=Ps(a),c=a.sessionId||"";if(!o||!c)continue;const l=Ua(o,c);if(r.has(l))continue;r.add(l);const u=cr(a);n.push({daemonId:o,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${o}:session:${c}`})}return n.sort(jf),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Cf(e,t){const{sendData:r,sendCommand:n}=vt(),a=(t==null?void 0:t.enabled)!==!1,o=Ps(e),c=e.sessionId||"",l=cr(e)||c,u=`daemon:${o}:session:${c}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??dr),d=i.useMemo(()=>!a||!o||!c?null:Nc({daemonId:o,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:m}),[o,a,l,r,c,u,m]),[h,f]=i.useState(()=>(d==null?void 0:d.getSnapshot())||fa(m));i.useEffect(()=>{if(!d){f(fa(m));return}d.retain(),f(d.getSnapshot());const k=d.subscribe(p=>{f(p)});return()=>{k(),d.release()}},[d,m]),i.useEffect(()=>{d&&(d.hydrateLiveMessages(e.messages),f(d.getSnapshot()))},[e.messages,d]);const w=i.useCallback(async()=>{!d||!o||!c||await d.loadHistoryPage(async({offset:k,excludeRecentCount:p})=>{const y=e.agentType,x=await n(o,"chat_history",{agentType:y,offset:k,limit:30,targetSessionId:c,historySessionId:l,excludeRecentCount:p}),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,d,o,l,n,c]);return i.useMemo(()=>wf(h,w),[w,h])}function Tf(e,t){const{sendData:r}=vt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??dr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Fa)),c=Sf(o),[l,u]=i.useState(0),[m,d]=i.useState(()=>new Map);i.useEffect(()=>{if(!n||e.length===0)return;const f=setInterval(()=>{u(w=>w+1)},c);return()=>{clearInterval(f)}},[e.length,n,c]);const h=i.useMemo(()=>Nf(e,{recentActivityMs:o}),[e,o,l]);return i.useEffect(()=>{if(!n||!r||h.descriptors.length===0){d(y=>y.size===0?y:new Map);return}const f=h.descriptors.map(y=>({key:Ua(y.daemonId,y.sessionId),controller:Nc({...y,sendData:r,tailLimit:a})})),w=new Set(f.map(({key:y})=>y)),k=(y,x)=>{d(b=>{const v=new Map(b);for(const R of v.keys())w.has(R)||v.delete(R);return v.set(y,x),v})},p=f.map(({key:y,controller:x})=>(x.retain(),k(y,x.getSnapshot()),x.subscribe(b=>k(y,b))));return()=>{p.forEach(y=>y()),f.forEach(({controller:y})=>y.release())}},[h.signature,n,r,a]),m}function Wo(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 qr(e){for(let t=e.length-1;t>=0;t-=1){const r=Ft(e[t]);if(r>0)return r}return 0}function If(e){const t=Ps(e),r=e.sessionId||"";return t&&r?`${t}::${r}`:""}function Mf(e){const t=new Set;for(const r of e)for(const n of nr(r)){if(t.has(n))return!0;t.add(n)}return!1}function Af(e,t){const r=new Set(nr(e));return r.size===0?!1:nr(t).some(n=>r.has(n))}function Cc(e,t){return t.length===0||e.length<=t.length||!Mf(e)?!1:Af(e[e.length-1],t[t.length-1])}function Lf(e,t){if(t.length===0)return!1;const r=Array.isArray(e.messages)?e.messages:[];if(r.length===0)return!0;const n=qr(r),a=qr(t);if(n>0&&a===n&&Cc(r,t))return!0;if(n<=0||a<=n)return!1;const o=Wo(r,e.status),c=Wo(t,e.status);return o!==c}function Rf(e,t){const r=t[t.length-1],n=Ft(r),a=Bt(r==null?void 0:r.content);return{...e,messages:t,...a?{lastMessagePreview:a}:{},...n>0?{lastMessageAt:n}:{}}}function _f(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=qr(r),o=qr(n);if(a>0&&(o<=0||a>o))return r;if(a>0&&a===o){if(Cc(r,n))return n;if(r.length>=n.length)return r}return n}function Pf(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 Ho(e,t){if(t.size===0||e.length===0)return e;let r=!1;const n=e.map(a=>{var l;const o=If(a);if(!o)return a;const c=((l=t.get(o))==null?void 0:l.liveMessages)||[];return Lf(a,c)?(r=!0,Rf(a,c)):a});return r?n:e}function Df(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Ef(e){return Df(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const $f=60;function ha({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:o,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:m=!1,scrollToBottomRequestNonce:d,isInputActive:h=!0,isVisible:f=!0}){var J,ue,le,Se,ie,pe,re;const w=i.useRef(new Map),k=i.useRef(void 0),p=lr(),{sendCommand:y}=vt(),{isVisible:x}=_a();ir("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const b=jt.useMemo(()=>Rs(e),[e.status,e.connectionState]),v=i.useMemo(()=>$m(e,t),[e,t]),R=i.useMemo(()=>{var Z;return Ea((Z=v.targetEntry)==null?void 0:Z.providerControls,{hostIdeType:e.hostIdeType,providerType:v.providerType})},[e.hostIdeType,v.providerType,(J=v.targetEntry)==null?void 0:J.providerControls]),g=kc({isCliLike:v.isCli||v.isAcp}),M=pf({isCliLike:v.isCli||v.isAcp}),C=Cf(e,{enabled:f&&!!e.sessionId,tailLimit:M}),[S,j]=i.useState(g),W=e.tabKey,L=C.historyMessages,I=C.hasMoreHistory,D=C.historyError,U=_f(e,C);i.useEffect(()=>{j(g)},[g,W]);const K=Math.max(0,U.length-S),N=$a(e),A=Ps(e),z=Ef(e),$=Ba(e),B=a||$,V=!!$,[G,me]=i.useState(!1);i.useEffect(()=>{const Z=v.targetEntry;A&&(!Z||Z.providerControls===void 0||Z.controlValues===void 0)&&p(A,{minFreshMs:3e4}).catch(()=>{})},[A,v.isAcp,(ue=v.targetEntry)==null?void 0:ue.providerControls,(le=v.targetEntry)==null?void 0:le.controlValues,p]);const ne=i.useCallback(async()=>{if(!G){if(U.length>S){j(Z=>Math.min(U.length,Z+$f));return}me(!0);try{await C.loadHistoryPage()}finally{me(!1)}}},[C,G,U.length,S]),{allMessages:xe,receivedAtMap:de}=i.useMemo(()=>{const Z=Pf({historyMessages:L,liveMessages:U,visibleLiveCount:S}),ee={};return Z.forEach((q,X)=>{const ae=`${e.tabKey}:${Hr(q,X)}`;let je=Ft(q)||w.current.get(ae)||0;je||(je=Date.now(),w.current.set(ae,je)),ee[Hr(q,X)]=je}),{allMessages:Z,receivedAtMap:ee}},[e.tabKey,K,L,U,S]),be=i.useMemo(()=>l.filter(Z=>Z.routeId===e.tabKey).sort((Z,ee)=>Z.timestamp-ee.timestamp),[l,e.tabKey]),he=i.useCallback(async()=>{var je,ke;if(!A)return;const Z=hc({activeConv:e,visibleMessages:xe,actionLogs:l,controls:(je=v.targetEntry)==null?void 0:je.providerControls,controlValues:(ke=v.targetEntry)==null?void 0:ke.controlValues,visibleBarControlCount:R.length,chatTailState:{hasMoreHistory:I,historyError:D,historyMessages:L},ui:{controlsVisible:x,visibleLiveCount:S,hiddenLiveCount:K,isInputActive:h,isVisible:f}}),ee=await y(A,"get_chat_debug_bundle",{agentType:v.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:Z}),q=Vr(ee),X=bc(q);let ae=!0;try{await navigator.clipboard.writeText(X)}catch(te){ae=!1,console.warn("[chat-debug-bundle] failed to copy debug bundle locator",te)}et.showToast(xc(q,{locatorCopied:ae}),ae?"success":"warning")},[e,l,xe,x,v.providerType,(Se=v.targetEntry)==null?void 0:Se.controlValues,(ie=v.targetEntry)==null?void 0:ie.providerControls,A,I,K,L,h,f,D,y,R.length,S]),Y=i.useCallback(()=>{const Z=Vm(k.current);k.current=Z.state,Z.shouldCollect&&he().catch(ee=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",ee),et.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[he]),oe=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")&&me(!1),e.status==="not_monitored"&&z)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(sr,{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(Ns,{size:14})," Open ",N," 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"&&z)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(Hi,{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(Ns,{size:14})," Open ",N," 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"&&!G)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,z,o,c,G,U.length,N,b.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&s.jsx(jc,{conversation:e,className:"chat-pane-meta-row"}),s.jsx(Cu,{messages:xe,actionLogs:be,agentName:Cs(e)||N||"Agent",userName:u,isCliMode:v.isCli||v.isAcp,isWorking:b.isGenerating,contextKey:e.tabKey,receivedAtMap:de,lastMessageHash:e.lastMessageHash,onLoadMore:ne,isLoadingMore:G,hasMoreHistory:I,hiddenLiveCount:K,loadError:D??void 0,emptyState:oe,scrollToBottomRequestNonce:d,isVisible:f}),s.jsx(Im,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:v.providerType,displayLabel:v.displayLabel,controls:(pe=v.targetEntry)==null?void 0:pe.providerControls,controlValues:(re=v.targetEntry)==null?void 0:re.controlValues,isActive:h,isCliTerminal:v.isCliTerminal}),!v.isCliTerminal&&s.jsx(ic,{contextKey:e.tabKey,panelLabel:N,isSending:n,isBusy:V,statusMessage:B,onSend:r,isActive:h,showControlsToggle:R.length>0,onControlsToggle:Y})]})}let Tc=ls;function Ic(){return Tc()}class Bf{constructor(){Ve(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 Mc=new Bf;class Kf{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 lt=new Kf;function Of(e){e.dashboardWS&&(Mc=e.dashboardWS),e.connectionManager&&(lt=e.connectionManager),e.useDaemonsHook&&(Tc=e.useDaemonsHook)}const Wf=.5,Hf=1.25;function it(e){return $a(e)}function ms(e){return mc(e).join(" · ")}function Ac(e){const t=uc(e);return t||(e.title?e.title:ms(e)||"No messages yet")}function Lc(e,t){const{isReconnecting:r,isConnecting:n}=Rs(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function Ff(e,t){const r=["Chat",...mc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function ss(e){return Lc(e)||ms(e)}function Uf(e){return`${it(e)} · ${Ac(e)}`}function zf(e){const t=zr(e),r=t?ot(t):Cs(e);return`${it(e)} — ${r||"Agent"}`}function Vf(e){return Cs(e)||"CLI"}function Rc(e){return dc(e)}function _c(e){return e?`Remote · ${it(e)||e.workspaceName||"Session"}`:"Remote"}function Gf({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:c=!0,isInputActive:l=!0}){var H;ls();const{sendPtyInput:u}=vt(),[m,d]=i.useState(!1),h=i.useRef(!1);h.current=m;const[f,w]=i.useState("Runtime terminal unavailable"),[k,p]=i.useState(!1),[y,x]=i.useState(null),[b,v]=i.useState(!1),[R,g]=i.useState(!1),[M,C]=i.useState(1),[S,j]=i.useState({width:0,height:0}),[W,L]=i.useState({width:0,height:0}),[I,D]=i.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[U,K]=i.useState(null),N=i.useRef(null),A=i.useRef(null),z=i.useRef(!1),$=i.useRef(!1),B=i.useRef(c),V=i.useRef(0),G=i.useRef(!1),me=i.useRef(""),ne=i.useRef(null),xe=i.useRef(!1),de=i.useRef(!1),be=i.useRef(null),he=i.useRef(null),Y=i.useRef(null),oe=32*1024,J=()=>{var _,T,P,F;return((T=(_=N.current)==null?void 0:_.ownerDocument)==null?void 0:T.defaultView)||((F=(P=A.current)==null?void 0:P.ownerDocument)==null?void 0:F.defaultView)||window},ue=_=>{const T=J();return{ownerWindow:T,frameId:T.requestAnimationFrame(_)}},le=()=>{const _=be.current;if(_){try{_.ownerWindow.cancelAnimationFrame(_.frameId)}catch{}be.current=null}},Se=()=>{const _=he.current;if(_){try{_.ownerWindow.clearTimeout(_.timeoutId)}catch{}he.current=null}},ie=()=>{const _=Y.current;if(_){try{_.ownerWindow.clearTimeout(_.timeoutId)}catch{}Y.current=null}},pe=()=>{c&&be.current===null&&(be.current=ue(()=>{tt()}))},re=e.tabKey,Z=e.sessionId||"",ee=e.daemonId||((H=e.routeId)==null?void 0:H.split(":")[0])||e.routeId||"",q=Ba(e),X=m?o||q:f,ae=Wf,je=Hf,ke=.05,te=()=>{const _=W.width,T=W.height;if(!Number.isFinite(S.width)||S.width<=0||!Number.isFinite(S.height)||S.height<=0||!Number.isFinite(_)||_<=0||!Number.isFinite(T)||T<=0)return 1;const P=S.width/_,F=S.height/T;return Number(Math.min(je,Math.max(ae,Math.min(P,F))).toFixed(2))},E=te(),ve=z.current&&M>E,Ce=Number.isFinite(W.width)&&W.width>0?Math.max(S.width,Math.round(W.width*M)):S.width,we=Number.isFinite(W.height)&&W.height>0?Math.max(S.height,Math.round(W.height*M)):S.height,Pe=()=>{ue(()=>{const _=A.current;_&&(_.scrollLeft=0,_.scrollTop=_.scrollHeight-_.clientHeight)})},Le=()=>{var _,T;V.current=0,G.current=!1,me.current="",ne.current=null,xe.current=!1,de.current=!1,z.current||($.current=!1,C(1)),be.current!==null&&le(),d(!1),w("Runtime terminal unavailable"),ie(),Se(),x(null),K(null),p(!1),v(!1),g(!1),(T=(_=r.current)==null?void 0:_.reset)==null||T.call(_)},Oe=()=>{var _,T;V.current=0,G.current=!1,me.current="",ne.current=null,xe.current=!1,de.current=!1,be.current!==null&&le(),d(!0),w(""),ie(),Se(),x(null),K(null),p(!1),v(!1),g(!1),(T=(_=r.current)==null?void 0:_.reset)==null||T.call(_)},ze=()=>{de.current&&(de.current=!1,ue(()=>{var _,T;(T=(_=r.current)==null?void 0:_.scrollToTop)==null||T.call(_)}))},tt=()=>{if(be.current=null,!c)return;const _=me.current;if(!_)return;const T=_.slice(0,oe);me.current=_.slice(T.length);const P=r.current;if(!P){me.current=T+me.current,pe();return}P.write(T,()=>{if(me.current.length>0){pe();return}ze()})},Xe=_=>{_&&(me.current+=_,pe())},Ye=(_,T=0,P,F,Q={})=>{var ce,Ne,De,$e;const ye=!!Q.force;!ye&&T>0&&V.current>=T||!ye&&T===0&&G.current||(V.current=T,T>0&&v(!0),d(!0),w(""),typeof P=="number"&&typeof F=="number"&&P>0&&F>0&&((Ne=(ce=r.current)==null?void 0:ce.resize)==null||Ne.call(ce,P,F)),me.current="",($e=(De=r.current)==null?void 0:De.reset)==null||$e.call(De),_?Xe(_):ze())};i.useEffect(()=>{Le()},[Z]),i.useEffect(()=>{var T;if(!Z)return;const _=((T=lt.onRuntimeEvent)==null?void 0:T.call(lt,Z,P=>{if(!(!P||P.sessionId!==Z)){if(P.type==="runtime_snapshot"){if(!c){ne.current={text:P.text||"",seq:P.seq||0,cols:P.cols,rows:P.rows,force:!!P.force};return}Ye(P.text||"",P.seq||0,P.cols,P.rows,{force:!!P.force});return}if(P.type==="session_output"){G.current=!0,typeof P.seq=="number"&&(V.current=Math.max(V.current,P.seq),P.seq>0&&v(!0)),h.current||d(!0),h.current||w(""),typeof P.data=="string"&&Xe(P.data);return}if(P.type==="session_cleared"){if(!c){xe.current=!0,me.current="",ne.current=null;return}Oe();return}if(P.type==="session_io_error"){const F=typeof P.error=="string"&&P.error?P.error:typeof P.reason=="string"&&P.reason?P.reason:"unknown error";d(!1),w(`Runtime input failed: ${F}`);return}}},ee))||(()=>{});return()=>{_()}},[ee,Z,r,c]);const mt=async(_={})=>{var T;if(!ee||!Z)return{success:!1,error:"daemonId and sessionId are required"};_.preserveStatus||w(_.loadingMessage||"Loading runtime terminal...");try{const P=await((T=lt.requestRuntimeSnapshot)==null?void 0:T.call(lt,ee,Z,{sinceSeq:_.sinceSeq,force:_.force}));return P&&P.success===!1?(_.preserveStatus||(d(!1),w(`Runtime terminal unavailable: ${P.error}`)),P):P||{success:!0}}catch(P){const F=(P==null?void 0:P.message)||String(P);return _.preserveStatus||(d(!1),w(`Runtime terminal unavailable: ${F}`)),{success:!1,error:F}}},pt=async _=>{var ye,ce;const T=((ye=N.current)==null?void 0:ye.ownerDocument)||document,P=T.defaultView||window,F=(ce=P.navigator)==null?void 0:ce.clipboard;if(F!=null&&F.writeText&&P.isSecureContext)try{return await F.writeText(_),!0}catch{}let Q=null;try{return Q=T.createElement("textarea"),Q.value=_,Q.setAttribute("readonly","true"),Q.style.position="fixed",Q.style.left="-9999px",Q.style.top="0",T.body.appendChild(Q),Q.focus(),Q.select(),T.execCommand("copy")}catch{return!1}finally{Q==null||Q.remove()}},dt=_=>{Se(),K(_);const T=J();he.current={ownerWindow:T,timeoutId:T.setTimeout(()=>{he.current=null,K(P=>P===_?null:P)},2200)}},Te=_=>{ie(),x(_);const T=J();Y.current={ownerWindow:T,timeoutId:T.setTimeout(()=>{Y.current=null,x(P=>P===_?null:P)},2200)}},Fe=async()=>{var Q,ye,ce,Ne;const _=((ye=(Q=r.current)==null?void 0:Q.getSelection)==null?void 0:ye.call(Q))||"",T=((Ne=(ce=r.current)==null?void 0:ce.getVisibleText)==null?void 0:Ne.call(ce))||"",P=_.trimEnd()||T.trimEnd();if(!P){dt("Nothing to copy");return}if(!await pt(P)){dt("Copy failed");return}dt(_.trimEnd()?"Copied selection":"Copied visible terminal")},Ge=async()=>{if(k)return;p(!0),x("Loading older terminal output..."),de.current=!0;const _=await mt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),(_==null?void 0:_.success)===!1){de.current=!1,x(`Older terminal output unavailable: ${_.error}`);return}g(!0),Te("Older terminal output loaded"),ue(()=>{var T;(T=r.current)==null||T.bumpResize()})};i.useEffect(()=>{var T,P;if(!Z)return;ee&&((T=lt.getState)==null?void 0:T.call(lt,ee))==="connected"&&mt();const _=(P=lt.onStateChange)==null?void 0:P.call(lt,(F,Q)=>{F!==ee||Q!=="connected"||mt()});return()=>{_==null||_()}},[ee,Z,r]),i.useEffect(()=>{t&&Le()},[t,re,r]),i.useEffect(()=>{var F,Q;const _=N.current,T=(Q=(F=_==null?void 0:_.ownerDocument)==null?void 0:F.defaultView)==null?void 0:Q.ResizeObserver;if(!_||!T)return;const P=new T(ye=>{const ce=ye[0];if(!ce)return;const{width:Ne,height:De}=ce.contentRect;j($e=>{const Ie=Math.round(Ne),Re=Math.round(De);return $e.width===Ie&&$e.height===Re?$e:{width:Ie,height:Re}})});return P.observe(_),()=>P.disconnect()},[]),i.useEffect(()=>{if(z.current)return;const _=te();!Number.isFinite(_)||_<=0||C(T=>$.current?_<T-ke?_:T:($.current=!0,_))},[W.height,W.width,S.height,S.width]),i.useEffect(()=>{ve&&Pe()},[ve,we,Ce]),i.useEffect(()=>{var P;const _=B.current;if(B.current=c,!c)return;_||g(!1),xe.current&&(xe.current=!1,Oe());const T=ne.current;T&&(ne.current=null,Ye(T.text,T.seq,T.cols,T.rows,{force:!!T.force})),ee&&Z&&((P=lt.getState)==null?void 0:P.call(lt,ee))==="connected"&&mt(),me.current&&be.current===null&&pe(),ue(()=>{var F;(F=r.current)==null||F.bumpResize()})},[ee,c,Z]),i.useEffect(()=>()=>{be.current!==null&&le(),Se(),ie()},[]),i.useEffect(()=>{const _=F=>{var ye;const Q=F.detail;Q!=null&&Q.sessionId&&Q.sessionId!==Z||m&&((ye=r.current)==null||ye.bumpResize())},T=J(),P=T===window?[window]:[window,T];for(const F of P)F.addEventListener("adhdev:fit-cli-terminal",_);return()=>{for(const F of P)F.removeEventListener("adhdev:fit-cli-terminal",_)}},[m,Z,r]);const ft=m&&b&&!R&&(I.atTop||!I.canScroll)||k||!!y;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:N,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[ft&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ge()},disabled:!Z||k,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:k?"Loading older...":"Load older terminal output"}),y&&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:y})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[U&&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:U}),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:()=>{Fe()},disabled:!m,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{z.current=!0,C(_=>{const T=Math.max(E,Number((_-.1).toFixed(2)));return T>E&&Pe(),T})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{z.current=!0,C(_=>{const T=Math.min(je,Number((_+.1).toFixed(2)));return T>E&&Pe(),T})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:A,className:ve?"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:Ce>0?`${Ce}px`:"100%",height:we>0?`${we}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:W.width>0?`${W.width}px`:"100%",height:W.height>0?`${W.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:M},children:s.jsx(Xi,{ref:r,readOnly:!m||!c,sizingMode:"measured",onViewportMetrics:L,onScrollMetrics:D,onInput:_=>{!m||(u==null||u(ee,Z,_))}})})})}),!m&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:f})]}),s.jsx(ic,{contextKey:e.tabKey,panelLabel:it(e),isSending:a,isBusy:!!q,statusMessage:X,onSend:async _=>q?!1:n(_),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const qf=5e3,Yf=12e3;function Xf(e){return e==="disconnected"||e==="reconnecting"}function Jf({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=qf,reconnectActionDelayMs:o=Yf}){const c=Xf(e),[l,u]=i.useState(()=>!c||a<=0),[m,d]=i.useState(()=>!c||o<=0),h=i.useRef(!1);i.useEffect(()=>{if(!c){u(!1);return}if(h.current=!1,a<=0){h.current=!0,u(!0);return}u(!1);const g=setTimeout(()=>{h.current=!0,u(!0)},a);return()=>clearTimeout(g)},[a,c]),i.useEffect(()=>{if(!c){d(!1);return}if(o<=0){d(!0);return}d(!1);const g=setTimeout(()=>{d(!0)},o);return()=>clearTimeout(g)},[o,c]);const f=c?l:e==="offline"||e==="auth_failed",w=!!(n&&e!=="auth_failed"&&(!c||m)),k=i.useMemo(()=>!t||e!=="connected"?!1:a<=0||h.current,[a,t,e]),p=e==="auth_failed"?"red":e==="offline"?"orange":"accent",y={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",R={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[f&&s.jsx("div",{className:v,style:R,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:y[p],border:x[p],color:b[p]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),w&&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"})]})}),k&&s.jsx("div",{className:v,style:R,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 Qf({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",u=()=>{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:u,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 za({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(Ma,{size:n}):s.jsx(Ht,{size:n})})}const Dt="New session",Pc="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 Zf(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 ep(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 tp(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 cn({git:e,className:t="",compact:r=!1}){const n=Zf(e),a=ep(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 ${tp(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 sp({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 Fo({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Uo({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const c=sn(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:u=>{u.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),o()},children:"Delete"})]})]})}function rp({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:u,onHideConversation:m,hiddenConversations:d=[],onShowConversation:h,onShowAllHidden:f,onResetPanelsToMain:w,inboxOpen:k,onInboxOpenChange:p,hiddenOpen:y,onHiddenOpenChange:x,onOpenNewSession:b,onOpenDashboardGuide:v,guideNudgeVisible:R=!1,actionShortcuts:g,notifications:M,notificationUnreadCount:C,onOpenNotification:S,onMarkNotificationRead:j,onMarkNotificationUnread:W,onDeleteNotification:L}){const{ides:I,p2pStates:D={}}=ls(),U=!!e&&Ze(e)&&!qe(e),K=!!e&&qe(e),N=l||(e?cc(e)?"terminal":"chat":null),[A,z]=i.useState(!1),$=i.useRef(null),B=i.useRef(null),V=I.filter(J=>J.type==="adhdev-daemon"),G=sp({wsStatus:t,isConnected:r,daemonCount:V.length,p2pStates:D}),me=G.subtitle,ne=G.tone==="connected"?"#22c55e":G.tone==="limited"?"#eab308":"#ef4444",xe=G.tone==="connected"?"0 0 4px #22c55e80":G.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",de=i.useMemo(()=>M.filter(J=>!J.readAt),[M]),be=i.useMemo(()=>M.filter(J=>!!J.readAt),[M]),he=i.useMemo(()=>de.slice(0,9),[de]),Y=C;i.useEffect(()=>{if(!k)return;const J=ue=>{var le;(le=$.current)!=null&&le.contains(ue.target)||p(!1)};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[k,p]),i.useEffect(()=>{if(!y)return;const J=ue=>{var le;(le=B.current)!=null&&le.contains(ue.target)||x(!1)};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[y,x]),i.useEffect(()=>{if(!y&&!k)return;const J=ue=>{if(!ue.altKey)return;const le=ue.code.match(/^Digit([1-9])$/);if(!le)return;const Se=Number(le[1])-1,ie=y?d[Se]:void 0,pe=k?he[Se]:void 0;if(!(!ie&&!pe)){if(ue.preventDefault(),ue.stopPropagation(),ie){h==null||h(ie),x(!1);return}pe&&(S(pe),p(!1))}};return window.addEventListener("keydown",J,!0),()=>window.removeEventListener("keydown",J,!0)},[d,y,k,he,x,p,S,h]);const oe=J=>{if(!J)return;const ue=n.find(le=>le.tabKey===J);ue&&(m==null||m(ue))};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(Ht,{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:ne,boxShadow:xe}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[s.jsx("span",{title:G.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:ne,boxShadow:xe}}),me&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",me]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${Dt}${g!=null&&g.openNewSession?` (${g.openNewSession})`:""}`,"aria-label":Dt,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:"?"}),R&&s.jsx("span",{children:"Guide"})]}),e&&(U||K||!qe(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:ms(e)||it(e),children:it(e)}),s.jsx(cn,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(U||K)&&c&&s.jsxs(s.Fragment,{children:[U&&u&&N&&s.jsx(za,{mode:N,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:K?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(wt,{size:14})})]}),!qe(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(Ia,{size:14})}),!U&&!qe(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Nt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:$,children:[s.jsxs("div",{className:`dashboard-header-hidden${A?" is-drop-target":""}`,ref:B,onDragEnter:J=>{J.dataTransfer.types.includes("text/tab-key")&&(J.preventDefault(),z(!0))},onDragOver:J=>{J.dataTransfer.types.includes("text/tab-key")&&(J.preventDefault(),J.dataTransfer.dropEffect="move",z(!0))},onDragLeave:J=>{J.currentTarget.contains(J.relatedTarget)||z(!1)},onDrop:J=>{const ue=J.dataTransfer.getData("text/tab-key");J.preventDefault(),z(!1),oe(ue)},children:[s.jsxs("button",{type:"button",onClick:()=>x(!y),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(Fi,{size:16}),d.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),y&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(Fo,{value:g==null?void 0:g.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[w&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:w,children:"Reset panels"}),d.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),x(!1)},children:"Restore all"})]})]}),e&&m&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(Fo,{value:g==null?void 0:g.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:it(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(J=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(J),x(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:it(J)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(J)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(J)+1]}):null,ms(J)]})]},J.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!k),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(tn,{size:16}),Y>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:Y})]}),k&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[de.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),de.map(J=>s.jsx(Uo,{notification:J,shortcutIndex:he.indexOf(J)>=0?he.indexOf(J)+1:void 0,onOpen:()=>S(J),onMarkRead:()=>j(J.id),onMarkUnread:()=>W(J.id),onDelete:()=>L(J.id)},J.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(J=>s.jsx(Uo,{notification:J,onOpen:()=>S(J),onMarkRead:()=>j(J.id),onMarkUnread:()=>W(J.id),onDelete:()=>L(J.id)},J.id))]}),M.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function ht(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function np(e,t){return String(e||"")!==String(t||"")}function ap(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(u=>String(u||"").toLowerCase()).join(`
39
- `).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!sc(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
40
- `).includes(a)))}function op(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 Dc(e,t={}){return op(ap(e,t),t.sortMode||"recent")}function Yr(e){return e?"Resume saved history":"Start fresh"}function Va(e){return e?"Resuming saved history…":"Starting fresh…"}function ip(){return"Start fresh"}function Ec(e,t=!1){return e==="cli"?Yr(t):e==="ide"?"Start IDE":"Start ACP session"}function $c(e,t=!1){return e==="cli"?Va(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 lp(){return"Open saved history"}function dp(){return"Saved History"}function Ga(){return"Use saved history when you want continuity in the same provider conversation."}function up(){return"No saved history found yet."}function mp(){return"Refresh saved history"}function fp(){return"Refreshing saved history…"}function rs(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function ns(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 Is(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ms(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function qa(e){return`Resume saved history with ${e}?`}function Ya(){return"Review or change the target workspace before resuming saved history."}function pp(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 Xa({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,missingWorkspaceResumePath:u,onSavedHistoryFiltersChange:m,onClose:d,onNewChat:h,onSwitchSession:f,onRefreshHistory:w,onResumeSavedSession:k}){var L;const p=t.find(I=>I.id===e.routeId),y=(p==null?void 0:p.chats)||[],x=(L=p==null?void 0:p.activeChat)==null?void 0:L.id,b=Ze(e)&&!qe(e),[v,R]=i.useState(()=>ht()),g=l||v,M=String(u||"").trim(),C=I=>{if(m){m(I);return}R(I)},S=i.useMemo(()=>a.map(I=>{const D=String(I.workspace||"").trim();return I.canResume||D||!M?I:{...I,workspace:M,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[M,a]),j=i.useMemo(()=>Dc(S,{textQuery:g.textQuery,workspaceQuery:g.workspaceQuery,modelQuery:g.modelQuery,resumableOnly:g.resumableOnly,sortMode:g.sortMode}),[S,g.modelQuery,g.resumableOnly,g.sortMode,g.textQuery,g.workspaceQuery]),W=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:d,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:b?dp():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:zf(e)}),b&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ga()})]}),s.jsx("button",{onClick:d,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(wt,{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:h,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),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:I=>C({...g,textQuery:I.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:I=>C({...g,workspaceQuery:I.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:I=>C({...g,modelQuery:I.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:I=>C({...g,sortMode:I.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:I=>C({...g,resumableOnly:I.target.checked})}),"Resume-ready only"]})]}),j.map(I=>{const D=e.providerSessionId===I.providerSessionId,U=D||!I.canResume||!!c,K=I.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{U||!k||k(I)},disabled:U,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${D?"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 ${D?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:I.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:I.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:pp(I.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:I.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:[I.workspace||"Workspace unknown",K?" · selected workspace":"",us(I.summaryMetadata)?` · ${us(I.summaryMetadata)}`:"",I.messageCount>0?` · ${I.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:D?"ACTIVE":I.canResume?K?"RESUME IN SELECTED WORKSPACE":c===I.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},I.id)})]}):y.map(I=>s.jsxs("div",{onClick:()=>{f(e.routeId,I.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===I.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===I.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:I.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:[I.id.substring(0,12),"..."]}),x===I.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},I.id)),(b&&!o&&j.length===0||!b&&y.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(Zd,{size:32})}),s.jsx("div",{className:"text-[13px]",children:b?a.length>0?"No saved history matches these filters.":up():"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:fp()})})]}),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:w,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(or,{size:13})," ",b?mp():"Refresh History"]})})})]})]});return typeof document>"u"?W:Zs.createPortal(W,document.body)}const zo={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 Bc({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=zo[n.type]||zo.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var o;(o=n.actions)!=null&&o.length||r&&r(n)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:o=>{o.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(wt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((o,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 hp=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function xp(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function bp(e){return e.sessionId||e.instanceId||e.agentType}function Nn(e,t){return e||t}function Kc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=St(r,{fallbackId:r.id}));return t}function Oc(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 Ja(e,t={}){return gp(e,Oc(e,t))}function gp(e,t={}){var h,f,w,k,p,y;const r=[],n=t.machineName,a=t.connectionState,o=xp(e),c=e.workspace||"",l=Gu(e.type,{agentName:e.cliName}),u=Ze(e)||qe(e)?l:ot(e.type),m=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||ot(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,surfaceHidden:x.surfaceHidden,git:x.git}}):[],d=hp(e);if(d){const x=e.sessionId||e.instanceId,b=l,v=(h=e.activeChat)==null?void 0:h.activeModal,R=v&&Array.isArray(v.buttons)&&v.buttons.length>0,g=bt((f=e.activeChat)==null?void 0:f.status,{activeModal:(w=e.activeChat)==null?void 0:w.activeModal})||bt((p=(k=e.agents)==null?void 0:k[0])==null?void 0:p.status)||"idle",M=e.activeChat||{title:"",messages:[]};let C=M.title&&String(M.title).trim()?String(M.title).trim():"";const S=(y=e.activeChat)==null?void 0:y.id,j=e.chats;if(S&&Array.isArray(j)&&j.length>0){const D=j.find(U=>U.id===S||U.id&&String(U.id)===String(S));D!=null&&D.title&&String(D.title).trim()&&(C=String(D.title).trim())}const W=(Ze(e)||qe(e),e.type),L=(Ze(e)||qe(e))&&Io(C,b,W)?"":C,I=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:Ze(e)?e.mode||"terminal":"chat",agentName:b,agentType:W,status:g,title:L,messages:I,resume:e.resume,hostIdeType:!Ze(e)&&!qe(e)?e.type:void 0,workspaceName:o,workspacePath:c,git:e.git,displayPrimary:L||o||(Ze(e)?e.mode==="chat"?b:"Terminal":b),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:R?v.buttons:void 0,modalMessage:R?v.message:void 0,streamSource:"native",tabKey:Nn(x,e.id),machineName:n,connectionState:a})}if(d&&(Ze(e)||qe(e)))return r;for(const x of m){const b=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,v=qu(x),R=bp(x),g=`${e.id}:${R}`,M=x.title&&String(x.title).trim()||"",C=Io(M,x.agentName,x.agentType)?"":M,S=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||S.length>0||b||C||!["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:C,messages:S,hostIdeType:e.type,workspaceName:o,workspacePath:c,git:x.git||e.git,displayPrimary:C||o||x.agentName||u,displaySecondary:`${u} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,modalButtons:b?x.activeModal.buttons:void 0,modalMessage:b?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Nn(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||u,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Nn(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function yp(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 Wc(e,t){const r=yp(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Hc=[{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:"🏄"}],Fc=[{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:"🧩"}],Uc=[{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:"🟠"}],vp=Hc,wp=Fc,jp=Uc;function fs(...e){return fd(pd(e))}function kp({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:fs("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 zc({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(kp,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:fs("mx-auto flex w-full flex-col gap-4",o,c),children:l})})]})}const xa="adhdev:themechange";function Sp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function gs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function ys(e){return e==="system"?Sp():e}function Vc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Rr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(xa,{detail:{preference:e,theme:t}}))}function Np(){const e=gs(),t=ys(e);Vc(t),Rr(e,t)}function Qa(){const[e,t]=i.useState(gs),[r,n]=i.useState(()=>ys(gs()));i.useEffect(()=>{Vc(r)},[r]),i.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const m=u.matches?"light":"dark";n(m),Rr("system",m)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),i.useEffect(()=>{const c=u=>{const m=u.detail||{},d=m.preference,h=m.theme;t(d==="dark"||d==="light"||d==="system"?d:gs()),n(h==="dark"||h==="light"?h:ys(gs()))},l=u=>{if(u.key!=="theme")return;const m=gs(),d=ys(m);t(m),n(d)};return window.addEventListener(xa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(xa,c),window.removeEventListener("storage",l)}},[]);const a=i.useCallback(c=>{const l=ys(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Rr(c,l)},[]),o=i.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=ys(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Rr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const Vo={dark:"Dark",light:"Light",system:"System"};function Cp({collapsed:e}){const{preference:t,cycleTheme:r}=Qa(),n=t==="dark"?s.jsx(tu,{size:16}):t==="light"?s.jsx(eu,{size:16}):s.jsx(su,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Vo[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Vo[t]})]})}function Cn(e,t){return e?typeof e=="function"?e(t):e:null}function Tp({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:c,preMainContent:l,collapsedStorageKey:u="sidebar-collapsed"}){const[m,d]=i.useState(!1),[h,f]=i.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),w=()=>d(!0),k=()=>d(!1),p=()=>{f(v=>{const R=!v;try{localStorage.setItem(u,R?"1":"0")}catch{}return R})},y=i.useMemo(()=>({collapsed:h,mobileMenuOpen:m,openMobileMenu:w,closeMobileMenu:k,toggleCollapsed:p}),[h,m]),x=v=>`nav-item${v.active?" active":""} cursor-pointer ${h?"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(),k()},title:h?v.title??(typeof v.label=="string"?v.label:void 0):v.title,children:[s.jsx("span",{className:"nav-icon",children:v.icon}),!h&&v.label]},v.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:w,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),m&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:k,onKeyDown:v=>v.key==="Escape"&&k()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:Cn(t,y)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:k,children:s.jsx(wt,{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:[!h&&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),Cn(o,y),s.jsx(Cp,{collapsed:h}),Cn(c,y)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function kt({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:fs("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 Gc({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:fs("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 Ip={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"},Mp={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function wr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:fs("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Ip[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Mp[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 Ap={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"},Lp={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Rp({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:fs("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Ap[e],r),children:[s.jsx("span",{className:fs("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Lp[e])}),n]})}function Qt({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 _p({onPrefChange:e}){const[t,r]=nm(),[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(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(tn,{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(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nt,{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:()=>{ac().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(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ru,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>o("completionAlert",c)}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(nu,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>o("approvalAlert",c)}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(sr,{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 Xr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Pp(e,t){const r=Xr(e),n=Xr(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 qc(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function Xs(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Pp(r,t)>=0)return!1;const n=Xr(r),a=Xr(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Dp(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Tn(e,t){return e instanceof Error?e.message:t}function Ep({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(Gc,{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(Bp,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Go({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 Zs.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 $p(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...vp,...wp,...jp].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 Bp({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var U,K;const[o,c]=i.useState("idle"),[l,u]=i.useState(""),[m,d]=i.useState(null),[h,f]=i.useState("idle"),[w,k]=i.useState(""),p=e.version||null,y=((U=e.machine)==null?void 0:U.platform)||((K=e.system)==null?void 0:K.platform)||"",x=St(e,{fallbackId:e.id}),b=y==="win32"?"🪟":y==="darwin"?"🍎":"🐧",v=t.filter(N=>N.daemonId===e.id&&N.transport==="cdp-page"),R=t.filter(N=>N.daemonId===e.id&&N.transport==="pty"),g=t.filter(N=>N.daemonId===e.id&&N.transport==="acp"),M=e.p2p,C=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const N=Dp(await r(e.id,"daemon_upgrade",{}));N.alreadyLatest?(c("done"),u(`Already on v${N.version||"latest"}.`)):N.upgraded||N.success?(c("done"),u(`Upgrade to v${N.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(N.error||"Upgrade failed"))}catch(N){c("error"),u(Tn(N,"Connection lost during upgrade"))}}},S=async()=>{if(d(null),!!n){f("loading");try{await n(e.id),f("done"),k("Machine disconnected.")}catch(N){f("error"),k(Tn(N,"Failed to disconnect"))}}},j=async()=>{if(d(null),!!a){f("loading");try{await a(e.id),f("done"),k("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(N){f("error"),k(Tn(N,"Failed to revoke token"))}}},W="0.9.54",L=qc(e,W),I=Xs(e,W),D=v.length+R.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),"…"]}),p&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!L&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&L&&s.jsx("button",{onClick:C,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${W}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${I?"↑ Update now":`↑ Update${` to v${W}`}`}`}),n&&s.jsx("button",{onClick:()=>d("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>d("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Rp,{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&&D>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),D>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[v.map(N=>{const A=$p(N.type),z=N.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:A.icon}),s.jsx("span",{children:A.name}),z!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${z?"bg-green-400":"animate-pulse"}`,style:z?void 0:{background:"var(--status-warning)"},title:z?"CDP connected":"CDP connecting..."})]},N.id)}),R.map(N=>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:N.cliName||"CLI"})]},N.id)),g.map(N=>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:N.cliName||"ACP"})]},N.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||w)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||h==="error"?"text-red-400":o==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:w||l})]}),m==="disconnect"&&s.jsx(Go,{title:"🔌 Disconnect Machine",message:`Disconnect "${x}" from ADHDev?
38
+ \`\`\``}function gt(e){return(typeof e=="string"?e.trim():"")||void 0}function Wt(e,t){const r=gt(t);return r?`${e}:${r}`:void 0}function zt(e,t,r){const n=Wt(t,r),a=gt(r);n&&e.push(n),a&&e.push(a)}function vs(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function yc(e){return gt(e.providerSessionId)||gt(e.sessionId)||gt(e.tabKey)||gt(e.routeId)}function Oa(e){return vs([gt(e.providerSessionId),gt(e.sessionId)])}function js(e){const t=[];return zt(t,"provider",e.providerSessionId),zt(t,"session",e.sessionId),zt(t,"tab",e.tabKey),zt(t,"route",e.routeId),vs(t)}function Xm(e){const t=[];return gt(e.providerSessionId)?(zt(t,"provider",e.providerSessionId),vs(t)):gt(e.sessionId)?(zt(t,"session",e.sessionId),vs(t)):gt(e.tabKey)?(zt(t,"tab",e.tabKey),vs(t)):gt(e.routeId)?(zt(t,"route",e.routeId),vs(t)):[]}function Wa(e){return Wt("provider",e.providerSessionId)||Wt("session",e.sessionId)||Wt("tab",e.tabKey)||Wt("route",e.routeId)||"unknown:"}function cr(e){return Oa(e)[0]}function Jm(e){const t=gt(e.providerSessionId),r=gt(e.sessionId),n=gt(e.tabKey),a=gt(e.routeId),o=[Wt("provider",t),Wt("session",r),Wt("tab",n),Wt("route",a)].filter(u=>typeof u=="string"),c=js({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=Wa({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:yc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:cr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:c}}function la(e,t){const r=Jm(e);return Xm(t).some(n=>r.lookupKeys.includes(n))}function Do(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 ts(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=Do(t==null?void 0:t.receivedAt)||Do(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function da(e,t=0){return ts(e)||e.lastUpdated||t||0}function vc(e){return ts(e)||e.lastUpdated||0}function wc(e,t,r=vc){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 ua(e){var r;const t=bt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Qm(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!ua(e)&&!e.title.trim()}function Zm(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(ua(r))-Number(ua(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:wc(t,r)})[0]||null}function _t(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=Zm(a);return n?o&&Qm(n)?o:n:o||r[0]||null}function Gt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ha(e){return cr(e)||e.tabKey||e.routeId||null}function kc(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=_t(e.conversations,n)||e.conversations.find(o=>o.routeId===n);return a?Ha(a):null}function jc({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const o=Ls(),c=hs(e),l=dc(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",m=e.streamSource==="agent-stream"&&!!e.agentName,d=!m&&(e.transport==="pty"||e.transport==="acp"),h=Cs(e),f=$m(e),v=i.useCallback(()=>{if(n){n();return}c&&o("/dashboard",{state:{openMachineId:c}})},[c,o,n]),j=i.useCallback(()=>{if(r){r();return}const p=Ha(e);p&&o(Gt(p))},[e,o,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:j,title:f,children:[s.jsx(Nt,{size:12}),s.jsx("span",{children:f})]}):s.jsxs("span",{className:"conversation-meta-chip",title:f,children:[s.jsx(Nt,{size:12}),s.jsx("span",{children:f})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(sr,{size:12}),s.jsx("span",{children:h})]}),d&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(sr,{size:12}),s.jsx("span",{children:h})]}),l&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:v,title:l,children:[s.jsx(ds,{size:12}),s.jsx("span",{children:l})]}):s.jsxs("span",{className:"conversation-meta-chip",title:l,children:[s.jsx(ds,{size:12}),s.jsx("span",{children:l})]}))]})}function jn(e,t){return`${e}:${t}`}function ef(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Ks(e,t){ef()&&console.debug(`[subscription-manager] ${e}`,t)}class tf{constructor(){Ve(this,"active",new Map);Ve(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var d;const c=jn(n.topic,n.key),l=this.active.get(c);let u=!0;if(l)l.handlers.add(a),l.lastUpdate&&a(l.lastUpdate);else{const h={daemonId:r,request:n,handlers:new Set([a])};this.active.set(c,h),Ks("subscribe",{daemonId:r,topic:n.topic,key:n.key}),u=((d=t.sendData)==null?void 0:d.call(t,r,n))??!1,!u&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(c,t,o.retryIntervalMs)}const m=()=>{var v;this.clearRetry(c);const h=this.active.get(c);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(c);const f={type:"unsubscribe",topic:n.topic,key:n.key};Ks("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(v=t.sendData)==null||v.call(t,r,f)};return m.initialSendAccepted=u,m}publish(t){const r=jn(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Ss.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),Ss.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=jn(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;Ks("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);Ks("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;Ks("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 qt=new tf;function sf(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 rf(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 qr(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:c}=t,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:m,childrenByParent:d}=rf(u),h=sf(o,n),f=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,v=m.filter(y=>y.kind==="workspace"&&y.transport==="cdp-page"),j=m.filter(y=>y.kind==="agent"&&y.transport==="pty"),p=m.filter(y=>y.kind==="agent"&&y.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...f&&{machine:f,platform:f.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:v.some(y=>!!y.cdpConnected)});for(const y of v){const x=h.get(y.id),b=zs(y,x),w=(d.get(y.id)||[]).map(R=>zs(R,h.get(R.id)));r.push({id:`${n}:ide:${y.id}`,sessionId:y.id,providerSessionId:y.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:y.id,workspace:b.workspace,terminals:0,childSessions:w,agents:w.map(R=>({id:R.id,name:R.providerName||R.providerType,type:R.providerType,status:R.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 y of j){const x=h.get(y.id),b=zs(y,x);r.push({id:`${n}:cli:${y.id}`,sessionId:y.id,providerSessionId:y.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:y.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 y of p){const x=h.get(y.id),b=zs(y,x);r.push({id:`${n}:acp:${y.id}`,sessionId:y.id,providerSessionId:y.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:y.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 nf=15e3,af=15e3,of=6e4,cf=1200,Eo=12,lf=8e3,df=4e3,Sn=new Map,Nn=new Map,yr=new Set,Ys=new Map;function uf(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 $o(e,t){const r=Ys.get(e);!r||r.size===0||(Ys.delete(e),r.forEach(n=>n(t)))}function mf(e,t){return new Promise(r=>{const n=Ys.get(e)||new Set;Ys.set(e,n);const a=c=>{clearTimeout(o),n.delete(a),n.size===0&&Ys.delete(e),r(c)},o=setTimeout(()=>a(!1),t);n.add(a)})}function lr(){const{sendCommand:e,sendData:t}=vt(),{injectEntries:r,getIdes:n}=er();return i.useCallback(async(a,o)=>{if(!a)return;const c=(o==null?void 0:o.minFreshMs)??of,l=Nn.get(a)||0;if(!(o!=null&&o.force)&&yr.has(a)&&l>0||!(o!=null&&o.force)&&l>0&&Date.now()-l<c)return;const u=Sn.get(a);if(u)return u;const m=(async()=>{if(t&&!yr.has(a)){const p=qt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},y=>{const x=n(),b=x.find(R=>R.id===a),w=qr(y.status,{daemonId:a,existingDaemon:b,existingEntries:x,timestamp:y.timestamp});w.length>0&&r(w),Nn.set(a,Date.now()),$o(a,!0)});if(p.initialSendAccepted?yr.add(a):yr.delete(a),!(o!=null&&o.force)&&p.initialSendAccepted&&await mf(a,cf))return}const d=await e(a,"get_status_metadata"),h=uf(d);if(!h)return;const f=n(),v=f.find(p=>p.id===a),j=qr(h,{daemonId:a,existingDaemon:v,existingEntries:f,timestamp:h.timestamp||Date.now()});j.length>0&&r(j,{authoritativeDaemonIds:[a]}),Nn.set(a,Date.now()),$o(a,!0)})().finally(()=>{Sn.delete(a)});return Sn.set(a,m),m},[n,r,e,t])}function nr(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 Ft(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}function ff(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=Bt(e.content),o=Bt(t.content);if(!a||!o||!(a===o||fa(a,o)||fa(o,a)))return!1;const l=Ft(e),u=Ft(t);return l&&u?Math.abs(l-u)<=15e3:!!e._localId!=!!t._localId}function ma(e){return Bt(e==null?void 0:e.content)}function fa(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 Bo(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=ma(e),o=Ft(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 pf(e,t,r=ff){const n=new Map,a=o=>{for(const c of Bo(o)){const l=n.get(c);l?l.push(o):n.set(c,[o])}};return t.forEach(a),e.filter(o=>{const c=ma(o),l=String((o==null?void 0:o.role)||"").toLowerCase(),u=Ft(o),m=new Set;for(const h of Bo(o)){const f=n.get(h);f&&f.forEach(v=>m.add(v))}return!(m.size>0?Array.from(m):t).some(h=>{if(r(o,h))return!0;const f=String((h==null?void 0:h.role)||"").toLowerCase();if(!c||!l||l!==f)return!1;const v=ma(h);if(!fa(v,c)&&v!==c)return!1;const j=Ft(h);return u&&j?Math.abs(u-j)<=15e3:!0})})}const hf=60,xf=1e3;function Sc(e={}){return e.isCliLike?xf:hf}function bf(e={}){return Sc(e)}const dr=60,gf=1e3,Fa=12e4,yf=new Set(["generating","waiting_approval","starting","streaming","working"]),Ko=new Map;function Ua(e,t){return`${e}::${t}`}function pa(e=dr){return{liveMessages:[],cursor:Nc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Rr(e){return Bi(e)}function Nc(e,t=dr){return{knownMessageCount:e.length,lastMessageSignature:Rr(e[e.length-1]),tailLimit:t}}function vr(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 Oo(e){for(let t=e.length-1;t>=0;t-=1){const r=Ft(e[t]);if(r>0)return r}return 0}function vf(e,t){if(t.length===0)return!1;if(e.length===0)return!0;const r=Oo(e),n=Oo(t);return!(r>0&&n<=0||r>0&&n>0&&n<r||r>0&&n===r&&t.length<e.length)}function wf(e,t){if(t.length===0)return e;const r=[...e],n=new Map,a=(o,c)=>{for(const l of nr(o))n.set(l,c)};r.forEach(a);for(const o of t){const l=nr(o).map(u=>n.get(u)).find(u=>u!==void 0);if(l!==void 0){r[l]=o,a(o,l);continue}r.push(o),a(o,r.length-1)}return r}function kf(e,t){const r=Array.isArray(t.messages)?t.messages:[];switch(t.syncMode){case"noop":return e;case"append":return wf(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 jf{constructor(t){Ve(this,"manager");Ve(this,"sendData");Ve(this,"daemonId");Ve(this,"sessionId");Ve(this,"historySessionId");Ve(this,"subscriptionKey");Ve(this,"snapshot");Ve(this,"transportSubscription",null);Ve(this,"listeners",new Set);Ve(this,"retainCount",0);Ve(this,"loadHistoryPromise",null);Ve(this,"pendingDisconnectTimer",null);this.manager=t.manager||qt,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=pa(Math.max(0,t.tailLimit??dr))}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(!vf(this.snapshot.liveMessages,r))return;const n=r,a=Nc(n,this.snapshot.cursor.tailLimit);vr(this.snapshot.liveMessages)===vr(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=pf(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:gf}))}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=Rr(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 f={knownMessageCount:Math.max(this.snapshot.cursor.knownMessageCount,Number(t.totalMessages||0)),lastMessageSignature:r,tailLimit:this.snapshot.cursor.tailLimit};this.snapshot.cursor.knownMessageCount===f.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===f.lastMessageSignature||(this.snapshot={...this.snapshot,cursor:f},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:f.knownMessageCount,lastMessageSignature:f.lastMessageSignature}));return}const o=kf(this.snapshot.liveMessages,t),c=r||Rr(o[o.length-1]),l=!!r&&Rr(o[o.length-1])===r,m={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};vr(this.snapshot.liveMessages)===vr(o)&&this.snapshot.cursor.knownMessageCount===m.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===m.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:o,cursor:m},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:m.knownMessageCount,lastMessageSignature:m.lastMessageSignature}),this.emit())}}function Cc(e){const t=Ua(e.daemonId,e.sessionId),r=Ko.get(t);if(r)return r.updateOptions(e),r;const n=new jf(e);return Ko.set(t,n),n}function Sf(e,t){return{...e,loadHistoryPage:t}}function Nf(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Cf(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(yf.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??Fa)),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 Tf(e=Fa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Mf(e,t={}){const r=new Set,n=[];for(const a of e){if(!Cf(a,t))continue;const o=Ps(a),c=a.sessionId||"";if(!o||!c)continue;const l=Ua(o,c);if(r.has(l))continue;r.add(l);const u=cr(a);n.push({daemonId:o,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${o}:session:${c}`})}return n.sort(Nf),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function If(e,t){const{sendData:r,sendCommand:n}=vt(),a=(t==null?void 0:t.enabled)!==!1,o=Ps(e),c=e.sessionId||"",l=cr(e)||c,u=`daemon:${o}:session:${c}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??dr),d=i.useMemo(()=>!a||!o||!c?null:Cc({daemonId:o,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:m}),[o,a,l,r,c,u,m]),[h,f]=i.useState(()=>(d==null?void 0:d.getSnapshot())||pa(m));i.useEffect(()=>{if(!d){f(pa(m));return}d.retain(),f(d.getSnapshot());const j=d.subscribe(p=>{f(p)});return()=>{j(),d.release()}},[d,m]),i.useEffect(()=>{d&&(d.hydrateLiveMessages(e.messages),f(d.getSnapshot()))},[e.messages,d]);const v=i.useCallback(async()=>{!d||!o||!c||await d.loadHistoryPage(async({offset:j,excludeRecentCount:p})=>{const y=e.agentType,x=await n(o,"chat_history",{agentType:y,offset:j,limit:30,targetSessionId:c,historySessionId:l,excludeRecentCount:p}),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,d,o,l,n,c]);return i.useMemo(()=>Sf(h,v),[v,h])}function Af(e,t){const{sendData:r}=vt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??dr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Fa)),c=Tf(o),[l,u]=i.useState(0),[m,d]=i.useState(()=>new Map);i.useEffect(()=>{if(!n||e.length===0)return;const f=setInterval(()=>{u(v=>v+1)},c);return()=>{clearInterval(f)}},[e.length,n,c]);const h=i.useMemo(()=>Mf(e,{recentActivityMs:o}),[e,o,l]);return i.useEffect(()=>{if(!n||!r||h.descriptors.length===0){d(y=>y.size===0?y:new Map);return}const f=h.descriptors.map(y=>({key:Ua(y.daemonId,y.sessionId),controller:Cc({...y,sendData:r,tailLimit:a})})),v=new Set(f.map(({key:y})=>y)),j=(y,x)=>{d(b=>{const w=new Map(b);for(const R of w.keys())v.has(R)||w.delete(R);return w.set(y,x),w})},p=f.map(({key:y,controller:x})=>(x.retain(),j(y,x.getSnapshot()),x.subscribe(b=>j(y,b))));return()=>{p.forEach(y=>y()),f.forEach(({controller:y})=>y.release())}},[h.signature,n,r,a]),m}function Wo(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 Yr(e){for(let t=e.length-1;t>=0;t-=1){const r=Ft(e[t]);if(r>0)return r}return 0}function Lf(e){const t=Ps(e),r=e.sessionId||"";return t&&r?`${t}::${r}`:""}function Rf(e){const t=new Set;for(const r of e)for(const n of nr(r)){if(t.has(n))return!0;t.add(n)}return!1}function _f(e,t){const r=new Set(nr(e));return r.size===0?!1:nr(t).some(n=>r.has(n))}function Tc(e,t){return t.length===0||e.length<=t.length||!Rf(e)?!1:_f(e[e.length-1],t[t.length-1])}function Pf(e,t){if(t.length===0)return!1;const r=Array.isArray(e.messages)?e.messages:[];if(r.length===0)return!0;const n=Yr(r),a=Yr(t);if(n>0&&a===n&&Tc(r,t))return!0;if(n<=0||a<=n)return!1;const o=Wo(r,e.status),c=Wo(t,e.status);return o!==c}function Df(e,t){const r=t[t.length-1],n=Ft(r),a=Bt(r==null?void 0:r.content);return{...e,messages:t,...a?{lastMessagePreview:a}:{},...n>0?{lastMessageAt:n}:{}}}function Ef(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=Yr(r),o=Yr(n);if(a>0&&(o<=0||a>o))return r;if(a>0&&a===o){if(Tc(r,n))return n;if(r.length>=n.length)return r}return n}function $f(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 Ho(e,t){if(t.size===0||e.length===0)return e;let r=!1;const n=e.map(a=>{var l;const o=Lf(a);if(!o)return a;const c=((l=t.get(o))==null?void 0:l.liveMessages)||[];return Pf(a,c)?(r=!0,Df(a,c)):a});return r?n:e}function Bf(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Kf(e){return Bf(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function Of(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Wf(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function Hf(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Mc(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Ic(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 Ff(e){return Mc(e)?!1:e.inboxBucket==="task_complete"&&Ic(e).length>0}function Fo(e){return e.branch||"detached HEAD"}function Uf(e){if(e.error)return`${Fo(e)} · Git error: ${e.error}`;const t=[Fo(e)];return e.changedFiles>0?t.push(Of(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 zf(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Uf(t)}`}function Vf(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function Gf(e,t={}){if(t.enabled===!1)return[];if(!Hf(e))return[];const r=Mc(e)?"working":Ff(e)?"complete":null;if(!r)return[];const n=r==="complete"?Ic(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Wf(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:zf(r,e.git),timestamp:Vf(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 qf=60;function ha({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:o,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:m=!1,scrollToBottomRequestNonce:d,isInputActive:h=!0,isVisible:f=!0}){var J,ue,le,Se,ie,pe,ne;const v=i.useRef(new Map),j=i.useRef(void 0),p=lr(),{sendCommand:y}=vt(),{isVisible:x}=_a();ir("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const b=kt.useMemo(()=>Rs(e),[e.status,e.connectionState]),w=i.useMemo(()=>Om(e,t),[e,t]),R=i.useMemo(()=>{var Z;return Ea((Z=w.targetEntry)==null?void 0:Z.providerControls,{hostIdeType:e.hostIdeType,providerType:w.providerType})},[e.hostIdeType,w.providerType,(J=w.targetEntry)==null?void 0:J.providerControls]),g=Sc({isCliLike:w.isCli||w.isAcp}),I=bf({isCliLike:w.isCli||w.isAcp}),C=If(e,{enabled:f&&!!e.sessionId,tailLimit:I}),[S,k]=i.useState(g),W=e.tabKey,L=C.historyMessages,M=C.hasMoreHistory,E=C.historyError,U=Ef(e,C);i.useEffect(()=>{k(g)},[g,W]);const K=Math.max(0,U.length-S),N=$a(e),A=Ps(e),z=Kf(e),$=Ba(e),B=a||$,G=!!$,[V,me]=i.useState(!1);i.useEffect(()=>{const Z=w.targetEntry;A&&(!Z||Z.providerControls===void 0||Z.controlValues===void 0)&&p(A,{minFreshMs:3e4}).catch(()=>{})},[A,w.isAcp,(ue=w.targetEntry)==null?void 0:ue.providerControls,(le=w.targetEntry)==null?void 0:le.controlValues,p]);const ae=i.useCallback(async()=>{if(!V){if(U.length>S){k(Z=>Math.min(U.length,Z+qf));return}me(!0);try{await C.loadHistoryPage()}finally{me(!1)}}},[C,V,U.length,S]),{allMessages:xe,receivedAtMap:de}=i.useMemo(()=>{const Z=$f({historyMessages:L,liveMessages:U,visibleLiveCount:S}),ee=Gf(e),q=ee.length>0?[...Z,...ee]:Z,X={};return q.forEach((re,je)=>{const we=`${e.tabKey}:${Fr(re,je)}`;let te=Ft(re)||v.current.get(we)||0;te||(te=Date.now(),v.current.set(we,te)),X[Fr(re,je)]=te}),{allMessages:q,receivedAtMap:X}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,K,L,U,S]),be=i.useMemo(()=>l.filter(Z=>Z.routeId===e.tabKey).sort((Z,ee)=>Z.timestamp-ee.timestamp),[l,e.tabKey]),he=i.useCallback(async()=>{var je,we,te;if(!A)return;const Z=xc({activeConv:e,visibleMessages:xe,actionLogs:l,controls:(je=w.targetEntry)==null?void 0:je.providerControls,controlValues:(we=w.targetEntry)==null?void 0:we.controlValues,visibleBarControlCount:R.length,chatTailState:{hasMoreHistory:M,historyError:E,historyMessages:L},ui:{controlsVisible:x,visibleLiveCount:S,hiddenLiveCount:K,isInputActive:h,isVisible:f}}),ee=await y(A,"get_chat_debug_bundle",{agentType:w.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:Z}),q=Gr(ee),X=gc(q);let re=!1;if((te=navigator.clipboard)!=null&&te.writeText&&window.isSecureContext)try{await navigator.clipboard.writeText(X),re=!0}catch(D){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",D)}if(!re){let D=null;try{D=document.createElement("textarea"),D.value=X,D.setAttribute("readonly","true"),D.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(D),D.focus(),D.select(),re=document.execCommand("copy")}catch{}finally{D==null||D.remove()}}re||console.warn("[chat-debug-bundle] failed to copy debug bundle locator to clipboard"),et.showToast(bc(q,{locatorCopied:re}),re?"success":"warning")},[e,l,xe,x,w.providerType,(Se=w.targetEntry)==null?void 0:Se.controlValues,(ie=w.targetEntry)==null?void 0:ie.providerControls,A,M,K,L,h,f,E,y,R.length,S]),Y=i.useCallback(()=>{const Z=Ym(j.current);j.current=Z.state,Z.shouldCollect&&he().catch(ee=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",ee),et.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[he]),oe=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")&&me(!1),e.status==="not_monitored"&&z)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(sr,{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(Ns,{size:14})," Open ",N," 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"&&z)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(Fi,{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(Ns,{size:14})," Open ",N," 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"&&!V)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,z,o,c,V,U.length,N,b.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&s.jsx(jc,{conversation:e,className:"chat-pane-meta-row"}),s.jsx(Iu,{messages:xe,actionLogs:be,agentName:Cs(e)||N||"Agent",userName:u,isCliMode:w.isCli||w.isAcp,isWorking:b.isGenerating,contextKey:e.tabKey,receivedAtMap:de,lastMessageHash:e.lastMessageHash,onLoadMore:ae,isLoadingMore:V,hasMoreHistory:M,hiddenLiveCount:K,loadError:E??void 0,emptyState:oe,scrollToBottomRequestNonce:d,isVisible:f}),s.jsx(Lm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:w.providerType,displayLabel:w.displayLabel,controls:(pe=w.targetEntry)==null?void 0:pe.providerControls,controlValues:(ne=w.targetEntry)==null?void 0:ne.controlValues,isActive:h,isCliTerminal:w.isCliTerminal}),!w.isCliTerminal&&s.jsx(cc,{contextKey:e.tabKey,panelLabel:N,isSending:n,isBusy:G,statusMessage:B,onSend:r,isActive:h,showControlsToggle:R.length>0,onControlsToggle:Y})]})}let Ac=ls;function Lc(){return Ac()}class Yf{constructor(){Ve(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 Rc=new Yf;class Xf{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 lt=new Xf;function Jf(e){e.dashboardWS&&(Rc=e.dashboardWS),e.connectionManager&&(lt=e.connectionManager),e.useDaemonsHook&&(Ac=e.useDaemonsHook)}const Qf=.5,Zf=1.25;function it(e){return $a(e)}function ms(e){return fc(e).join(" · ")}function _c(e){const t=mc(e);return t||(e.title?e.title:ms(e)||"No messages yet")}function Pc(e,t){const{isReconnecting:r,isConnecting:n}=Rs(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function ep(e,t){const r=["Chat",...fc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function ss(e){return Pc(e)||ms(e)}function tp(e){return`${it(e)} · ${_c(e)}`}function sp(e){const t=Vr(e),r=t?ot(t):Cs(e);return`${it(e)} — ${r||"Agent"}`}function rp(e){return Cs(e)||"CLI"}function Dc(e){return uc(e)}function Ec(e){return e?`Remote · ${it(e)||e.workspaceName||"Session"}`:"Remote"}function np({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:c=!0,isInputActive:l=!0}){var H;ls();const{sendPtyInput:u}=vt(),[m,d]=i.useState(!1),h=i.useRef(!1);h.current=m;const[f,v]=i.useState("Runtime terminal unavailable"),[j,p]=i.useState(!1),[y,x]=i.useState(null),[b,w]=i.useState(!1),[R,g]=i.useState(!1),[I,C]=i.useState(1),[S,k]=i.useState({width:0,height:0}),[W,L]=i.useState({width:0,height:0}),[M,E]=i.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[U,K]=i.useState(null),N=i.useRef(null),A=i.useRef(null),z=i.useRef(!1),$=i.useRef(!1),B=i.useRef(c),G=i.useRef(0),V=i.useRef(!1),me=i.useRef(""),ae=i.useRef(null),xe=i.useRef(!1),de=i.useRef(!1),be=i.useRef(null),he=i.useRef(null),Y=i.useRef(null),oe=32*1024,J=()=>{var _,T,P,F;return((T=(_=N.current)==null?void 0:_.ownerDocument)==null?void 0:T.defaultView)||((F=(P=A.current)==null?void 0:P.ownerDocument)==null?void 0:F.defaultView)||window},ue=_=>{const T=J();return{ownerWindow:T,frameId:T.requestAnimationFrame(_)}},le=()=>{const _=be.current;if(_){try{_.ownerWindow.cancelAnimationFrame(_.frameId)}catch{}be.current=null}},Se=()=>{const _=he.current;if(_){try{_.ownerWindow.clearTimeout(_.timeoutId)}catch{}he.current=null}},ie=()=>{const _=Y.current;if(_){try{_.ownerWindow.clearTimeout(_.timeoutId)}catch{}Y.current=null}},pe=()=>{c&&be.current===null&&(be.current=ue(()=>{tt()}))},ne=e.tabKey,Z=e.sessionId||"",ee=e.daemonId||((H=e.routeId)==null?void 0:H.split(":")[0])||e.routeId||"",q=Ba(e),X=m?o||q:f,re=Qf,je=Zf,we=.05,te=()=>{const _=W.width,T=W.height;if(!Number.isFinite(S.width)||S.width<=0||!Number.isFinite(S.height)||S.height<=0||!Number.isFinite(_)||_<=0||!Number.isFinite(T)||T<=0)return 1;const P=S.width/_,F=S.height/T;return Number(Math.min(je,Math.max(re,Math.min(P,F))).toFixed(2))},D=te(),ve=z.current&&I>D,Ce=Number.isFinite(W.width)&&W.width>0?Math.max(S.width,Math.round(W.width*I)):S.width,ke=Number.isFinite(W.height)&&W.height>0?Math.max(S.height,Math.round(W.height*I)):S.height,Pe=()=>{ue(()=>{const _=A.current;_&&(_.scrollLeft=0,_.scrollTop=_.scrollHeight-_.clientHeight)})},Le=()=>{var _,T;G.current=0,V.current=!1,me.current="",ae.current=null,xe.current=!1,de.current=!1,z.current||($.current=!1,C(1)),be.current!==null&&le(),d(!1),v("Runtime terminal unavailable"),ie(),Se(),x(null),K(null),p(!1),w(!1),g(!1),(T=(_=r.current)==null?void 0:_.reset)==null||T.call(_)},Oe=()=>{var _,T;G.current=0,V.current=!1,me.current="",ae.current=null,xe.current=!1,de.current=!1,be.current!==null&&le(),d(!0),v(""),ie(),Se(),x(null),K(null),p(!1),w(!1),g(!1),(T=(_=r.current)==null?void 0:_.reset)==null||T.call(_)},ze=()=>{de.current&&(de.current=!1,ue(()=>{var _,T;(T=(_=r.current)==null?void 0:_.scrollToTop)==null||T.call(_)}))},tt=()=>{if(be.current=null,!c)return;const _=me.current;if(!_)return;const T=_.slice(0,oe);me.current=_.slice(T.length);const P=r.current;if(!P){me.current=T+me.current,pe();return}P.write(T,()=>{if(me.current.length>0){pe();return}ze()})},Xe=_=>{_&&(me.current+=_,pe())},Ye=(_,T=0,P,F,Q={})=>{var ce,Ne,De,$e;const ye=!!Q.force;!ye&&T>0&&G.current>=T||!ye&&T===0&&V.current||(G.current=T,T>0&&w(!0),d(!0),v(""),typeof P=="number"&&typeof F=="number"&&P>0&&F>0&&((Ne=(ce=r.current)==null?void 0:ce.resize)==null||Ne.call(ce,P,F)),me.current="",($e=(De=r.current)==null?void 0:De.reset)==null||$e.call(De),_?Xe(_):ze())};i.useEffect(()=>{Le()},[Z]),i.useEffect(()=>{var T;if(!Z)return;const _=((T=lt.onRuntimeEvent)==null?void 0:T.call(lt,Z,P=>{if(!(!P||P.sessionId!==Z)){if(P.type==="runtime_snapshot"){if(!c){ae.current={text:P.text||"",seq:P.seq||0,cols:P.cols,rows:P.rows,force:!!P.force};return}Ye(P.text||"",P.seq||0,P.cols,P.rows,{force:!!P.force});return}if(P.type==="session_output"){V.current=!0,typeof P.seq=="number"&&(G.current=Math.max(G.current,P.seq),P.seq>0&&w(!0)),h.current||d(!0),h.current||v(""),typeof P.data=="string"&&Xe(P.data);return}if(P.type==="session_cleared"){if(!c){xe.current=!0,me.current="",ae.current=null;return}Oe();return}if(P.type==="session_io_error"){const F=typeof P.error=="string"&&P.error?P.error:typeof P.reason=="string"&&P.reason?P.reason:"unknown error";d(!1),v(`Runtime input failed: ${F}`);return}}},ee))||(()=>{});return()=>{_()}},[ee,Z,r,c]);const mt=async(_={})=>{var T;if(!ee||!Z)return{success:!1,error:"daemonId and sessionId are required"};_.preserveStatus||v(_.loadingMessage||"Loading runtime terminal...");try{const P=await((T=lt.requestRuntimeSnapshot)==null?void 0:T.call(lt,ee,Z,{sinceSeq:_.sinceSeq,force:_.force}));return P&&P.success===!1?(_.preserveStatus||(d(!1),v(`Runtime terminal unavailable: ${P.error}`)),P):P||{success:!0}}catch(P){const F=(P==null?void 0:P.message)||String(P);return _.preserveStatus||(d(!1),v(`Runtime terminal unavailable: ${F}`)),{success:!1,error:F}}},pt=async _=>{var ye,ce;const T=((ye=N.current)==null?void 0:ye.ownerDocument)||document,P=T.defaultView||window,F=(ce=P.navigator)==null?void 0:ce.clipboard;if(F!=null&&F.writeText&&P.isSecureContext)try{return await F.writeText(_),!0}catch{}let Q=null;try{return Q=T.createElement("textarea"),Q.value=_,Q.setAttribute("readonly","true"),Q.style.position="fixed",Q.style.left="-9999px",Q.style.top="0",T.body.appendChild(Q),Q.focus(),Q.select(),T.execCommand("copy")}catch{return!1}finally{Q==null||Q.remove()}},dt=_=>{Se(),K(_);const T=J();he.current={ownerWindow:T,timeoutId:T.setTimeout(()=>{he.current=null,K(P=>P===_?null:P)},2200)}},Te=_=>{ie(),x(_);const T=J();Y.current={ownerWindow:T,timeoutId:T.setTimeout(()=>{Y.current=null,x(P=>P===_?null:P)},2200)}},Fe=async()=>{var Q,ye,ce,Ne;const _=((ye=(Q=r.current)==null?void 0:Q.getSelection)==null?void 0:ye.call(Q))||"",T=((Ne=(ce=r.current)==null?void 0:ce.getVisibleText)==null?void 0:Ne.call(ce))||"",P=_.trimEnd()||T.trimEnd();if(!P){dt("Nothing to copy");return}if(!await pt(P)){dt("Copy failed");return}dt(_.trimEnd()?"Copied selection":"Copied visible terminal")},Ge=async()=>{if(j)return;p(!0),x("Loading older terminal output..."),de.current=!0;const _=await mt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),(_==null?void 0:_.success)===!1){de.current=!1,x(`Older terminal output unavailable: ${_.error}`);return}g(!0),Te("Older terminal output loaded"),ue(()=>{var T;(T=r.current)==null||T.bumpResize()})};i.useEffect(()=>{var T,P;if(!Z)return;ee&&((T=lt.getState)==null?void 0:T.call(lt,ee))==="connected"&&mt();const _=(P=lt.onStateChange)==null?void 0:P.call(lt,(F,Q)=>{F!==ee||Q!=="connected"||mt()});return()=>{_==null||_()}},[ee,Z,r]),i.useEffect(()=>{t&&Le()},[t,ne,r]),i.useEffect(()=>{var F,Q;const _=N.current,T=(Q=(F=_==null?void 0:_.ownerDocument)==null?void 0:F.defaultView)==null?void 0:Q.ResizeObserver;if(!_||!T)return;const P=new T(ye=>{const ce=ye[0];if(!ce)return;const{width:Ne,height:De}=ce.contentRect;k($e=>{const Me=Math.round(Ne),Re=Math.round(De);return $e.width===Me&&$e.height===Re?$e:{width:Me,height:Re}})});return P.observe(_),()=>P.disconnect()},[]),i.useEffect(()=>{if(z.current)return;const _=te();!Number.isFinite(_)||_<=0||C(T=>$.current?_<T-we?_:T:($.current=!0,_))},[W.height,W.width,S.height,S.width]),i.useEffect(()=>{ve&&Pe()},[ve,ke,Ce]),i.useEffect(()=>{var P;const _=B.current;if(B.current=c,!c)return;_||g(!1),xe.current&&(xe.current=!1,Oe());const T=ae.current;T&&(ae.current=null,Ye(T.text,T.seq,T.cols,T.rows,{force:!!T.force})),ee&&Z&&((P=lt.getState)==null?void 0:P.call(lt,ee))==="connected"&&mt(),me.current&&be.current===null&&pe(),ue(()=>{var F;(F=r.current)==null||F.bumpResize()})},[ee,c,Z]),i.useEffect(()=>()=>{be.current!==null&&le(),Se(),ie()},[]),i.useEffect(()=>{const _=F=>{var ye;const Q=F.detail;Q!=null&&Q.sessionId&&Q.sessionId!==Z||m&&((ye=r.current)==null||ye.bumpResize())},T=J(),P=T===window?[window]:[window,T];for(const F of P)F.addEventListener("adhdev:fit-cli-terminal",_);return()=>{for(const F of P)F.removeEventListener("adhdev:fit-cli-terminal",_)}},[m,Z,r]);const ft=m&&b&&!R&&(M.atTop||!M.canScroll)||j||!!y;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:N,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[ft&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ge()},disabled:!Z||j,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:j?"Loading older...":"Load older terminal output"}),y&&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:y})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[U&&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:U}),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:()=>{Fe()},disabled:!m,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{z.current=!0,C(_=>{const T=Math.max(D,Number((_-.1).toFixed(2)));return T>D&&Pe(),T})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{z.current=!0,C(_=>{const T=Math.min(je,Number((_+.1).toFixed(2)));return T>D&&Pe(),T})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:A,className:ve?"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:Ce>0?`${Ce}px`:"100%",height:ke>0?`${ke}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:W.width>0?`${W.width}px`:"100%",height:W.height>0?`${W.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:I},children:s.jsx(Ji,{ref:r,readOnly:!m||!c,sizingMode:"measured",onViewportMetrics:L,onScrollMetrics:E,onInput:_=>{!m||(u==null||u(ee,Z,_))}})})})}),!m&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:f})]}),s.jsx(cc,{contextKey:e.tabKey,panelLabel:it(e),isSending:a,isBusy:!!q,statusMessage:X,onSend:async _=>q?!1:n(_),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const ap=5e3,op=12e3;function ip(e){return e==="disconnected"||e==="reconnecting"}function cp({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=ap,reconnectActionDelayMs:o=op}){const c=ip(e),[l,u]=i.useState(()=>!c||a<=0),[m,d]=i.useState(()=>!c||o<=0),h=i.useRef(!1);i.useEffect(()=>{if(!c){u(!1);return}if(h.current=!1,a<=0){h.current=!0,u(!0);return}u(!1);const g=setTimeout(()=>{h.current=!0,u(!0)},a);return()=>clearTimeout(g)},[a,c]),i.useEffect(()=>{if(!c){d(!1);return}if(o<=0){d(!0);return}d(!1);const g=setTimeout(()=>{d(!0)},o);return()=>clearTimeout(g)},[o,c]);const f=c?l:e==="offline"||e==="auth_failed",v=!!(n&&e!=="auth_failed"&&(!c||m)),j=i.useMemo(()=>!t||e!=="connected"?!1:a<=0||h.current,[a,t,e]),p=e==="auth_failed"?"red":e==="offline"?"orange":"accent",y={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)"},w="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",R={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[f&&s.jsx("div",{className:w,style:R,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:y[p],border:x[p],color:b[p]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),v&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>n==null?void 0:n(),disabled:e==="offline",children:"Reconnect now"})]})}),j&&s.jsx("div",{className:w,style:R,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 lp({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",u=()=>{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:u,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 za({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(Ia,{size:n}):s.jsx(Ht,{size:n})})}const Dt="New session",$c="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 dp(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 up(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 mp(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 ln({git:e,className:t="",compact:r=!1}){const n=dp(e),a=up(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 ${mp(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 fp({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 Uo({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=rn(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:u=>{u.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),o()},children:"Delete"})]})]})}function pp({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:u,onHideConversation:m,hiddenConversations:d=[],onShowConversation:h,onShowAllHidden:f,onResetPanelsToMain:v,inboxOpen:j,onInboxOpenChange:p,hiddenOpen:y,onHiddenOpenChange:x,onOpenNewSession:b,onOpenDashboardGuide:w,guideNudgeVisible:R=!1,actionShortcuts:g,notifications:I,notificationUnreadCount:C,onOpenNotification:S,onMarkNotificationRead:k,onMarkNotificationUnread:W,onDeleteNotification:L}){const{ides:M,p2pStates:E={}}=ls(),U=!!e&&Ze(e)&&!qe(e),K=!!e&&qe(e),N=l||(e?lc(e)?"terminal":"chat":null),[A,z]=i.useState(!1),$=i.useRef(null),B=i.useRef(null),G=M.filter(J=>J.type==="adhdev-daemon"),V=fp({wsStatus:t,isConnected:r,daemonCount:G.length,p2pStates:E}),me=V.subtitle,ae=V.tone==="connected"?"#22c55e":V.tone==="limited"?"#eab308":"#ef4444",xe=V.tone==="connected"?"0 0 4px #22c55e80":V.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",de=i.useMemo(()=>I.filter(J=>!J.readAt),[I]),be=i.useMemo(()=>I.filter(J=>!!J.readAt),[I]),he=i.useMemo(()=>de.slice(0,9),[de]),Y=C;i.useEffect(()=>{if(!j)return;const J=ue=>{var le;(le=$.current)!=null&&le.contains(ue.target)||p(!1)};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[j,p]),i.useEffect(()=>{if(!y)return;const J=ue=>{var le;(le=B.current)!=null&&le.contains(ue.target)||x(!1)};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[y,x]),i.useEffect(()=>{if(!y&&!j)return;const J=ue=>{if(!ue.altKey)return;const le=ue.code.match(/^Digit([1-9])$/);if(!le)return;const Se=Number(le[1])-1,ie=y?d[Se]:void 0,pe=j?he[Se]:void 0;if(!(!ie&&!pe)){if(ue.preventDefault(),ue.stopPropagation(),ie){h==null||h(ie),x(!1);return}pe&&(S(pe),p(!1))}};return window.addEventListener("keydown",J,!0),()=>window.removeEventListener("keydown",J,!0)},[d,y,j,he,x,p,S,h]);const oe=J=>{if(!J)return;const ue=n.find(le=>le.tabKey===J);ue&&(m==null||m(ue))};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(Ht,{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:ae,boxShadow:xe}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[s.jsx("span",{title:V.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:ae,boxShadow:xe}}),me&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",me]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${Dt}${g!=null&&g.openNewSession?` (${g.openNewSession})`:""}`,"aria-label":Dt,children:s.jsx(Vi,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[w&&s.jsxs("button",{type:"button",onClick:w,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),R&&s.jsx("span",{children:"Guide"})]}),e&&(U||K||!qe(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:ms(e)||it(e),children:it(e)}),s.jsx(ln,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(U||K)&&c&&s.jsxs(s.Fragment,{children:[U&&u&&N&&s.jsx(za,{mode:N,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:K?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(wt,{size:14})})]}),!qe(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(Ma,{size:14})}),!U&&!qe(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Nt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:$,children:[s.jsxs("div",{className:`dashboard-header-hidden${A?" is-drop-target":""}`,ref:B,onDragEnter:J=>{J.dataTransfer.types.includes("text/tab-key")&&(J.preventDefault(),z(!0))},onDragOver:J=>{J.dataTransfer.types.includes("text/tab-key")&&(J.preventDefault(),J.dataTransfer.dropEffect="move",z(!0))},onDragLeave:J=>{J.currentTarget.contains(J.relatedTarget)||z(!1)},onDrop:J=>{const ue=J.dataTransfer.getData("text/tab-key");J.preventDefault(),z(!1),oe(ue)},children:[s.jsxs("button",{type:"button",onClick:()=>x(!y),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(Ui,{size:16}),d.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),y&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(Uo,{value:g==null?void 0:g.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[v&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:v,children:"Reset panels"}),d.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),x(!1)},children:"Restore all"})]})]}),e&&m&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(Uo,{value:g==null?void 0:g.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:it(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(J=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(J),x(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:it(J)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(J)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(J)+1]}):null,ms(J)]})]},J.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!j),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(sn,{size:16}),Y>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:Y})]}),j&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[de.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),de.map(J=>s.jsx(zo,{notification:J,shortcutIndex:he.indexOf(J)>=0?he.indexOf(J)+1:void 0,onOpen:()=>S(J),onMarkRead:()=>k(J.id),onMarkUnread:()=>W(J.id),onDelete:()=>L(J.id)},J.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(J=>s.jsx(zo,{notification:J,onOpen:()=>S(J),onMarkRead:()=>k(J.id),onMarkUnread:()=>W(J.id),onDelete:()=>L(J.id)},J.id))]}),I.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function ht(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function hp(e,t){return String(e||"")!==String(t||"")}function xp(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(u=>String(u||"").toLowerCase()).join(`
39
+ `).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!rc(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
40
+ `).includes(a)))}function bp(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 Bc(e,t={}){return bp(xp(e,t),t.sortMode||"recent")}function Xr(e){return e?"Resume saved history":"Start fresh"}function Va(e){return e?"Resuming saved history…":"Starting fresh…"}function gp(){return"Start fresh"}function Kc(e,t=!1){return e==="cli"?Xr(t):e==="ide"?"Start IDE":"Start ACP session"}function Oc(e,t=!1){return e==="cli"?Va(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function yp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function vp(){return"Open saved history"}function wp(){return"Saved History"}function Ga(){return"Use saved history when you want continuity in the same provider conversation."}function kp(){return"No saved history found yet."}function jp(){return"Refresh saved history"}function Sp(){return"Refreshing saved history…"}function rs(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function ns(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 Ms(e){return e==="start-fresh"?"Start fresh":"Restart"}function Is(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function qa(e){return`Resume saved history with ${e}?`}function Ya(){return"Review or change the target workspace before resuming saved history."}function Np(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 Xa({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,missingWorkspaceResumePath:u,onSavedHistoryFiltersChange:m,onClose:d,onNewChat:h,onSwitchSession:f,onRefreshHistory:v,onResumeSavedSession:j}){var L;const p=t.find(M=>M.id===e.routeId),y=(p==null?void 0:p.chats)||[],x=(L=p==null?void 0:p.activeChat)==null?void 0:L.id,b=Ze(e)&&!qe(e),[w,R]=i.useState(()=>ht()),g=l||w,I=String(u||"").trim(),C=M=>{if(m){m(M);return}R(M)},S=i.useMemo(()=>a.map(M=>{const E=String(M.workspace||"").trim();return M.canResume||E||!I?M:{...M,workspace:I,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[I,a]),k=i.useMemo(()=>Bc(S,{textQuery:g.textQuery,workspaceQuery:g.workspaceQuery,modelQuery:g.modelQuery,resumableOnly:g.resumableOnly,sortMode:g.sortMode}),[S,g.modelQuery,g.resumableOnly,g.sortMode,g.textQuery,g.workspaceQuery]),W=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:d,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:b?wp():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:sp(e)}),b&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ga()})]}),s.jsx("button",{onClick:d,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(wt,{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:h,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),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:M=>C({...g,textQuery:M.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:g.workspaceQuery,onChange:M=>C({...g,workspaceQuery:M.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:g.modelQuery,onChange:M=>C({...g,modelQuery:M.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:g.sortMode,onChange:M=>C({...g,sortMode:M.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:g.resumableOnly,onChange:M=>C({...g,resumableOnly:M.target.checked})}),"Resume-ready only"]})]}),k.map(M=>{const E=e.providerSessionId===M.providerSessionId,U=E||!M.canResume||!!c,K=M.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{U||!j||j(M)},disabled:U,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${E?"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 ${E?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:M.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:M.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Np(M.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:M.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[M.workspace||"Workspace unknown",K?" · selected workspace":"",us(M.summaryMetadata)?` · ${us(M.summaryMetadata)}`:"",M.messageCount>0?` · ${M.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:E?"ACTIVE":M.canResume?K?"RESUME IN SELECTED WORKSPACE":c===M.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},M.id)})]}):y.map(M=>s.jsxs("div",{onClick:()=>{f(e.routeId,M.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===M.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${x===M.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:M.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[M.id.substring(0,12),"..."]}),x===M.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},M.id)),(b&&!o&&k.length===0||!b&&y.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(su,{size:32})}),s.jsx("div",{className:"text-[13px]",children:b?a.length>0?"No saved history matches these filters.":kp():"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:Sp()})})]}),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:v,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(or,{size:13})," ",b?jp():"Refresh History"]})})})]})]});return typeof document>"u"?W:Zs.createPortal(W,document.body)}const Vo={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 Wc({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=Vo[n.type]||Vo.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var o;(o=n.actions)!=null&&o.length||r&&r(n)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:o=>{o.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(wt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((o,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 Cp=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Tp(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Mp(e){return e.sessionId||e.instanceId||e.agentType}function Cn(e,t){return e||t}function Hc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=St(r,{fallbackId:r.id}));return t}function Fc(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 Ja(e,t={}){return Ip(e,Fc(e,t))}function Ip(e,t={}){var h,f,v,j,p,y;const r=[],n=t.machineName,a=t.connectionState,o=Tp(e),c=e.workspace||"",l=Xu(e.type,{agentName:e.cliName}),u=Ze(e)||qe(e)?l:ot(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var b,w;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||ot(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:((w=x.activeChat)==null?void 0:w.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,surfaceHidden:x.surfaceHidden,git:x.git}}):[],d=Cp(e);if(d){const x=e.sessionId||e.instanceId,b=l,w=(h=e.activeChat)==null?void 0:h.activeModal,R=w&&Array.isArray(w.buttons)&&w.buttons.length>0,g=bt((f=e.activeChat)==null?void 0:f.status,{activeModal:(v=e.activeChat)==null?void 0:v.activeModal})||bt((p=(j=e.agents)==null?void 0:j[0])==null?void 0:p.status)||"idle",I=e.activeChat||{title:"",messages:[]};let C=I.title&&String(I.title).trim()?String(I.title).trim():"";const S=(y=e.activeChat)==null?void 0:y.id,k=e.chats;if(S&&Array.isArray(k)&&k.length>0){const E=k.find(U=>U.id===S||U.id&&String(U.id)===String(S));E!=null&&E.title&&String(E.title).trim()&&(C=String(E.title).trim())}const W=(Ze(e)||qe(e),e.type),L=(Ze(e)||qe(e))&&Mo(C,b,W)?"":C,M=I.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:Ze(e)?e.mode||"terminal":"chat",agentName:b,agentType:W,status:g,title:L,messages:M,resume:e.resume,hostIdeType:!Ze(e)&&!qe(e)?e.type:void 0,workspaceName:o,workspacePath:c,git:e.git,displayPrimary:L||o||(Ze(e)?e.mode==="chat"?b:"Terminal":b),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:R?w.buttons:void 0,modalMessage:R?w.message:void 0,streamSource:"native",tabKey:Cn(x,e.id),machineName:n,connectionState:a})}if(d&&(Ze(e)||qe(e)))return r;for(const x of m){const b=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,w=Ju(x),R=Mp(x),g=`${e.id}:${R}`,I=x.title&&String(x.title).trim()||"",C=Mo(I,x.agentName,x.agentType)?"":I,S=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||S.length>0||b||C||!["idle","panel_hidden","disconnected","not_monitored"].includes(w))&&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:w,title:C,messages:S,hostIdeType:e.type,workspaceName:o,workspacePath:c,git:x.git||e.git,displayPrimary:C||o||x.agentName||u,displaySecondary:`${u} · ${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:Cn(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||u,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Cn(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function Ap(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 Uc(e,t){const r=Ap(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:"🏄"}],Vc=[{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:"🧩"}],Gc=[{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:"🟠"}],Lp=zc,Rp=Vc,_p=Gc;function fs(...e){return xd(bd(e))}function Pp({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:fs("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 qc({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(Pp,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:fs("mx-auto flex w-full flex-col gap-4",o,c),children:l})})]})}const xa="adhdev:themechange";function Dp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function gs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function ys(e){return e==="system"?Dp():e}function Yc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function _r(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(xa,{detail:{preference:e,theme:t}}))}function Ep(){const e=gs(),t=ys(e);Yc(t),_r(e,t)}function Qa(){const[e,t]=i.useState(gs),[r,n]=i.useState(()=>ys(gs()));i.useEffect(()=>{Yc(r)},[r]),i.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const m=u.matches?"light":"dark";n(m),_r("system",m)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),i.useEffect(()=>{const c=u=>{const m=u.detail||{},d=m.preference,h=m.theme;t(d==="dark"||d==="light"||d==="system"?d:gs()),n(h==="dark"||h==="light"?h:ys(gs()))},l=u=>{if(u.key!=="theme")return;const m=gs(),d=ys(m);t(m),n(d)};return window.addEventListener(xa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(xa,c),window.removeEventListener("storage",l)}},[]);const a=i.useCallback(c=>{const l=ys(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}_r(c,l)},[]),o=i.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=ys(l);n(u);try{localStorage.setItem("theme",l)}catch{}return _r(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const Go={dark:"Dark",light:"Light",system:"System"};function $p({collapsed:e}){const{preference:t,cycleTheme:r}=Qa(),n=t==="dark"?s.jsx(nu,{size:16}):t==="light"?s.jsx(ru,{size:16}):s.jsx(au,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Go[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Go[t]})]})}function Tn(e,t){return e?typeof e=="function"?e(t):e:null}function Bp({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:c,preMainContent:l,collapsedStorageKey:u="sidebar-collapsed"}){const[m,d]=i.useState(!1),[h,f]=i.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),v=()=>d(!0),j=()=>d(!1),p=()=>{f(w=>{const R=!w;try{localStorage.setItem(u,R?"1":"0")}catch{}return R})},y=i.useMemo(()=>({collapsed:h,mobileMenuOpen:m,openMobileMenu:v,closeMobileMenu:j,toggleCollapsed:p}),[h,m]),x=w=>`nav-item${w.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${w.className?` ${w.className}`:""}`,b=w=>s.jsxs("div",{className:x(w),id:`nav-${w.id}`,onClick:()=>{w.onSelect(),j()},title:h?w.title??(typeof w.label=="string"?w.label:void 0):w.title,children:[s.jsx("span",{className:"nav-icon",children:w.icon}),!h&&w.label]},w.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:v,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),m&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:j,onKeyDown:w=>w.key==="Escape"&&j()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:Tn(t,y)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:j,children:s.jsx(wt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),n.map(w=>s.jsxs("div",{className:w.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&w.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:w.title}):null,w.items.map(b)]},w.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),Tn(o,y),s.jsx($p,{collapsed:h}),Tn(c,y)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function jt({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:fs("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 Xc({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:fs("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 Kp={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"},Op={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function wr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:fs("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Kp[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Op[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 Wp={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"},Hp={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Fp({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:fs("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Wp[e],r),children:[s.jsx("span",{className:fs("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Hp[e])}),n]})}function Qt({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 Up({onPrefChange:e}){const[t,r]=im(),[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(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(sn,{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(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nt,{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:()=>{oc().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(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ou,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>o("completionAlert",c)}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(iu,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>o("approvalAlert",c)}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(sr,{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 Jr(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=Jr(e),n=Jr(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 Jc(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function Xs(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=Jr(r),a=Jr(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Vp(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Mn(e,t){return e instanceof Error?e.message:t}function Gp({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(Xc,{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(Yp,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function qo({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 Zs.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 qp(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Lp,...Rp,..._p].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 Yp({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var U,K;const[o,c]=i.useState("idle"),[l,u]=i.useState(""),[m,d]=i.useState(null),[h,f]=i.useState("idle"),[v,j]=i.useState(""),p=e.version||null,y=((U=e.machine)==null?void 0:U.platform)||((K=e.system)==null?void 0:K.platform)||"",x=St(e,{fallbackId:e.id}),b=y==="win32"?"🪟":y==="darwin"?"🍎":"🐧",w=t.filter(N=>N.daemonId===e.id&&N.transport==="cdp-page"),R=t.filter(N=>N.daemonId===e.id&&N.transport==="pty"),g=t.filter(N=>N.daemonId===e.id&&N.transport==="acp"),I=e.p2p,C=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const N=Vp(await r(e.id,"daemon_upgrade",{}));N.alreadyLatest?(c("done"),u(`Already on v${N.version||"latest"}.`)):N.upgraded||N.success?(c("done"),u(`Upgrade to v${N.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(N.error||"Upgrade failed"))}catch(N){c("error"),u(Mn(N,"Connection lost during upgrade"))}}},S=async()=>{if(d(null),!!n){f("loading");try{await n(e.id),f("done"),j("Machine disconnected.")}catch(N){f("error"),j(Mn(N,"Failed to disconnect"))}}},k=async()=>{if(d(null),!!a){f("loading");try{await a(e.id),f("done"),j("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(N){f("error"),j(Mn(N,"Failed to revoke token"))}}},W="0.9.56",L=Jc(e,W),M=Xs(e,W),E=w.length+R.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),"…"]}),p&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!L&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&L&&s.jsx("button",{onClick:C,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${W}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${M?"↑ Update now":`↑ Update${` to v${W}`}`}`}),n&&s.jsx("button",{onClick:()=>d("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>d("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Fp,{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:[I&&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 ${I.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${I.state==="connecting"||I.state==="new"?"animate-pulse":""}`,style:I.state==="connecting"||I.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",I.state==="connected"?"connected":I.state==="connecting"||I.state==="new"?"connecting...":I.state||"off"]}),I.peers!==void 0&&I.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",I.peers," peer",I.peers!==1?"s":"",")"]})]}),I&&E>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),E>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[w.map(N=>{const A=qp(N.type),z=N.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:A.icon}),s.jsx("span",{children:A.name}),z!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${z?"bg-green-400":"animate-pulse"}`,style:z?void 0:{background:"var(--status-warning)"},title:z?"CDP connected":"CDP connecting..."})]},N.id)}),R.map(N=>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:N.cliName||"CLI"})]},N.id)),g.map(N=>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:N.cliName||"ACP"})]},N.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||v)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||h==="error"?"text-red-400":o==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:v||l})]}),m==="disconnect"&&s.jsx(qo,{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
 
44
- Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:S,onCancel:()=>d(null)}),m==="revoke"&&s.jsx(Go,{title:"⚠️ Remove Machine",message:`Remove "${x}" from your dashboard?
44
+ Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:S,onCancel:()=>d(null)}),m==="revoke"&&s.jsx(qo,{title:"⚠️ Remove Machine",message:`Remove "${x}" from your dashboard?
45
45
 
46
46
  This will:
47
47
  • Immediately disconnect the machine
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:j,onCancel:()=>d(null)})]})}const Kp=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Op(){const{preference:e,setPreference:t}=Qa();return s.jsx("div",{className:"flex gap-2",children:Kp.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 Wp(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 Hp(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function In(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function qo(e){const{r:t,g:r,b:n}=Hp(e);return .2126*In(t)+.7152*In(r)+.0722*In(n)}function Yo(e,t){const r=qo(e),n=qo(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function Yc(e){const t=Wp(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Yo(t,r)>=Yo(t,n)?r:n}const ba={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},ga={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},Fp=[{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"}}}],Xc="adhdev-chat-theme",Jc="adhdev-chat-theme-custom";function _r(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Xc)||"ember"}catch{return"ember"}}function Rt(e){try{const t=localStorage.getItem(Jc);if(t){const r=JSON.parse(t);return{...e==="dark"?ba:ga,...r[e]}}}catch{}return e==="dark"?ba:ga}function jr(e,t){try{localStorage.setItem(Jc,JSON.stringify({dark:e,light:t}))}catch{}}function Ct(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 Jr(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 Up={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Js(e,t){var a;const r=(a=Up[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",Jr(r,24)),n.style.setProperty("--accent-on-primary",Yc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Jr(r,18)})`),n.style.setProperty("--border-accent",Ct(r,.35)),n.style.setProperty("--nav-active-bg",Ct(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Ct(r,.06)}`)}function as(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Ct(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Ct(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Ct(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",Ct(e.borderSubtle,.5)),t.style.setProperty("--border-default",Ct(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Jr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Yc(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Jr(e.accentColor,40)})`),t.style.setProperty("--border-accent",Ct(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Ct(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Ct(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 ${Ct(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 Za(){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 zp(e){try{localStorage.setItem(Xc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=os()?"dark":"light";as(Rt(t))}else Za(),Js(e,os()?"dark":"light")}function Vp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=_r();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=os()?"dark":"light";as(Rt(t))}else Za(),Js(e,os()?"dark":"light")}function os(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function xt({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 Os({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 Gp({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=i.useState(()=>Rt(r));i.useEffect(()=>{a(Rt(r))},[r]);const o=i.useCallback((c,l)=>{a(u=>{const m={...u,[c]:l},h=Rt(r==="dark"?"light":"dark");return r==="dark"?jr(m,h):jr(h,m),as(m),t(m),m})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",s.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(Os,{title:"App Background",children:[s.jsx(xt,{label:"Background",value:n.bgPrimary,onChange:c=>o("bgPrimary",c)}),s.jsx(xt,{label:"Surface",value:n.bgSecondary,onChange:c=>o("bgSecondary",c)}),s.jsx(xt,{label:"Card",value:n.surfacePrimary,onChange:c=>o("surfacePrimary",c)})]}),s.jsxs(Os,{title:"App Text",children:[s.jsx(xt,{label:"Primary",value:n.textPrimary,onChange:c=>o("textPrimary",c)}),s.jsx(xt,{label:"Secondary",value:n.textSecondary,onChange:c=>o("textSecondary",c)}),s.jsx(xt,{label:"Muted",value:n.textMuted,onChange:c=>o("textMuted",c)})]}),s.jsxs(Os,{title:"Borders & Accent",children:[s.jsx(xt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>o("borderSubtle",c)}),s.jsx(xt,{label:"Border default",value:n.borderDefault,onChange:c=>o("borderDefault",c)}),s.jsx(xt,{label:"Accent",value:n.accentColor,onChange:c=>o("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Os,{title:"Chat Bubbles",children:[s.jsx(xt,{label:"User bubble",value:n.userBubble,onChange:c=>o("userBubble",c)}),s.jsx(xt,{label:"User text",value:n.userText,onChange:c=>o("userText",c)}),s.jsx(xt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>o("assistantBubble",c)}),s.jsx(xt,{label:"Agent text",value:n.assistantText,onChange:c=>o("assistantText",c)})]}),s.jsxs(Os,{title:"Chat Layout",children:[s.jsx(xt,{label:"Chat BG",value:n.containerBg,onChange:c=>o("containerBg",c)}),s.jsx(xt,{label:"Send button",value:n.sendButton,onChange:c=>o("sendButton",c)}),s.jsx(xt,{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?ba:ga,u=Rt(e?"light":"dark");e?jr(c,u):jr(u,c),a(c),as(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 qp(){const[e,t]=i.useState(_r),[r,n]=i.useState(!0),[a,o]=i.useState(()=>Rt("dark"));i.useEffect(()=>{n(os());const u=new MutationObserver(()=>{const h=os();n(h);const f=_r();f==="custom"?as(Rt(h?"dark":"light")):Js(f,h?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const h=os();n(h);const f=_r();f==="custom"?as(Rt(h?"dark":"light")):Js(f,h?"dark":"light")};return m.addEventListener("change",d),()=>{u.disconnect(),m.removeEventListener("change",d)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?as(Rt(r?"dark":"light")):(Za(),Js(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o(Rt(r?"dark":"light"))},[r]);const c=u=>{t(u),zp(u)},l=[...Fp,{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(u=>{const m=e===u.id,d=r?u.preview.dark:u.preview.light,h=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:d.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.userBubble,color:h},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[m&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&s.jsx(Gp,{dark:r,onColorsChange:u=>o(u)})]})}const eo="adhdev_mobileDashboardMode_v1",ya="adhdev:mobile-dashboard-mode-change";function to(){try{return localStorage.getItem(eo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Yp(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??to())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==eo||t()};return window.addEventListener(ya,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ya,r),window.removeEventListener("storage",n)}}function Xp(e){try{localStorage.setItem(eo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ya,{detail:e}))}function Jp(){const[e,t]=i.useState(!0);return i.useEffect(()=>{t(to()==="chat")},[]),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ht,{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),Xp(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Mn=new Map,Xo=new Map;function Qp(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 Zp(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 Qc(){const{sendCommand:e}=vt(),{injectEntries:t,getIdes:r}=er();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??sf,c=Xo.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<o)return;const l=Mn.get(n);if(l)return l;const u=(async()=>{const m=await e(n,"get_machine_runtime_stats"),d=Qp(m);if(!d)return;const h=r().find(w=>w.id===n),f=Zp(h,n,d.machine,d.timestamp||Date.now());t([f]),Xo.set(n,Date.now())})().finally(()=>{Mn.delete(n)});return Mn.set(n,u),u},[r,t,e])}function eh(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 th(e,t){const{sendData:r}=vt(),{injectEntries:n,getIdes:a}=er(),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(u=>qt.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const h=a().find(w=>w.id===u),f=eh(h,u,d);n([f])}));return()=>{l.forEach(u=>u())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function sh(e,t){const{sendData:r}=vt(),[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 u=qt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},m=>{l&&(clearTimeout(l),l=null),a(m.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},of):c(!1),()=>{l&&clearTimeout(l),u()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:o,applyDiagnostics:a}}function rh(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Zc(e){const{sendData:t}=vt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=rh(e);if(!a||!e.sessionId||!t){n({});return}const o=qt.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),Ss.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 el="adhdev_hiddenTabs";function nh(){try{const e=localStorage.getItem(el);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function xs(e){try{localStorage.setItem(el,JSON.stringify([...e]))}catch{}}function An(e){return Wa(e)}function so(e,t){return ks(t).some(r=>e.has(r))}function ah(){const[e,t]=i.useState(nh),r=i.useCallback(m=>{const d=An(m);t(h=>{const f=new Set(h);return f.has(d)?f.delete(d):f.add(d),xs(f),f})},[]),n=i.useCallback(m=>{const d=An(m);t(h=>{if(h.has(d))return h;const f=new Set(h);return f.add(d),xs(f),f})},[]),a=i.useCallback(m=>{const d=An(m);t(h=>{if(!h.has(d))return h;const f=new Set(h);return f.delete(d),xs(f),f})},[]),o=i.useCallback(()=>{t(m=>{if(m.size===0)return m;const d=new Set;return xs(d),d})},[]),c=i.useCallback((m,d)=>{t(h=>{const f=new Set(h);for(const w of d)f.add(w);return xs(f),f})},[]),l=i.useCallback((m,d)=>{t(h=>{const f=new Set(h);for(const w of d)f.delete(w);return xs(f),f})},[]),u=i.useCallback(m=>so(e,m),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:o,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function tl(e){return e instanceof Error?e.message:String(e||"")}function sl(e){const t=tl(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 rl(e){const t=tl(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function nl({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Ze(e)||qe(e))return;const o=_s(e);if(o===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(hs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:$t(e),mode:t})}catch(l){const u=rl(l);c&&!u&&a(m=>{const d={...m};return o===al(r,c)?delete d[c]:d[c]=o,d}),sl(l)?console.warn(u?"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 Jo(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 oh(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=Jo(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>Jo(u,t)):a.childSessions,l=c!==a.childSessions;return o!==a||l?(r=!0,{...o,...l?{childSessions:c}:{}}):a});return r?n:e}function al(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 ih(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))al(t,a)===o&&(delete n[a],r=!0);return r?n:e}function ch({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{ac()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:Rc(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return cm(a),i.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),m={};for(const[d,h]of Object.entries(l))u-h<5e3&&(m[d]=h);return Object.keys(m).length===Object.keys(l).length?l:m})},5500);return()=>clearTimeout(c)},[t,r]),i.useEffect(()=>{const o=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(m=>m.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(o)},[n]),null}function lh(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 Ln(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 dh(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 Qo(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?dh(Bt(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 uh(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||""),Qo(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||""),Qo(r.activeChat)].join(":"))].join("|")}function mh(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 fh(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of ks({routeId:n.routeId}))r.set(o,a);for(const o of ks({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of ks({tabKey:n.tabKey}))r.set(o,n)}return r}function ph(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function hh(e){const t=ph(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=Bt(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function xh({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>lh(e),[e]),o=i.useMemo(()=>Kc(e),[e]),c=i.useRef([]),l=i.useRef([]),u=i.useRef([]),m=i.useRef(new Map),d=i.useRef(new Map),h=i.useMemo(()=>{const R=new Map,g=[];for(const j of a){const{connectionState:W="new",machineName:L}=Oc(j,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),I=uh(j),D=m.current.get(j.id);if(D&&D.ide===j&&D.sourceSignature===I&&D.connectionState===W&&D.machineName===L){R.set(j.id,D),g.push(...D.conversations);continue}const U=Ja(j,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),K={ide:j,sourceSignature:I,connectionState:W,machineName:L,conversations:U};R.set(j.id,K),g.push(...U)}m.current=R;const M=new Map,C=j=>{const W=hh(j),L=d.current.get(j.tabKey);if(L&&L.signature===W)return M.set(j.tabKey,L),L.timestamp;const I={signature:W,timestamp:yc(j)||(L==null?void 0:L.timestamp)||0};return M.set(j.tabKey,I),I.timestamp},S=[...g].sort((j,W)=>vc(j,W,C));return d.current=M,S},[a,t,o]),f=i.useMemo(()=>{const R=mh(h,r);return Ln(c.current,R)?c.current:(c.current=R,R)},[h,r]),w=i.useMemo(()=>{const R=new Map,g=Array.from(new Set(f.map(M=>M.routeId)));for(const M of g){const C=_t(f,M);C&&R.set(M,C)}return R},[f]),k=i.useMemo(()=>{const R=new Map;for(const g of f){const M=w.get(g.routeId),C=g.streamSource==="native"&&M?M:g;for(const S of ks({providerSessionId:g.providerSessionId,sessionId:g.sessionId}))R.set(S,C)}return R},[f,w]),p=i.useMemo(()=>fh(f,w),[f,w]),y=i.useCallback(R=>{if(R)return k.get(R)},[k]),x=i.useCallback(R=>{if(R)return p.get(R)},[p]),b=i.useMemo(()=>{const R=f.filter(g=>!so(n,g));return Ln(l.current,R)?l.current:(l.current=R,R)},[f,n]),v=i.useMemo(()=>{const R=b.map(g=>g.tabKey);return Ln(u.current,R)?u.current:(u.current=R,R)},[b]);return{chatIdes:a,conversations:f,visibleConversations:b,visibleTabKeys:v,resolveConversationBySessionId:y,resolveConversationByTarget:x}}function bh({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 u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:c}}function gh({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){i.useEffect(()=>{et.setIdes(e)},[e]),i.useEffect(()=>{et.setResolveAction((a,o,c)=>{t(a,o,c).catch(()=>{})})},[t]),i.useEffect(()=>{const a=et.onToast(o=>{r(l=>l.some(m=>m.message===o.message&&o.timestamp-m.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(u=>u.id!==o.id)),c)});return()=>{a()}},[r]),i.useEffect(()=>{const a=Mc.on("status_event",o=>{et.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=c=>{var p;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 u=l.targetSessionId||l.targetKey||l.daemonId,m=n(u),d=(m==null?void 0:m.routeId)||l.daemonId;if(!d)return;const h=Number(l.buttonIndex),f=l.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[h])||"Approve",w=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(w);t(d,"resolve_action",{action:k?"approve":"reject",button:f,...Number.isFinite(h)&&{buttonIndex:h},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};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 yh="adhdev_dashboardLayout_v1",vh="adhdev_dashboardDockview_v1",wh="adhdev_dashboardDockviewHiddenRestore_v1",Ws={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function ro(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function jh(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function ol(e){return`${yh}:${e}`}function kh(e){const t=ol(e);return ro(t,null)}function Sh(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=ol(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function il(e){return`${vh}:${e}`}function Nh(e){const t=il(e);return ro(t,null)}function Ch(e,t){try{const r=il(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function cl(e){return`${wh}:${e}`}function Th(e){const t=cl(e);return ro(t,{})}function Ih(e,t){try{const r=cl(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Mh(){return{groupAssignments:[...Ws.groupAssignments],focusedGroup:Ws.focusedGroup,groupActiveTabIds:{...Ws.groupActiveTabIds},groupTabOrders:{...Ws.groupTabOrders},groupSizes:[...Ws.groupSizes]}}function Ah(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Lh(){const[e]=i.useState(()=>jh(typeof window<"u"?window.innerWidth:1280)),[t,r]=i.useState(()=>new Map),[n,a]=i.useState(0),[o,c]=i.useState({}),[l,u]=i.useState({}),[m,d]=i.useState([]),[h,f]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[w,k]=i.useState(!1),p=i.useCallback(()=>{if(w)return;const j=kh(e)??Mh();r(new Map(j.groupAssignments)),a(j.focusedGroup),c(j.groupActiveTabIds),u(j.groupTabOrders),d(j.groupSizes),k(!0)},[w,e]);i.useEffect(()=>{w&&Sh(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:l,groupSizes:m})},[w,e,t,n,o,l,m]),i.useEffect(()=>{const j=window.matchMedia("(max-width: 767px)"),W=L=>f(L.matches);return j.addEventListener("change",W),()=>j.removeEventListener("change",W)},[]);const y=i.useCallback(j=>{r(j)},[]),x=i.useCallback(j=>{a(j)},[]),b=i.useCallback(j=>{c(j)},[]),v=i.useCallback(j=>{u(j)},[]),R=i.useCallback(j=>{d(j)},[]),g=i.useCallback(j=>{x(j)},[x]),M=i.useCallback((j,W)=>{c(L=>(L[j]??null)===(W??null)?L:{...L,[j]:W})},[]),C=i.useCallback((j,W)=>{u(L=>{const I=L[j];return Ah(I,W)?L:{...L,[j]:W}})},[]),S=i.useCallback((j,W)=>{const L=W.get(j)??0;return M(L,j),g(L),L},[g,M]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:y,focusedGroup:n,updateFocusedGroup:x,focusGroup:g,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:M,groupTabOrders:l,updateGroupTabOrders:v,setGroupTabOrder:C,groupSizes:m,updateGroupSizes:R,isMobile:h,hasHydratedStoredLayout:w,hydrateStoredLayout:p,focusConversationTab:S}}function Rh(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Oa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function _h({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:c,setSearchParams:l,historyModalOpen:u,activeConv:m,isRefreshingHistory:d,ides:h,handleRefreshHistory:f}){const w=i.useRef(!1),k=i.useRef(!1),p=i.useRef(null),y=i.useRef(!1);i.useEffect(()=>{if(!e||w.current||t.length===0)return;if(!a){o();return}const x=r(e);x&&(c(x.tabKey,n),w.current=!0,k.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.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(!(k.current||a)&&t.length!==0){if(!e){o(),k.current=!0;return}if(w.current){k.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(k.current||a)&&(o(),k.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,o]),i.useEffect(()=>{if(!u){y.current=!1;return}if(!m||y.current||d)return;const x=h.find(b=>b.id===m.routeId);x&&(!x.chats||x.chats.length===0||Rh(x.chats,m))&&(y.current=!0,f())},[u,m,d,h,f])}function Rn(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=Oa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function ll({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[c,l]=i.useState(!1),[u,m]=i.useState(!1),d=i.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=i.useCallback(async(k,p)=>{try{const y=k||(t==null?void 0:t.daemonId)||"",x=await e(y,"switch_chat",{id:p,sessionId:p,...es(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"?Bs(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Bs(a,`⚠️ Switch error: ${b}`):Bs(a,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),Bs(a,`❌ Switch failed: ${y.message||"connection error"}`)}},[t,e,a]),f=i.useCallback(async()=>{if(!(!t||c)){l(!0);try{const k=Ts(t);await e(k,"new_chat",{...es(t)}),o(p=>({...p,[t.tabKey]:Date.now()}))}catch(k){console.error("New chat failed",k)}finally{l(!1)}}},[t,c,e,o]),w=i.useCallback(async()=>{var k,p;if(!(!t||u)){m(!0);try{const y=Ts(t),x=async()=>e(y,"list_chats",{forceExpand:!0,...es(t)});let b=await x(),v=(b==null?void 0:b.chats)||((k=b==null?void 0:b.result)==null?void 0:k.chats);Rn(v,t)&&(await new Promise(R=>setTimeout(R,450)),b=await x(),v=(b==null?void 0:b.chats)||((p=b==null?void 0:b.result)==null?void 0:p.chats)),b!=null&&b.success&&Array.isArray(v)&&(n(t.routeId,v),Rn(v,t)&&!Rn(r,t)&&Bs(a,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{m(!1)}}},[t,r,u,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:h,handleNewChat:f,handleRefreshHistory:w}}function Ph(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 Dh(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Zo(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 kr(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 u=a[l];typeof u=="number"&&u>0&&o.set(c,u)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function ei(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 Eh(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 $h(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 ti(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 si(e){return Array(e).fill(100/e)}function Bh({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:m}){const d=i.useRef(null),h=i.useMemo(()=>kr(e,m),[e,m]),f=h.assignments,w=i.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),k=w>1,p=i.useCallback((g,M)=>{t(C=>{const S=new Map(kr(C,m).assignments);return M===0?S.delete(g):S.set(g,M),S}),n(C=>({...C,[M]:g})),r(M)},[t,m,n,r]),y=i.useCallback(g=>{t(M=>{const C=kr(M,m).assignments,S=new Map;for(const[j,W]of C)W!==g&&(W>g?S.set(j,W-1):S.set(j,W));return S}),c(M=>{if(M.length<=1)return[];const C=[...M];C.splice(g,1);const S=C.reduce((j,W)=>j+W,0);return S>0?C.map(j=>j/S*100):[]}),r(0)},[t,m,c,r]),x=i.useCallback((g,M)=>{M.preventDefault();const C=d.current;if(!C)return;const S=M.clientX,j=C.offsetWidth,W=o.length===w?[...o]:si(w),L=D=>{const K=(D.clientX-S)/j*100,N=[...W];N[g]=Math.max(15,W[g]+K),N[g+1]=Math.max(15,W[g+1]-K),c(N)},I=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",I),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",I)},[o,w,c]),b=i.useCallback((g,M,C)=>{if(w>=4)return;const S=C==="left"?M:M+1;t(j=>{const W=kr(j,m).assignments,L=new Map;for(const I of u){const D=W.get(I.tabKey)??0,U=D>=S?D+1:D;U>0&&L.set(I.tabKey,U)}return S>0&&L.set(g,S),L}),c(j=>{const W=j.length===w?[...j]:si(w),L=W[M]??100/w,I=Math.max(15,L/2),D=Math.max(15,L/2),U=[...W];U[M]=I,U.splice(S,0,D);const K=U.reduce((N,A)=>N+A,0);return U.map(N=>N/K*100)}),n(j=>{const W=ti(j,S);return W[S]=g,W}),a(j=>{const W=ti(j,S);return W[S]=[g],W}),r(S)},[w,t,m,u,c,n,a,r]);i.useEffect(()=>{Ph(e,f)||t(f)},[e,f,t]),i.useEffect(()=>{const{mapping:g,usedGroups:M}=h;n(C=>{const S=ei(C,g);return Zo(C,S)?C:S}),a(C=>{const S=ei(C,g);return Zo(C,S)?C:S}),r(C=>{const S=l?0:Eh(C,M,g);return C===S?C:S}),c(C=>{const S=l?[]:$h(C,M,h.groupCount);return Dh(C,S)?C:S})},[h,l,n,a,r,c]);const v=i.useMemo(()=>{const g=Array.from({length:w},()=>[]);for(const M of u){const C=f.get(M.tabKey)??0,S=Math.min(C,w-1);g[S].push(M)}return g},[u,f,w]),R=i.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:d,normalizedGroupAssignments:f,numGroups:w,isSplitMode:k,groupedConvs:v,moveTabToGroup:p,closeGroup:y,handleResizeStart:x,splitTabRelative:b,clearAllSplits:R}}function Kh({ides:e,sendDaemonCommand:t}){const r="0.9.54",n=i.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:qc(d,r)).sort((d,h)=>Number(Xs(h,r))-Number(Xs(d,r))),[r,e]),a=i.useMemo(()=>n.some(d=>Xs(d,r)),[r,n]),[o,c]=i.useState(!1),[l,u]=i.useState({}),m=i.useCallback(async d=>{var h,f;u(w=>({...w,[d]:"upgrading"}));try{const w=await t(d,"daemon_upgrade",{});(h=w==null?void 0:w.result)!=null&&h.upgraded||(f=w==null?void 0:w.result)!=null&&f.success?u(k=>({...k,[d]:"done"})):u(k=>({...k,[d]:"error"}))}catch{u(w=>({...w,[d]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:o,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:m}}const dl=80;function Pr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function Oh(e){return{...e,createdAt:Pr(e.createdAt),updatedAt:Pr(e.updatedAt,e.createdAt),lastEventAt:Pr(e.lastEventAt,e.updatedAt||e.createdAt)}}function Wh(e){const t=Wa(e);return t==="unknown:"?e.id:t}function Hh(e){return[e.type,gc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Fh(e,t=dl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Wh(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 Uh(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=rn(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const u=Pr(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=Hh({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(Oh({id:m,dedupKey:m,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:dc(a),preview:_m(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return Fh(n)}function zh(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Vh(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=dl}=e,a=i.useMemo(()=>Uh(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=i.useMemo(()=>zh(a),[a]);return{notifications:a,unreadCount:o}}function Gh({notifications:e,sendDaemonCommand:t}){const r=i.useCallback(o=>{const c=e.find(u=>u.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 ln(...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 qh(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 dn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=qh(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 Yh(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 Xh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function un(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=Xh(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=(m,d)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${d}`:m==="/"||m==="\\"?`${c}${d}`:`${m.replace(/[\\/]+$/,"")}${c}${d}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:typeof(m==null?void 0:m.path)=="string"&&m.path.trim()?m.path:l(o,m.name)})).sort((m,d)=>m.name.localeCompare(d.name)):[];return{path:o,directories:u}}function Jh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ri(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Qh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Zh({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=ri(n.workspacePath),l=e.find(m=>{var k,p,y,x;if(!m||m.type==="adhdev-daemon"||Jh(m.daemonId||m.id)!==n.machineId||(rr(m)?"cli":ws(m)?"acp":"ide")!==n.kind||String(m.agentType||m.type||"")!==n.providerType)return!1;if(n.resumeSessionId)return String(m.providerSessionId||"")===n.resumeSessionId;if(c){const b=ri(m.workspace||m.runtimeWorkspaceLabel);return b?b===c:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((x=(y=(p=(k=m.activeChat)==null?void 0:k.messages)==null?void 0:p.at)==null?void 0:y.call(p,-1))==null?void 0:x.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const u=wc({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});u&&(a(null),r(u))},[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 ex({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const c=i.useCallback(async(f,w)=>un(e,f,w),[e]),l=i.useCallback(async(f,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const k=await e(f,"workspace_add",{path:w.trim()});return k!=null&&k.success?{ok:!0}:{ok:!1,error:(k==null?void 0:k.error)||"Could not save workspace"}}catch(k){return{ok:!1,error:k instanceof Error?k.message:"Could not save workspace"}}},[e]),u=i.useCallback(async(f,w,k)=>{var p;try{const y={ideType:w,enableCdp:!0};(p=k==null?void 0:k.workspacePath)!=null&&p.trim()&&(y.workspace=k.workspacePath.trim());const x=await e(f,"launch_ide",y);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:f,kind:"ide",providerType:w,workspacePath:(k==null?void 0:k.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(y){return{ok:!1,error:y instanceof Error?y.message:"Could not launch IDE"}}},[e,t]),m=i.useCallback(async(f,w,k,p)=>{var x,b,v;const y=Date.now();try{const R={cliType:k};(x=p==null?void 0:p.workspacePath)!=null&&x.trim()?R.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(R.workspaceId=p.workspaceId),(b=p==null?void 0:p.resumeSessionId)!=null&&b.trim()&&(R.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(R.cliArgs=p.cliArgs),(v=p==null?void 0:p.initialModel)!=null&&v.trim()&&(R.initialModel=p.initialModel.trim());const g=await e(f,"launch_cli",R),M=(g==null?void 0:g.result)||g,C=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);return g!=null&&g.success&&C?(r(C),{ok:!0}):g!=null&&g.success?(t({machineId:f,kind:w,providerType:k,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:y}),{ok:!0}):{ok:!1,error:(g==null?void 0:g.error)||(M==null?void 0:M.error)||`Could not launch ${w.toUpperCase()} session`}}catch(R){return Qh(R)?(t({machineId:f,kind:w,providerType:k,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:y}),{ok:!0}):{ok:!1,error:R instanceof Error?R.message:`Could not launch ${w.toUpperCase()} session`}}},[r,e,t]),d=i.useCallback(async(f,w)=>{if(!f||!w)return[];try{const k=await e(f,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),p=(k==null?void 0:k.result)??k;return Array.isArray(p==null?void 0:p.sessions)?p.sessions:[]}catch(k){return console.error("List saved sessions failed",k),[]}},[e]),h=i.useCallback(async f=>{await nl({conversation:n,mode:f,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineSavedSessions:d,setActiveCliViewMode:h}}function tx(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 sx(e,t,r=Date.now()){return!e||!tx(t)?null:{tabKey:e,nonce:r}}function rx({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:c}){const[l,u]=i.useState(null),[m,d]=i.useState(null),h=i.useMemo(()=>{var y,x;if(!e){if(l){const b=t.find(v=>v.tabKey===l);if(b)return b}return r[0]}const p=n[a];if(p){const b=t.find(v=>v.tabKey===p);if(b)return b}return((y=o[a])==null?void 0:y[0])||((x=o[0])==null?void 0:x[0])},[t,l,a,n,o,e,r]),f=i.useCallback(p=>{u(p)},[]),w=i.useCallback(p=>{u(p.tabKey),c(y=>{const x=new URLSearchParams(y),b=Dm(p);return b?x.set("activeTab",b):x.delete("activeTab"),x},{replace:!0})},[c]),k=i.useCallback((p,y)=>{const x=sx(p,y);x&&d(x)},[]);return{activeConv:h,openDesktopConversation:w,requestScrollToBottom:k,scrollToBottomRequest:m,setDesktopActiveTab:f}}function nx(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 ax(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 ox({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),u=i.useRef(null);i.useEffect(()=>{const m=()=>{c.current&&(clearTimeout(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null),o.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const d=Fr(e,r),h=ax({tabKey:e.tabKey,historySessionId:cr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:ts(e),liveState:d}),f=h.autoReadKey,w=nx({autoReadKey:f,shouldMarkSeen:h.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!h.shouldMarkSeen){w.shouldCancelPending&&m(),a.current=f;return}if(!w.shouldSchedule)return;w.shouldCancelPending&&m();const k=()=>{if(document.visibilityState!=="visible"||a.current===f)return;a.current=f,o.current=null,c.current=null,l.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null);const y=h.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:y,completionMarker:h.completionMarker}).catch(()=>{})};if(o.current=w.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(k,1500);const y=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};u.current=y,document.addEventListener("visibilitychange",y);return}const p=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(k,800),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null))};u.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),i.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function ni(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 ix({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:c,setClearedTabs:l,setSearchParams:u}){var N;const[m,d]=i.useState(!1),[h,f]=i.useState([]),[w,k]=i.useState(()=>ht()),[p,y]=i.useState(!1),[x,b]=i.useState(null),v=i.useRef(null),R=i.useMemo(()=>r||t||e,[e,r,t]),g=!!R&&Ze(R)&&!qe(R),M=i.useMemo(()=>{if(!R||!g)return null;const A=R.daemonId||R.routeId||"",z=$t(R),$=ni(R);return`${A}:${z}:${R.providerSessionId||""}:${$}`},[R,g]),{isCreatingChat:C,isRefreshingHistory:S,handleSwitchSession:j,handleNewChat:W,handleRefreshHistory:L}=ll({sendDaemonCommand:a,activeConv:R,chats:(N=n.find(A=>A.id===(R==null?void 0:R.routeId)))==null?void 0:N.chats,updateRouteChats:o,setToasts:c,setClearedTabs:l}),I=i.useCallback(()=>{d(!0)},[]),D=i.useCallback(()=>{d(!1)},[]),U=i.useCallback(async()=>{if(!(!R||!g||p)){y(!0);try{const A=R.daemonId||R.routeId,z=$t(R),$=ni(R),B=await a(A,"list_saved_sessions",{agentType:z,providerType:z,kind:"cli",limit:50,...R.providerSessionId?{providerSessionId:R.providerSessionId}:{},...$?{workspace:$}:{}}),V=(B==null?void 0:B.result)??B;f(Array.isArray(V==null?void 0:V.sessions)?V.sessions:[])}catch(A){console.error("Refresh saved sessions failed",A),f([])}finally{y(!1)}}},[R,p,g,a]);i.useEffect(()=>{if(!m){v.current=null;return}if(!g){v.current=null,f([]),y(!1);return}!M||p||v.current!==M&&(v.current=M,U())},[U,m,p,g,M]);const K=i.useCallback(async A=>{if(!R||!g||!A.providerSessionId||!A.workspace)return;const z=R.daemonId||R.routeId,$=$t(R);try{b(A.providerSessionId);const B=await a(z,"launch_cli",{cliType:$,dir:A.workspace,resumeSessionId:A.providerSessionId,initialModel:rc(A.summaryMetadata,"model",{preferShortValue:!0})||void 0}),V=(B==null?void 0:B.result)??B,G=typeof(V==null?void 0:V.sessionId)=="string"?V.sessionId:typeof(V==null?void 0:V.id)=="string"?V.id:"";G&&u(me=>{const ne=new URLSearchParams(me);return ne.set("activeTab",G),ne},{replace:!0}),D()}catch(B){console.error("Resume saved session failed",B)}finally{b(null)}},[D,R,g,a,u]);return{historyModalOpen:m,openHistoryModal:I,closeHistoryModal:D,historyTargetConv:R,isSavedSessionHistoryTarget:g,isHistoryCreatingChat:C,isHistoryRefreshingHistory:S,handleHistorySwitchSession:j,handleHistoryNewChat:W,handleHistoryRefresh:L,savedHistorySessions:h,savedHistoryFilters:w,setSavedHistoryFilters:k,isSavedHistoryLoading:p,resumingSavedHistorySessionId:x,handleRefreshSavedHistory:U,handleResumeSavedHistorySession:K}}function cx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}){const[u,m]=i.useState(null),[d,h]=i.useState(null),f=i.useMemo(()=>{if(e||!n)return null;const x=l(n);return x&&!Ze(x)&&!qe(x)?x:null},[e,n,l]),w=i.useMemo(()=>{const x=u==null?void 0:u.routeId;if(!x)return null;const b=u!=null&&u.tabKey?o.find(v=>v.tabKey===u.tabKey):a?o.find(v=>v.tabKey===a):null;return(b==null?void 0:b.routeId)===x?b:_t(o,x)},[o,u,a]),k=i.useMemo(()=>{if(w)return c.find(x=>x.id===w.routeId)},[c,w]);i.useEffect(()=>{f&&(m({routeId:f.routeId,tabKey:Lo(f)}),h(f),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,f]);const p=i.useCallback(x=>{x&&(m({routeId:x.routeId,tabKey:Lo(x)}),h(x))},[]),y=i.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:k,remoteDialogActiveConv:d,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:y}}function lx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l,activeConv:u,sendDaemonCommand:m}){const{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:w,openRemoteDialog:k,closeRemoteDialog:p}=cx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}),[y,x]=i.useState(!1),[b,v]=i.useState(null),R=i.useCallback(async C=>{const S=C||u;!S||!Ze(S)&&!qe(S)||(v(S),x(!0))},[u]),g=i.useCallback(()=>{x(!1),v(null)},[]),M=i.useCallback(async C=>{const S=b||u;if(!S||!Ze(S)&&!qe(S)){g();return}x(!1);try{const j=$t(S),W=S.routeId||S.daemonId||"";await m(W,"stop_cli",{cliType:j,targetSessionId:S.sessionId,mode:C})}catch(j){console.error("Stop CLI failed:",j)}finally{v(null)}},[u,g,b,m]);return{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:w,openRemoteDialog:k,closeRemoteDialog:p,cliStopDialogOpen:y,cliStopTargetConv:b,requestCliStop:R,cancelCliStop:g,confirmCliStop:M}}function _n(e,t=!0){return(e??!0)&&t}const no=i.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d=null,handleFocusAgent:h,isFocusingAgent:f,actionLogs:w,userName:k,scrollToBottomRequestNonce:p,isInputActive:y=!0,isVisible:x=!0}){const b=n,v=!n,R=_n(x,b),g=_n(x,v),M=_n(x),C=Zc(t),S=C.status||C.modalMessage||C.modalButtons?{...t,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Zi,{activeConv:S,onModalButton:c}),S.transport!=="pty"&&S.transport!=="acp"&&S.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(tr,{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,S.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(Gf,{activeConv:S,clearToken:r,terminalRef:o,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,isVisible:R,isInputActive:y&&R})}),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(ha,{activeConv:S,ideEntry:a,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:f,actionLogs:w,userName:k,scrollToBottomRequestNonce:p,isInputActive:y&&g,isVisible:g})})]}):s.jsx(ha,{activeConv:S,ideEntry:a,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:f,actionLogs:w,userName:k,scrollToBottomRequestNonce:p,isInputActive:y&&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 dx({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:m,onOpenNativeConversation:d,onOpenMachine:h,onOpenHistory:f,onOpenRemote:w,onHideConversation:k,onStopCli:p,cliViewMode:y,onSetCliViewMode:x,handleSendChat:b,handleFocusAgent:v,handleModalButton:R,handleRelaunch:g}){const M=i.useRef(null),C=Ze(e)&&!t,S=C&&y==="terminal",j=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 ${j} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(Ta,{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(jc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>h(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[C&&y&&s.jsx(za,{mode:y,onChange:x,compact:!0}),C&&p&&s.jsx("button",{onClick:()=>{p(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(wt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Ia,{size:14})}),!t&&!C&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:s.jsx(Nt,{size:14})}),k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Close chat",children:s.jsx(wt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(no,{activeConv:e,clearToken:0,isCliTerminal:S,ideEntry:n,terminalRef:M,handleModalButton:R,handleRelaunch:g,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:v,isFocusingAgent:u,actionLogs:a,userName:o})})]})}const Pn={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 ux(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function ul(){const[e,t]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),c=e==="unix"?"unix":r;i.useEffect(()=>{t(ux())},[]);const l=i.useCallback(()=>{navigator.clipboard.writeText(Pn[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:Pn[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Pn[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 ml({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Nt},{key:"chats",label:"Chats",icon:Ht}];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 Sr({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 bs({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 Hs({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 Nr({item:e,type:t,getAvatarText:r,onOpenConversation:n,onCollectChatDebugBundle:a}){const o=t==="needs_attention"||t==="task_complete",c=t==="working",l=t==="earlier",u=t==="task_complete",{isReconnecting:m,isConnecting:d}=Rs(e.conversation),h=it(e.conversation),f=ms(e.conversation),w=Lc(e.conversation,{requiresAction:t==="needs_attention"}),k=o?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":l?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",p=o?"bg-accent-primary shadow-glow":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":l?"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",y=l?"text-text-secondary":"text-text-primary",x=l?"text-text-muted":"text-text-secondary",b=l?"text-text-secondary opacity-80":"text-text-muted",v=l?"text-text-muted opacity-80":"text-text-muted",R=!c&&!u,g="text-[color:var(--status-warning)]",M=C=>{if(!a)return;C.preventDefault(),C.stopPropagation();const S=a==null?void 0:a(e.conversation);Promise.resolve(S).catch(j=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",j)})};return s.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${k}`,onClick:()=>n(e.conversation),onContextMenu:M,type:"button",children:[o||c?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 ${p}`,style:o?{color:"var(--accent-on-primary)"}:void 0,children:r(h)}),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 ${y}`,children:h}),R&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${v}`,children:Qi(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${x}`,children:[s.jsx("span",{className:"truncate",children:f}),s.jsx(cn,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),m?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${g} animate-pulse`,children:"Reconnecting…"})]}):d?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):w==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:g,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${b}`,children:e.preview})]}),o&&!u&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),u&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),c&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]},e.conversation.tabKey)}function ai({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 mx({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:c,getAvatarText:l,actionLogs:u,sendDaemonCommand:m,onOpenConversation:d,onShowConversation:h,onShowAllHidden:f,onOpenNewSession:w,onOpenMachine:k,onOpenSettings:p,onSectionChange:y,wsStatus:x="connected",isStandalone:b=!1,onCollectChatDebugBundle:v}){const R=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,C=e==="machines"?"Machines":"Chats",S=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",j=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",W=i.useCallback(async D=>{const U=Ts(D);if(!U)return;const K=Array.isArray(D.messages)?D.messages:[],N=hc({activeConv:D,visibleMessages:K,actionLogs:u,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:K.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),A=await m(U,"get_chat_debug_bundle",{...es(D),delivery:"daemon_file",frontendSnapshot:N}),z=Vr(A),$=bc(z);let B=!0;try{await navigator.clipboard.writeText($)}catch(V){B=!1,console.warn("[chat-debug-bundle] failed to copy mobile inbox debug bundle locator",V)}et.showToast(xc(z,{locatorCopied:B}),B?"success":"warning")},[u,m]),L=v||W,I=i.useCallback((D,U)=>{D.preventDefault(),D.stopPropagation(),Promise.resolve(L(U)).catch(K=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",K),et.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[L]);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 ${S}`,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:C}),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(tn,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:p,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(en,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${j}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:R?s.jsx(Hs,{icon:s.jsx(ai,{}),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(Hs,{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(ul,{})})}):s.jsx(bs,{children:c.map((D,U)=>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] ${U>0?"border-t border-border-subtle/70":""}`,onClick:()=>k(D.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(D.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:D.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:D.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[D.unread," new"]}):D.total>0?`${D.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:D.subtitle}),D.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[D.total," chat",D.total!==1?"s":"",D.unread>0?` · ${D.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},D.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Sr,{title:"Needs attention",className:"mb-0"}),s.jsx(bs,{children:t.map((D,U)=>s.jsx("div",{className:U>0?"border-t border-border-subtle/70":"",children:s.jsx(Nr,{item:D,type:"needs_attention",getAvatarText:l,onOpenConversation:d,onCollectChatDebugBundle:L})},D.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Sr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(bs,{children:r.map((D,U)=>s.jsx("div",{className:U>0?"border-t border-border-subtle/70":"",children:s.jsx(Nr,{item:D,type:"task_complete",getAvatarText:l,onOpenConversation:d,onCollectChatDebugBundle:L})},D.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Sr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(bs,{children:n.map((D,U)=>s.jsx("div",{className:U>0?"border-t border-border-subtle/70":"",children:s.jsx(Nr,{item:D,type:"working",getAvatarText:l,onOpenConversation:d,onCollectChatDebugBundle:L})},D.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(Sr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(bs,{children:a.map((D,U)=>s.jsx("div",{className:U>0?"border-t border-border-subtle/70":"",children:s.jsx(Nr,{item:D,type:"earlier",getAvatarText:l,onOpenConversation:d,onCollectChatDebugBundle:L})},D.conversation.tabKey))}):M?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):R?s.jsx(Hs,{icon:s.jsx(ai,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):g?s.jsx(Hs,{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(Ht,{size:20})}),title:"No conversations yet",subtitle:Pc,children:w&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:w,"aria-label":Dt,title:Dt,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:Dt})]})}):s.jsx(Hs,{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.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[s.jsx("span",{children:"Hidden"}),s.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:f,children:"Restore all"})]}),s.jsx(bs,{className:"bg-bg-secondary/25",children:o.map((D,U)=>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] opacity-50 saturate-0 ${U>0?"border-t border-border-subtle/70":""}`,onClick:()=>h(D),onContextMenu:K=>I(K,D),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-bg-primary border border-border-subtle text-text-secondary",children:l(it(D))}),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:it(D)}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:ms(D)}),s.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},D.tabKey))})]})]}),e==="chats"&&w&&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:w,"aria-label":Dt,title:Dt,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(ml,{section:e,onSectionChange:y})]})}function fx(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 fl(e){const t=[e.workspace||"Workspace unknown"],r=us(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=fx(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function mn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:m}){const[d,h]=i.useState(r);i.useEffect(()=>{h(r)},[r]);const f=Yh(r),w=d.trim();return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:s.jsx(wt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!f||a||u(f)},disabled:!f||a,children:[s.jsx(Ta,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:k=>h(k.target.value),onKeyDown:k=>{k.key!=="Enter"||!w||a||(k.preventDefault(),u(w))},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:()=>{!w||a||u(w)},disabled:!w||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(k=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(k.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Ns,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:k.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:k.path})]})]},k.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(w||r),disabled:!w&&!r||a,children:c})]})]})})}function ao({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:m,argsValue:d,onArgsChange:h,showModelInput:f,modelValue:w,onModelChange:k,historyProviderNode:p,onConfirm:y,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(wt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:v=>o(v.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(v=>s.jsx("option",{value:v.key,children:v.label},v.key))}),(b==null?void 0:b.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:b.description})]}),p,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}`)),f&&k&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:w||"",onChange:v=>k(v.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),m&&h&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:d||"",onChange:v=>h(v.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:x,disabled:u,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:y,disabled:u,children:[s.jsx(Aa,{size:14}),u?l:c]})]})]})})}function oi(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function is(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,o=[];a&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])o.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${oi(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&o.push({key:`custom:${c}`,label:oi(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(o.some(m=>m.key===u))return{options:o,selectedKey:u}}return l?{options:o,selectedKey:`saved:${l.id}`}:c?{options:o,selectedKey:`custom:${c}`}:{options:o,selectedKey:"__home__"}}function px(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function hx(e){return[px(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function xx(e){return e.lastLaunchedAt?sn(e.lastLaunchedAt):""}function pl(e){return{metaText:hx(e),updatedLabel:xx(e)}}function Dn(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function bx({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var Ye,mt,pt,dt;const c=lr(),[l,u]=i.useState(!1),m=(((Ye=e.detectedIdes)==null?void 0:Ye.length)||0)>0,d=i.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),h=e.defaultWorkspaceId||null,[f,w]=i.useState(h||((mt=d[0])==null?void 0:mt.id)||""),[k,p]=i.useState(""),[y,x]=i.useState(""),[b,v]=i.useState([]),[R,g]=i.useState(!1),[M,C]=i.useState(""),[S,j]=i.useState(!1),[W,L]=i.useState(Dn(m,t.length,r.length)),I=i.useRef(null),[D,U]=i.useState(null),K=i.useRef("__home__"),[N,A]=i.useState("__home__"),[z,$]=i.useState(""),[B,V]=i.useState(""),[G,me]=i.useState(""),[ne,xe]=i.useState([]),[de,be]=i.useState(()=>ht().textQuery),[he,Y]=i.useState(()=>ht().workspaceQuery),[oe,J]=i.useState(()=>ht().modelQuery),[ue,le]=i.useState(()=>ht().resumableOnly),[Se,ie]=i.useState(()=>ht().sortMode),[pe,re]=i.useState(!1),[Z,ee]=i.useState(!1),q=i.useRef(null),X=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const ae=f==="__custom__"?k.trim():((pt=d.find(Te=>Te.id===f))==null?void 0:pt.path)||"",je=f==="__custom__"&&!!ae&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ke=f!=="__custom__"&&((dt=d.find(Te=>Te.id===f))==null?void 0:dt.path)||"",te=i.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),E=i.useCallback(async Te=>{g(!0),C("");try{const Fe=await a(Te);x(Fe.path),p(Fe.path),v(Fe.directories)}catch(Fe){C(Fe instanceof Error?Fe.message:"Could not load folder")}finally{g(!1)}},[a]),ve=i.useCallback(()=>{var Fe;w("__custom__"),j(!0);const Te=dn(e.platform,ln(k.trim(),ke,te,e.defaultWorkspacePath,(Fe=d.find(Ge=>Ge.id===h))==null?void 0:Fe.path,d.map(Ge=>Ge.path)));E(Te)},[k,h,E,te,ke,e.platform,d]),Ce=i.useCallback(Te=>{if(Te!=null&&Te.workspaceId){w(Te.workspaceId),p("");return}if(Te!=null&&Te.workspacePath){w("__custom__"),p(Te.workspacePath);return}w(""),p("")},[]),we=i.useCallback(Te=>{if(w(Te),Te==="__custom__"){ve();return}p("")},[ve]),Pe=i.useCallback(Te=>{w("__custom__"),p(Te)},[]),Le=i.useCallback((Te,Fe)=>{I.current=Fe,K.current=Te.selectedWorkspaceKey||"__home__",A(Te.selectedWorkspaceKey||"__home__"),$(Te.initialArgs||""),V(Te.initialModel||""),me(""),xe([]);const Ge=Te.providerType?`${e.id}:${Te.providerType}`:null;if(np(X.current,Ge)){const ct=ht();be(ct.textQuery),Y(ct.workspaceQuery),J(ct.modelQuery),le(ct.resumableOnly),ie(ct.sortMode)}X.current=Ge,U(Te),Te.providerType&&o&&(re(!0),o(Te.providerType).then(ct=>xe(ct||[])).catch(ct=>console.warn("Failed to load saved sessions",ct)).finally(()=>re(!1)))},[o,e.id]),Oe=i.useMemo(()=>Dc(ne,{textQuery:de,workspaceQuery:he,modelQuery:oe,resumableOnly:ue,sortMode:Se}),[oe,ue,ne,Se,de,he]);i.useEffect(()=>{G&&(Oe.some(Te=>Te.providerSessionId===G)||me(""))},[Oe,G]);const ze=i.useCallback(()=>{I.current&&(ee(!0),I.current().finally(()=>{I.current=null,ee(!1),U(null)}))},[]),tt=i.useCallback(()=>{I.current=null,U(null)},[]),Xe=i.useCallback(Te=>{K.current=Te,A(Te)},[]);return i.useEffect(()=>{var Te;q.current!==e.id&&(q.current=e.id,w(h||((Te=d[0])==null?void 0:Te.id)||"__custom__"),p(""),x(""),v([]),C(""),j(!1),be(ht().textQuery),Y(ht().workspaceQuery),J(ht().modelQuery),le(ht().resumableOnly),ie(ht().sortMode),X.current=null,L(Dn(m,t.length,r.length)))},[r.length,t.length,h,m,e.id,d]),i.useEffect(()=>{var Te;f!=="__custom__"&&(f&&d.some(Fe=>Fe.id===f)||w(h||((Te=d[0])==null?void 0:Te.id)||"__custom__"))},[h,f,d]),i.useEffect(()=>{W==="ide"&&m||W==="cli"&&t.length>0||W==="acp"&&r.length>0||L(Dn(m,t.length,r.length))},[W,r.length,t.length,m]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:m,workspaceRows:d,defaultWorkspaceId:h,workspaceChoice:f,customWorkspacePath:k,browseCurrentPath:y,browseDirectories:b,browseBusy:R,browseError:M,browseDialogOpen:S,activeLauncherKind:W,launchConfirm:D,launchConfirmWorkspaceKeyRef:K,launchConfirmWorkspaceKey:N,launchConfirmArgs:z,launchConfirmModel:B,launchConfirmResumeId:G,launchConfirmSavedSessions:ne,launchConfirmTextFilter:de,launchConfirmWorkspaceFilter:he,launchConfirmModelFilter:oe,launchConfirmResumableOnly:ue,launchConfirmSortMode:Se,filteredLaunchConfirmSavedSessions:Oe,launchConfirmSessionsLoading:pe,launchConfirmBusy:Z,resolvedWorkspacePath:ae,canCreateMissingWorkspace:je,openBrowseDialog:ve,loadBrowsePath:E,handleWorkspaceChoiceChange:we,chooseCustomWorkspacePath:Pe,setCustomWorkspacePath:p,setBrowseDialogOpen:j,setActiveLauncherKind:L,openLaunchConfirm:Le,handleConfirmLaunch:ze,closeLaunchConfirm:tt,setWorkspaceSelectionFromOption:Ce,setLaunchConfirmWorkspaceKeyAndSync:Xe,setLaunchConfirmArgs:$,setLaunchConfirmModel:V,setLaunchConfirmResumeId:me,setLaunchConfirmTextFilter:be,setLaunchConfirmWorkspaceFilter:Y,setLaunchConfirmModelFilter:J,setLaunchConfirmResumableOnly:le,setLaunchConfirmSortMode:ie}}function gx({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:c,machineAction:l,isStandalone:u,section:m,showBottomNav:d,onBack:h,onSectionChange:f,onOpenConversation:w,onOpenRecent:k,onOpenMachineDetails:p,onMachineUpgrade:y,onLaunchDetectedIde:x,onAddWorkspace:b,onBrowseDirectory:v,onLaunchWorkspaceProvider:R,onListSavedSessions:g}){const M=N=>N==="ide"?"IDE":N==="cli"?"CLI":"ACP",C=r.slice(0,4),S=t.slice(0,3),j=bx({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:v,onListSavedSessions:g}),W=i.useMemo(()=>C.map(N=>{const{metaText:A,updatedLabel:z}=pl(N);return{key:`recent-launch:${N.id}`,primary:N.label,secondary:A,updatedLabel:z,onClick:()=>{const{options:$,selectedKey:B}=is({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspacePath:N.workspace});j.openLaunchConfirm({title:N.kind==="ide"?rs("restart-ide",N.label):N.providerSessionId?qa(N.label):rs("start-fresh",N.label),description:N.kind==="ide"?ns("restart-ide"):N.providerSessionId?Ya():ns("start-fresh"),confirmLabel:N.kind==="ide"?Is("restart-ide"):N.providerSessionId?Yr(!0):Is("start-fresh"),busyLabel:N.kind==="ide"?Ms("restart-ide"):N.providerSessionId?Va(!0):Ms("start-fresh"),workspaceOptions:$,selectedWorkspaceKey:B,details:[{label:"Mode",value:M(N.kind)},...N.providerType?[{label:"Provider",value:N.providerType}]:[]]},async()=>{const V=$.find(G=>G.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(V),await k({...N,workspace:(V==null?void 0:V.workspacePath)??null})})}}}),[j,k,C]),L=i.useMemo(()=>S.map(N=>({key:`recent-chat:${N.conversation.tabKey}`,primary:it(N.conversation),secondary:Ff(N.conversation,{timestampLabel:N.timestamp?Qi(N.timestamp):null}),unread:N.unread,onClick:()=>w(N.conversation)})),[w,S]),I=j.showAllRecent?W:W.slice(0,4),D=W.length>0,U=L.length>0,K=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${K} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:s.jsx(Ta,{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:St(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:L.map(N=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${N.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:N.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:N.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))})]}),D&&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:I.map(N=>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:N.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:N.primary}),N.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:N.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))}),W.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:()=>j.setShowAllRecent(N=>!N),children:j.showAllRecent?"Show fewer":`Show ${W.length-4} more`})})]}),(j.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:j.workspaceChoice,onChange:N=>j.handleWorkspaceChoiceChange(N.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:j.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[j.workspaceRows.map(N=>s.jsxs("option",{value:N.id,children:[N.id===j.defaultWorkspaceId?"⭐ ":"",nn(N.path,N.label)||N.path]},N.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),j.workspaceChoice==="__custom__"&&s.jsxs("div",{className:"flex flex-col gap-2.5",children:[s.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Ns,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),s.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:j.resolvedWorkspacePath||j.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:j.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:()=>{j.resolvedWorkspacePath&&b(j.resolvedWorkspacePath)},disabled:!j.resolvedWorkspacePath||j.browseBusy,children:"Save as workspace"})]})]}),j.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[j.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.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:()=>j.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.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:()=>j.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.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:()=>j.setActiveLauncherKind("acp"),children:"ACP"})]}),j.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:j.activeLauncherKind==="ide"?"Choose an IDE":j.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:j.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(N=>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:A,selectedKey:z}=is({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${N.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:A,selectedWorkspaceKey:z,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:N.name}]},async()=>{const $=A.find(B=>B.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption($),x(N.type,{workspacePath:($==null?void 0:$.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:N.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},N.type)):(j.activeLauncherKind==="cli"?n:a).map(N=>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 A=j.activeLauncherKind==="cli"?"cli":"acp",{options:z,selectedKey:$}=is({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${N.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${A.toUpperCase()}`,workspaceOptions:z,selectedWorkspaceKey:$,details:[{label:"Mode",value:A.toUpperCase()},{label:"Provider",value:N.displayName}],showArgsInput:!0,showModelInput:A==="acp",initialArgs:"",initialModel:"",providerType:N.type},async()=>{const B=z.find(V=>V.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(B),R(A,N.type,{workspaceId:(B==null?void 0:B.workspaceId)??null,workspacePath:(B==null?void 0:B.workspacePath)??null,args:j.launchConfirmArgs,model:j.launchConfirmModel,resumeSessionId:j.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[N.icon?`${N.icon} `:"",N.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},N.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,j.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(j.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:y,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:p,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),j.browseDialogOpen&&s.jsx(mn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:j.browseCurrentPath,directories:j.browseDirectories,busy:j.browseBusy,error:j.browseError,confirmLabel:"Use this folder",onClose:()=>j.setBrowseDialogOpen(!1),onNavigate:N=>{j.loadBrowsePath(N)},onConfirm:N=>{j.chooseCustomWorkspacePath(N),j.setBrowseDialogOpen(!1)}}),j.launchConfirm&&s.jsx(ao,{title:j.launchConfirm.title,description:j.launchConfirm.description,details:j.launchConfirm.details,workspaceOptions:j.launchConfirm.workspaceOptions,selectedWorkspaceKey:j.launchConfirmWorkspaceKey,onWorkspaceChange:j.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:j.launchConfirm.providerType?Yr(!!j.launchConfirmResumeId):j.launchConfirm.confirmLabel,busyLabel:j.launchConfirm.providerType?void 0:j.launchConfirm.busyLabel,busy:j.launchConfirmBusy,showArgsInput:j.launchConfirm.showArgsInput,argsValue:j.launchConfirmArgs,onArgsChange:j.setLaunchConfirmArgs,showModelInput:j.launchConfirm.showModelInput,modelValue:j.launchConfirmModel,onModelChange:j.setLaunchConfirmModel,historyProviderNode:j.launchConfirm.providerType&&(j.launchConfirmSessionsLoading||j.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"}),j.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:Ga()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:j.launchConfirmTextFilter,onChange:N=>j.setLaunchConfirmTextFilter(N.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:j.launchConfirmWorkspaceFilter,onChange:N=>j.setLaunchConfirmWorkspaceFilter(N.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:j.launchConfirmModelFilter,onChange:N=>j.setLaunchConfirmModelFilter(N.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),s.jsxs("select",{value:j.launchConfirmSortMode,onChange:N=>j.setLaunchConfirmSortMode(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:j.launchConfirmBusy||j.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:j.launchConfirmResumableOnly,onChange:N=>j.setLaunchConfirmResumableOnly(N.target.checked),disabled:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:j.launchConfirmResumeId,onChange:N=>j.setLaunchConfirmResumeId(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:j.launchConfirmBusy||j.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:ip()}),j.filteredLaunchConfirmSavedSessions.map(N=>s.jsxs("option",{value:N.providerSessionId,disabled:!N.canResume,children:[N.title||N.providerSessionId," ",N.canResume?"":"(workspace missing)"]},N.providerSessionId))]}),!j.launchConfirmSessionsLoading&&j.launchConfirmSavedSessions.length>0&&j.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),j.launchConfirmResumeId&&(()=>{const N=j.filteredLaunchConfirmSavedSessions.find(z=>z.providerSessionId===j.launchConfirmResumeId);if(!N)return null;const A=fl(N);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:A.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:A.providerSessionId}),s.jsx("div",{className:"mt-1",children:A.metaLine}),A.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:A.updatedLabel}),A.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:A.preview})]})})()]}),onConfirm:j.handleConfirmLaunch,onCancel:j.closeLaunchConfirm}),d&&s.jsx(ml,{section:m,onSectionChange:f})]})}function Dr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function yx(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:Dr(e)}function vx(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 wx(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:us(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,u,m,d;const a=rr(n)?"cli":ws(n)?"acp":"ide",o=us(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(rr(n)?n.cliName||n.type:ws(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:ws(n)?o||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((d=(m=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:m.call(u,-1))==null?void 0:d.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function jx(e,t){const r=new Map;for(const n of t){const a=hs(n.conversation),o=r.get(a);o?o.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],o=[...a].sort((h,f)=>f.timestamp-h.timestamp)[0]||null,c=(o==null?void 0:o.conversation)||null,l=aa(n),u=a.filter(h=>h.unread||h.requiresAction).length,m=vx(n),d=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:St(n,{fallbackId:n.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:l,preview:c?Uf(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 kx(e){return e==="chat"}function Cr(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 Sx({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:w,setSelectedTabKey:k,setScreen:p,setSelectedMachineId:y,setSection:x,setMachineBackTarget:b,resetMachineAction:v}){const R=i.useRef(null),g=i.useCallback(M=>{if(!(M!=null&&M.sessionId))return;const C=Fr(M,c),S=Math.max(Date.now(),ts(M),C.lastUpdated||0);Cr("mark_read:start",{tabKey:M.tabKey,sessionId:M.sessionId,displayPrimary:it(M),inboxBucket:C.inboxBucket,unread:C.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:ts(M),readAt:S}),l(hs(M)||M.routeId,"mark_session_seen",{sessionId:M.sessionId,providerSessionId:M.providerSessionId,seenAt:S,completionMarker:C.completionMarker}).then(j=>{Cr("mark_read:result",{tabKey:M.tabKey,sessionId:M.sessionId,result:j})}).catch(j=>{Cr("mark_read:error",{tabKey:M.tabKey,sessionId:M.sessionId,error:j instanceof Error?j.message:String(j)})})},[c,l]);return i.useEffect(()=>{var C;if(!n){kx(o)&&p("inbox"),k(((C=e[0])==null?void 0:C.tabKey)||null),R.current=null;return}if(o!=="chat"){R.current=null;return}const M=`${n.tabKey}:${n.sessionId||""}`;R.current!==M&&(R.current=M,g(n))},[e,g,o,n,p,k]),i.useEffect(()=>{if(!u)return;const M=e.find(C=>C.tabKey===u);M&&(k(M.tabKey),p("chat"),m==null||m())},[e,m,u,p,k]),i.useEffect(()=>{if(!d)return;const M=t.find(C=>C.id===d);M&&(y(M.id),v(),x("machines"),b("inbox"),p("machine"),h==null||h())},[t,h,d,v,b,p,x,y]),i.useEffect(()=>{f&&(x(f),p("inbox"),w==null||w())},[w,f,p,x]),i.useEffect(()=>{const M=r.filter(C=>C.inboxBucket==="task_complete"||C.unread);M.length!==0&&Cr("inbox_state",{screen:o,selectedTabKey:a,items:M.map(C=>{const S=Fr(C.conversation,c);return{liveState:S,tabKey:C.conversation.tabKey,sessionId:C.conversation.sessionId,displayPrimary:it(C.conversation),serverBucket:S.inboxBucket,computedBucket:C.inboxBucket,serverUnread:S.unread,computedUnread:C.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:ts(C.conversation)}})})},[r,c,o,a]),{markConversationRead:g}}function Nx(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ii(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Cx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Tx({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,o]=i.useState("idle"),[c,l]=i.useState(""),[u,m]=i.useState(null),d=i.useCallback(()=>{o("idle"),l(""),m(null)},[]),h=i.useCallback(async(b,v,R)=>{var g;try{o("loading"),l(`Launching ${v}…`);const M={ideType:v,enableCdp:!0};(g=R==null?void 0:R.workspacePath)!=null&&g.trim()&&(M.workspace=R.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]),f=i.useCallback(async(b,v,R)=>{if(v.trim())try{o("loading"),l(R!=null&&R.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(b,"workspace_add",{path:v.trim(),createIfMissing:(R==null?void 0:R.createIfMissing)===!0});if(g!=null&&g.success){o("done"),l(R!=null&&R.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]),w=i.useCallback(async b=>{var v,R,g,M,C,S;try{o("loading"),l("Starting daemon upgrade…");const j=await e(b,"daemon_upgrade",{});if((v=j==null?void 0:j.result)!=null&&v.alreadyLatest){o("done"),l(`Already on v${((R=j==null?void 0:j.result)==null?void 0:R.version)||"latest"}.`);return}if((g=j==null?void 0:j.result)!=null&&g.upgraded||(M=j==null?void 0:j.result)!=null&&M.success){o("done"),l(`Upgrade to v${((C=j==null?void 0:j.result)==null?void 0:C.version)||"latest"} started. Daemon is restarting…`);return}o("error"),l(((S=j==null?void 0:j.result)==null?void 0:S.error)||"Upgrade failed")}catch(j){o("error"),l(j instanceof Error?j.message:"Upgrade failed")}},[e]),k=i.useCallback(async(b,v,R,g)=>{var S,j,W;const M=Date.now(),C={machineId:b,kind:v,providerType:R,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 ${R}…`),m(C);const L={cliType:R};(S=g==null?void 0:g.workspacePath)!=null&&S.trim()?L.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(L.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(L.resumeSessionId=g.resumeSessionId),(j=g==null?void 0:g.args)!=null&&j.trim()&&(L.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),(W=g==null?void 0:g.model)!=null&&W.trim()&&(L.initialModel=g.model.trim());const I=await e(b,"launch_cli",L),D=(I==null?void 0:I.result)||I,U=(D==null?void 0:D.sessionId)||(D==null?void 0:D.id);if(I!=null&&I.success&&U){m(null),o("done"),l(`${R} launched`),t(Gt(U));return}if(I!=null&&I.success){o("loading"),l(`${R} launch requested — waiting for session…`);return}m(null),o("error"),l((I==null?void 0:I.error)||(D==null?void 0:D.error)||`Could not launch ${v.toUpperCase()} workspace`)}catch(L){if(Cx(L)){o("loading"),l(`${R} launch requested — waiting for session…`);return}m(null),o("error"),l(L instanceof Error?L.message:`Could not launch ${v.toUpperCase()} workspace`)}},[t,e]),p=i.useCallback(async(b,v)=>{try{const R=await e(b,"list_saved_sessions",{providerType:v,kind:"cli",limit:30}),g=(R==null?void 0:R.result)??R;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(R){return console.error("Failed to list saved sessions on mobile:",R),[]}},[e]),y=i.useCallback(async(b,v)=>un(e,b,v),[e]);i.useEffect(()=>{if(!u)return;const b=ii(u.workspacePath),v=r.find(g=>{var L,I,D,U;if(!g||g.type==="adhdev-daemon"||Nx(g.daemonId||g.id)!==u.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==u.kind||String(g.agentType||g.type||"")!==u.providerType)return!1;const j=String(g.providerSessionId||"");if(u.resumeSessionId&&j)return j===u.resumeSessionId;if(b){const K=ii(g.workspace||g.runtimeWorkspaceLabel);return K?K===b:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((U=(D=(I=(L=g.activeChat)==null?void 0:L.messages)==null?void 0:I.at)==null?void 0:D.call(I,-1))==null?void 0:U.timestamp)||0)>=u.startedAt-5e3});if(!v)return;const R=wc({entrySessionId:v.sessionId,entryInstanceId:v.instanceId,entryRouteId:v.id,conversations:n});R&&(m(null),o("done"),l(`${u.providerType} launched`),t(Gt(R)))},[n,r,t,u]),i.useEffect(()=>{if(!u)return;const b=window.setTimeout(()=>{m(v=>!v||v.startedAt!==u.startedAt?v:(o("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(b)},[u]);const x=i.useCallback(async(b,v)=>{if(v.kind==="ide"&&v.providerType){await h(b,v.providerType,{workspacePath:v.workspace||null});return}(v.kind==="cli"||v.kind==="acp")&&v.providerType&&await k(b,v.kind,v.providerType,{workspacePath:v.workspace||null,resumeSessionId:v.providerSessionId||null})},[h,k]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:h,handleAddWorkspace:f,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:k,handleListSavedSessions:p,handleBrowseDirectory:y,handleOpenRecent:x}}function Ix({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:m}){const d=i.useCallback(x=>{o(x.tabKey),c("chat"),n(x)},[n,c,o]),h=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]),f=i.useCallback(()=>{n(t),c("inbox")},[n,t,c]),w=i.useCallback((x,b="inbox")=>{l(x),a(),u("machines"),m(b),c("machine")},[a,m,c,u,l]),k=i.useCallback(x=>{const b=hs(x);b&&w(b,"chat")},[w]),p=i.useCallback(()=>{a(),c(r)},[r,a,c]),y=i.useCallback(x=>{u(x),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:h,backFromConversation:f,openMachine:w,openConversationMachine:k,backFromMachine:p,changeMachineSection:y}}function ps(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function Mx(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Ax({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,userName:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:w,onOpenHistory:k,onOpenRemote:p,onStopCli:y,wsStatus:x,isConnected:b,onShowHiddenConversation:v,onShowAllHiddenConversations:R,onHideConversation:g,onOpenNewSession:M,liveSessionInboxState:C,setCliViewModeOverrides:S}){const[j,W]=i.useState(()=>{var te;return((te=e[0])==null?void 0:te.tabKey)||null}),[L,I]=i.useState(()=>e[0]?"chat":"inbox"),[D,U]=i.useState("chats"),[K,N]=i.useState(null),[A,z]=i.useState("inbox"),$=i.useRef([]),B=Ls(),V="0.9.54",G=i.useMemo(()=>e.find(te=>te.tabKey===j)||e[0]||null,[e,j]),me=i.useMemo(()=>G?r.find(te=>te.id===G.routeId):void 0,[r,G]),ne=i.useMemo(()=>!G||qe(G)||!Ze(G)?null:_s(G),[G]),xe=i.useMemo(()=>r.filter(te=>te.type==="adhdev-daemon").sort(Pa),[r]),de=i.useMemo(()=>xe.find(te=>te.id===K)||null,[xe,K]),be=on({sendDaemonCommand:a,activeConv:G||void 0,setActionLogs:o,isStandalone:c}),he=Tx({sendDaemonCommand:a,navigate:B,ides:r,conversations:e}),Y=i.useMemo(()=>e.map(te=>{const E=L==="chat"&&(G==null?void 0:G.tabKey)===te.tabKey,ve=rn(te,C,{hideOpenTaskCompleteUnread:!0,isOpenConversation:E}),Ce=ts(te),we=Ac(te);return{conversation:te,timestamp:Ce,preview:we,unread:ve.unread,requiresAction:ve.requiresAction,isWorking:ve.isWorking,inboxBucket:ve.inboxBucket}}),[e,C,L,G]),{markConversationRead:oe}=Sx({conversations:e,machineEntries:xe,items:Y,selectedConversation:G,selectedTabKey:j,screen:L,liveSessionInboxState:C,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:w,setSelectedTabKey:W,setScreen:I,setSelectedMachineId:N,setSection:U,setMachineBackTarget:z,resetMachineAction:he.resetMachineAction}),J=Ix({conversations:e,selectedConversation:G,machineBackTarget:A,markConversationRead:oe,resetMachineAction:he.resetMachineAction,setSelectedTabKey:W,setScreen:I,setSelectedMachineId:N,setSection:U,setMachineBackTarget:z}),ue=i.useMemo(()=>Dr(Y.filter(te=>te.requiresAction)),[Y]),le=i.useMemo(()=>Dr(Y.filter(te=>te.unread&&!te.requiresAction)),[Y]),Se=i.useMemo(()=>yx(Y.filter(te=>!te.unread&&!te.requiresAction&&te.isWorking),$.current),[Y]);i.useEffect(()=>{$.current=Se.map(te=>te.conversation.tabKey)},[Se]);const ie=i.useMemo(()=>Dr(Y.filter(te=>!te.unread&&!te.requiresAction&&!te.isWorking)),[Y]),pe=i.useMemo(()=>de?Y.filter(te=>hs(te.conversation)===de.id):[],[Y,de]),re=i.useMemo(()=>wx(de,r),[r,de]),Z=(de==null?void 0:de.version)||null,ee=!!de&&!!Z&&!0&&Z!==V,q=i.useMemo(()=>(de==null?void 0:de.availableProviders)||[],[de]),X=i.useMemo(()=>q.filter(te=>ps(te,"cli")).map(te=>({type:te.type,displayName:te.displayName||te.type,icon:te.icon})),[q]),ae=i.useMemo(()=>q.filter(te=>ps(te,"acp")).map(te=>({type:te.type,displayName:te.displayName||te.type,icon:te.icon})),[q]),je=i.useMemo(()=>jx(xe,Y),[Y,xe]),ke=i.useCallback(async te=>{de&&await he.handleOpenRecent(de.id,te)},[he,de]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:L==="chat"&&G?s.jsx(dx,{selectedConversation:G,isAcp:qe(G),isStandalone:c,selectedIdeEntry:me,actionLogs:n,userName:l,isSendingChat:be.isSendingChat,sendFeedbackMessage:be.sendFeedbackMessage,isFocusingAgent:be.isFocusingAgent,handleModalButton:be.handleModalButton,handleRelaunch:be.handleRelaunch,onBack:J.backFromConversation,onOpenNativeConversation:J.openNativeConversation,onOpenMachine:J.openConversationMachine,onHideConversation:g,onOpenHistory:k,onOpenRemote:p,onStopCli:y,cliViewMode:ne,onSetCliViewMode:async te=>{await nl({conversation:G,mode:te,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:S})},handleSendChat:be.handleSendChat,handleFocusAgent:be.handleFocusAgent}):L==="machine"&&de?s.jsx(gx,{selectedMachineEntry:de,selectedMachineConversations:pe,selectedMachineRecentLaunches:re,cliProviders:X,acpProviders:ae,selectedMachineNeedsUpgrade:ee,appVersion:V,machineAction:he.machineAction,isStandalone:c,section:D,showBottomNav:A==="inbox",onBack:J.backFromMachine,onSectionChange:J.changeMachineSection,onOpenConversation:J.openConversation,onOpenRecent:ke,onOpenMachineDetails:()=>B(`/machines/${de.id}`),onMachineUpgrade:()=>he.handleMachineUpgrade(de.id),onLaunchDetectedIde:(te,E)=>he.handleLaunchDetectedIde(de.id,te,E),onAddWorkspace:(te,E)=>he.handleAddWorkspace(de.id,te,E),onBrowseDirectory:te=>he.handleBrowseDirectory(de.id,te),onLaunchWorkspaceProvider:(te,E,ve)=>he.handleLaunchWorkspaceProvider(de.id,te,E,ve),onListSavedSessions:te=>he.handleListSavedSessions(de.id,te)}):s.jsx(mx,{section:D,attentionItems:ue,unreadItems:le,workingItems:Se,completedItems:ie,hiddenConversations:t,machineCards:je,getAvatarText:Mx,actionLogs:n,sendDaemonCommand:a,onOpenConversation:J.openConversation,onShowConversation:v,onShowAllHidden:R,onOpenNewSession:M,onOpenMachine:J.openMachine,onOpenSettings:()=>B("/settings"),onSectionChange:U,wsStatus:x,isConnected:b,isStandalone:c})})}function En(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Lx({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const c=i.useRef(0),[l,u]=i.useState(!1),[m,d]=i.useState(null),h=i.useCallback(()=>{c.current=0,u(!1),d(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const f=i.useCallback(y=>{y.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),w=i.useCallback(y=>{if(!y.dataTransfer.types.includes("text/tab-key"))return;if(y.preventDefault(),!En(t,r)){d("merge");return}const x=y.currentTarget.getBoundingClientRect(),b=y.clientX-x.left,v=x.width/3;b<v?d("split-left"):b>v*2?d("split-right"):d("merge")},[t,r]),k=i.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),d(null))},[]),p=i.useCallback(y=>{c.current=0,u(!1);const x=y.dataTransfer.getData("text/tab-key"),b=x?e.some(R=>R.tabKey===x):!1,v=m;if(d(null),o(),!!x){if(y.preventDefault(),v==="split-left"&&En(t,r)){r==null||r(x,"split-left");return}if(v==="split-right"&&En(t,r)){r==null||r(x,"split-right");return}if(b){a(x);return}n==null||n(x)}},[e,m,t,r,n,a,o]);return{dragOver:l,dropAction:m,resetDragState:h,handleDragEnter:f,handleDragOver:w,handleDragLeave:k,handleDrop:p}}function Rx(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 _x({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,c]=i.useState(t??null),[l,u]=i.useState(r??[]),[m,d]=i.useState(null),h=i.useRef(null),f=i.useRef(null),w=i.useRef(n),k=i.useRef(a);i.useEffect(()=>{w.current=n},[n]),i.useEffect(()=>{k.current=a},[a]),i.useEffect(()=>{t&&t!==o&&c(t)},[t,o]),i.useEffect(()=>{u(C=>{const S=Rx(C,e);return S.length===C.length&&S.every((j,W)=>j===C[W])?C:S})},[e]);const p=i.useMemo(()=>{const C=m??l;if(C.length===0)return e;const S=new Map(C.map((j,W)=>[j,W]));return[...e].sort((j,W)=>{const L=S.get(j.tabKey)??999,I=S.get(W.tabKey)??999;return L-I})},[e,m,l]);i.useEffect(()=>{var S,j;if(p.length===0){o!==null&&(c(null),(S=w.current)==null||S.call(w,null));return}if(o&&p.some(W=>W.tabKey===o))return;const C=p[0].tabKey;C!==o&&(c(C),(j=w.current)==null||j.call(w,C))},[p,o]);const y=i.useMemo(()=>p.find(C=>C.tabKey===o),[p,o]),x=i.useCallback(C=>{var S;c(C),(S=w.current)==null||S.call(w,C)},[]),b=i.useCallback((C,S,j)=>{u(W=>{var U;const L=W.filter(K=>K!==C),I=L.indexOf(S);if(I<0)return W;const D=j==="left"?I:I+1;return L.splice(D,0,C),(U=k.current)==null||U.call(k,L),L}),d(null)},[]),v=i.useCallback((C,S,j)=>{const L=(l.length>0?l:e.map(U=>U.tabKey)).filter(U=>U!==C),I=L.indexOf(S);if(I<0)return;const D=j==="left"?I:I+1;L.splice(D,0,C),h.current=L,d(L)},[l,e]),R=i.useCallback(()=>{var S;const C=h.current;C&&(u(C),(S=k.current)==null||S.call(k,C))},[]),g=i.useCallback(()=>{h.current=null,d(null)},[]),M=i.useCallback(C=>{u(S=>{var W;const j=S.filter(L=>L!==C);return j.push(C),(W=k.current)==null||W.call(k,j),j})},[]);return{activeTabId:o,activeConv:y,sortedConversations:p,previewOrderRef:h,draggingTabRef:f,selectTab:x,handleTabReorder:b,updatePreviewOrder:v,commitPreviewOrder:R,clearPreviewOrder:g,moveTabToEnd:M,setDraggingTabKey:C=>{f.current=C}}}function Px({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 oo({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,u=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?Pc: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:u}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),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:Dt,"aria-label":Dt,children:[s.jsx(zi,{size:14}),s.jsx("span",{children:Dt})]})}),c&&s.jsx(ul,{}),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 hl="adhdev-tab-shortcuts";function xl(){try{return JSON.parse(localStorage.getItem(hl)||"{}")}catch{return{}}}function bl({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,c]=i.useState(()=>xl()),[l,u]=i.useState(null),m=i.useCallback(h=>{const f=[];return h.metaKey&&f.push(a?"⌘":"Meta"),h.ctrlKey&&f.push("Ctrl"),h.altKey&&f.push(a?"⌥":"Alt"),h.shiftKey&&f.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(f.push(h.key.length===1?h.key.toUpperCase():h.key),f.join("+"))},[a]),d=i.useCallback(h=>{c(h);try{localStorage.setItem(hl,JSON.stringify(h))}catch{}},[]);return i.useEffect(()=>{if(!e||!l)return;const h=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){u(null);return}const w=m(f);if(!w)return;const k={...o};for(const[p,y]of Object.entries(k))y===w&&delete k[p];k[l]=w,d(k),u(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,o,d,m]),i.useEffect(()=>{if(!e)return;const h=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[w,k]of Object.entries(o))if(t.includes(w)&&m(f)===k){f.preventDefault(),r(),n(w);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,o,t,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const $n=e=>{e.preventDefault()},Dx=i.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:m,onConversationActivated:d,onPreviewReorder:h,onReorderTab:f,onCommitPreviewOrder:w,onClearPreviewOrder:k,onDragStateReset:p,onDragTabKeyChange:y,onReceiveTab:x,onOpenContextMenu:b,longPressTimer:v,isGroupActive:R}){const g=Rs(t),M=g.isGenerating?"agent-tab-generating":g.isWaiting?"agent-tab-waiting":"",C=g.isReconnecting,S=i.useCallback(A=>{l.current=t.tabKey,y(t.tabKey),A.dataTransfer.setData("text/tab-key",t.tabKey),A.dataTransfer.effectAllowed="move"},[t.tabKey,l,y]),j=i.useCallback(()=>{l.current=null,y(null),w(),k(),p()},[l,y,w,k,p]),W=i.useCallback(A=>{const z=l.current;if(!(!z||z===t.tabKey)&&A.dataTransfer.types.includes("text/tab-key")){A.preventDefault(),A.stopPropagation();const $=A.currentTarget.getBoundingClientRect(),B=A.clientX<$.left+$.width/2?"left":"right";h(z,t.tabKey,B)}},[t.tabKey,l,h]),L=i.useCallback(A=>{A.preventDefault(),A.stopPropagation();const z=A.dataTransfer.getData("text/tab-key");if(z&&z!==t.tabKey){const $=A.currentTarget.getBoundingClientRect(),B=A.clientX<$.left+$.width/2?"left":"right";c.includes(z)?f(z,t.tabKey,B):x&&x(z)}k()},[t.tabKey,c,f,x,k]),I=i.useCallback(A=>{A.stopPropagation(),u(),m(t.tabKey),d(t)},[t,d,u,m]),D=i.useCallback(A=>{A.preventDefault(),b(A.clientX,A.clientY,t.tabKey)},[t.tabKey,b]),U=i.useCallback(A=>{const z=A.touches[0];v.current=setTimeout(()=>{b(z.clientX,z.clientY,t.tabKey)},600)},[t.tabKey,v,b]),K=i.useCallback(()=>{v.current&&clearTimeout(v.current)},[v]),N=["adhdev-dockview-tab",M,r&&"is-active",R&&"is-group-active",C&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:N,draggable:!0,onDragStart:S,onDragEnd:j,onDragOver:W,onDrop:L,onClick:I,onContextMenu:D,onTouchStart:U,onTouchEnd:K,onTouchMove:K,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:"▲"}):C?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:[C?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:ss(t)}):g.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[ss(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:ss(t)}),s.jsx(cn,{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 Ex({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:w,onReceiveTab:k,onHideTab:p,isGroupActive:y,allowTabShortcuts:x=!0}){const[b,v]=i.useState(null),R=i.useRef(null),g=i.useRef(null),M=i.useMemo(()=>e.map(D=>D.tabKey),[e]);ir("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:C,tabShortcuts:S,shortcutListening:j,setShortcutListening:W,saveShortcuts:L}=bl({enabled:x,sortedTabKeys:e.map(D=>D.tabKey),onFocus:o,onSelectTab:c});i.useEffect(()=>{if(!b)return;const D=U=>{const K=document.querySelector("[data-pane-context-menu]");K&&K.contains(U.target)||v(null)};return window.addEventListener("mousedown",D,!0),()=>window.removeEventListener("mousedown",D,!0)},[b]),i.useEffect(()=>{const D=g.current;if(!D)return;const U=K=>{Math.abs(K.deltaY)<=Math.abs(K.deltaX)||(K.preventDefault(),D.scrollLeft+=K.deltaY)};return D.addEventListener("wheel",U,{passive:!1}),()=>D.removeEventListener("wheel",U)},[]);const I=i.useCallback((D,U,K)=>{v({x:D,y:U,tabKey:K})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:g,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(D=>s.jsx(Dx,{conv:D,isActive:t===D.tabKey,isDraggedTab:a.current===D.tabKey,isTaskCompleteUnread:n.has(D.tabKey),shortcut:x?S[D.tabKey]:void 0,conversationKeys:M,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:w,onReceiveTab:k,onOpenContextMenu:I,longPressTimer:R,isGroupActive:y},D.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:$n,onClick:D=>{D.stopPropagation(),W(b.tabKey),v(null)},children:["⌨ ",S[b.tabKey]?`Change shortcut (${S[b.tabKey]})`:"Set shortcut"]}),S[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:$n,onClick:()=>{const D={...S};delete D[b.tabKey],L(D),v(null)},children:"✕ Remove shortcut"})]}),p&&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:$n,onClick:()=>{p(b.tabKey),v(null)},children:"🚫 Hide from Dashboard"})]})]}),x&&j&&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:()=>W(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:D=>D.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",C?"⌘+1":"Ctrl+1",", ",C?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function $x({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,userName:u,groupIndex:m,onFocus:d,isSplitMode:h,numGroups:f,onMoveTab:w,onReceiveTab:k,style:p,onActiveTabChange:y,initialActiveTabId:x,initialTabOrder:b,onTabOrderChange:v,onHideTab:R,isFocused:g,allowTabShortcuts:M=!0,onOpenNewSession:C,liveSessionInboxState:S}){const{sendCommand:j}=vt(),W=i.useRef(null),{activeTabId:L,activeConv:I,sortedConversations:D,draggingTabRef:U,selectTab:K,handleTabReorder:N,updatePreviewOrder:A,commitPreviewOrder:z,clearPreviewOrder:$,moveTabToEnd:B,setDraggingTabKey:V}=_x({conversations:e,initialActiveTabId:x,initialTabOrder:b,onActiveTabChange:y,onTabOrderChange:v}),G=on({sendDaemonCommand:a,activeConv:I,setActionLogs:o,isStandalone:c}),{dragOver:me,dropAction:ne,resetDragState:xe,handleDragEnter:de,handleDragOver:be,handleDragLeave:he,handleDrop:Y}=Lx({conversations:e,numGroups:f,onMoveTab:w,onReceiveTab:k,onOwnTabDrop:B,onClearPreviewOrder:$}),oe=I&&!qe(I)&&_s(I)==="terminal",J=i.useMemo(()=>I?t.find(ie=>ie.id===I.routeId):void 0,[t,I]),ue=i.useMemo(()=>I?n.filter(ie=>ie.routeId===I.tabKey):[],[n,I]),le=i.useMemo(()=>new Set(D.filter(ie=>$u(ie,S,{isOpenConversation:ie.tabKey===L})).map(ie=>ie.tabKey)),[L,S,D]);ir("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:L,dragOver:me});const Se=i.useCallback(ie=>{ie.streamSource==="agent-stream"&&ie.agentType&&j(ie.routeId,pc(),{agentType:ie.agentType,...ie.sessionId&&{targetSessionId:ie.sessionId}}).catch(()=>{})},[j]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...p,outline:me?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(Ex,{conversations:D,activeTabId:L,groupIndex:m,numGroups:f,unreadTabKeys:le,draggingTabRef:U,onFocus:d,onSelectTab:K,onConversationActivated:Se,onPreviewReorder:A,onReorderTab:N,onCommitPreviewOrder:z,onClearPreviewOrder:$,onDragStateReset:xe,onDragTabKeyChange:V,onMoveTab:w,onReceiveTab:k,onHideTab:R,isGroupActive:g??!1,allowTabShortcuts:M}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:de,onDragOver:be,onDragLeave:he,onDrop:Y,children:[me&&s.jsx(Px,{dropAction:ne,canSplit:!!(f<4&&w)}),I?s.jsx(no,{activeConv:I,clearToken:r[I.tabKey]||0,isCliTerminal:!!oe,ideEntry:J,terminalRef:W,handleModalButton:G.handleModalButton,handleRelaunch:G.handleRelaunch,handleSendChat:G.handleSendChat,isSendingChat:G.isSendingChat,sendFeedbackMessage:G.sendFeedbackMessage,handleFocusAgent:G.handleFocusAgent,isFocusingAgent:G.isFocusingAgent,actionLogs:ue,userName:u,isInputActive:!h||!!g}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(oo,{conversationsCount:e.length,isSplitMode:h,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:C})})]})]})}function Bx({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:m,isStandalone:d,hasRegisteredMachines:h,userName:f,focusedGroup:w,focusGroup:k,moveTabToGroup:p,splitTabRelative:y,closeGroup:x,handleResizeStart:b,groupActiveTabIds:v,setGroupActiveTab:R,groupTabOrders:g,setGroupTabOrder:M,toggleHiddenTab:C,onOpenNewSession:S,allowTabShortcuts:j=!0,liveSessionInboxState:W}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((L,I)=>{const D=t&&n.length===r?`${n[I]}%`:void 0;return s.jsxs(jt.Fragment,{children:[t&&I>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(I-1,U),onDoubleClick:()=>x(I),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($x,{style:t?{flexBasis:D??`${100/r}%`,flexGrow:D?0:1,flexShrink:D?0:1}:void 0,conversations:L,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:m,isStandalone:d,hasRegisteredMachines:h,userName:f,groupIndex:I,isFocused:t&&w===I,onFocus:()=>k(I),isSplitMode:t,numGroups:r,onMoveTab:(U,K)=>{K==="left"&&I>0?p(U,I-1):K==="right"&&I<r-1?p(U,I+1):K==="split-left"&&r<4?y(U,I,"left"):K==="split-right"&&r<4&&y(U,I,"right")},onReceiveTab:U=>p(U,I),onActiveTabChange:U=>R(I,U),initialActiveTabId:v[I],initialTabOrder:g[I],onTabOrderChange:U=>M(I,U),onHideTab:C,onOpenNewSession:S,allowTabShortcuts:j,liveSessionInboxState:W})]},I)})})}function gl({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=i.useState(null),[c,l]=i.useState(null);i.useEffect(()=>e?lt.onScreenshot("ide-page",(d,h)=>{if(d!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(h)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var d;return e?((d=lt.onStatus)==null?void 0:d.call(lt,(h,f)=>{h===e&&f!=null&&f.screenshotUsage&&l(f.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,t]),i.useEffect(()=>{const m=e?lt.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&t?m.startScreenshots(t):m.stopScreenshots(t),()=>{m.stopScreenshots(t)}},[n,r,t,e]);const u=i.useCallback(async(m,d)=>{const h=e?lt.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(m,d,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const yl="adhdev-dashboard-action-shortcuts",Kx=1200,Ox=[["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 Wx(){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 vl(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 va(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Qr(e){const t=Object.fromEntries(vl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(yl)||"{}"),n={...t,...r};for(const[a,o]of Ox)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function wl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Hx({enabled:e=!0,onTrigger:t}){const r=Wx(),[n,a]=i.useState(()=>Qr(r)),[o,c]=i.useState(null),[l,u]=i.useState([]),m=i.useRef({parts:[],timer:null}),d=i.useCallback(p=>{const y=[];return p.metaKey&&y.push(r?"⌘":"Meta"),p.ctrlKey&&y.push("Ctrl"),p.altKey&&y.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&y.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(y.push(wl(p.key)),y.join("+"))},[r]),h=i.useCallback(p=>{a(p);try{localStorage.setItem(yl,JSON.stringify(p))}catch{}},[]);i.useEffect(()=>{const p=Qr(r),y=Object.entries(n),x=Object.entries(p);y.length===x.length&&y.every(([b,v])=>p[b]===v)||h(p)},[n,r,h]);const f=i.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),w=i.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},Kx))},[]);i.useEffect(()=>{if(!o)return;const p=y=>{if(y.preventDefault(),y.stopPropagation(),y.key==="Escape"){c(null),u([]);return}const x=d(y);if(!x)return;const v=!(y.metaKey||y.ctrlKey||y.altKey)&&/^[A-Z0-9]$/.test(x);if(l.length===0&&v){u([x]);return}const g=[...l,x].slice(0,2).join(" "),M={...n};for(const[C,S]of Object.entries(M))S===g&&delete M[C];M[o]=g,h(M),c(null),u([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,d,h,o,l]),i.useEffect(()=>{if(!e||o)return;const p=y=>{if(y.defaultPrevented)return;const x=d(y);if(!x)return;const b=y.metaKey||y.ctrlKey||y.altKey;if(va(y.target))return;const v=m.current.parts,R=b?[x]:[...v.slice(-1),x].slice(-2),g=R.join(" "),M=R[R.length-1],C=Object.entries(n).filter(([,I])=>!!I),S=C.find(([,I])=>I===g);if(S){y.preventDefault(),f(),t(S[0]);return}if(C.some(([,I])=>I.startsWith(`${g} `))){y.preventDefault(),m.current.parts=R,w();return}const W=C.find(([,I])=>I===M);if(W){y.preventDefault(),f(),t(W[0]);return}if(C.some(([,I])=>I.startsWith(`${M} `))){y.preventDefault(),m.current.parts=[M],w();return}f()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,w,e,d,t,f,o]),i.useEffect(()=>()=>f(),[f]);const k=i.useMemo(()=>vl(r),[r]);return{isMac:r,actionDefinitions:k,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:h}}function Fx({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 jl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function ci({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!jl(n):!0}function Ux({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:jl(r)}const kl=1e3,zx=4;function li(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function di(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function Vx({detachDelayMs:e=kl,stillnessThresholdPx:t=zx,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,c=null,l=null,u=null,m=null,d=!1;const h=()=>{m!=null&&(a(m),m=null)},f=()=>{h(),l=null},w=()=>{h(),o=null,c=null,l=null,u=null,d=!1},k=()=>{!o||!l||!u||d||m!=null||(m=n(()=>{m=null,!(!o||!l||!u||d)&&li(u,c)&&(di(l,u,t)||(d=!0,r({panelId:o,clientX:u.clientX,clientY:u.clientY})))},e))},p=x=>{if(!(!o||d)){if(!li(x,c)){u={clientX:x.clientX,clientY:x.clientY},f();return}(!l||di(l,x,t))&&(h(),l={clientX:x.clientX,clientY:x.clientY}),u={clientX:x.clientX,clientY:x.clientY},k()}},y=x=>{!o||d||(x&&(u={clientX:x.clientX,clientY:x.clientY}),f())};return{startDrag:x=>{h(),o=x.panelId,c=x.selfPanelBounds??null,l=null,u={clientX:x.clientX,clientY:x.clientY},d=!1},markSelfPanel:p,markNonSelfPanel:y,markNoDropTarget:y,markDockTarget:y,endDrag:w,isDragging:()=>o!=null,hasDetached:()=>d,dispose:w}}function Gx(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}const Sl=i.createContext(null);function fn(){const e=i.useContext(Sl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Er(e){return it(e)||e.tabKey}function qx(e){return`remote:${e}`}function At(e){return e.startsWith("remote:")}function ui(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Yx(e){e.preventDefault()}function Bn(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 Kn(e,t){e.classList.remove(Qn.className,Zn.className),e.classList.add(t==="light"?Qn.className:Zn.className)}function mi(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 Xx(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 Jx(e,t,r){var c;const n=[t];let a;for(const l of n){let u;for(const m of l){const d=e.addPanel({id:m.tabKey,component:"conversation",title:Er(m),params:{kind:"conversation",tabKey:m.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return r??((c=t[0])==null?void 0:c.tabKey)??null}function fi(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])At(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!==Er(n)&&a.api.setTitle(Er(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Er(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 pi(e,t,r){var u,m;const n=r?qx(r):null;for(const d of[...e.panels])At(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=_t(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),c=_c(a);if(o){o.title!==c&&o.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((m=e.panels.find(d=>!At(d.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function Qx({params:e,api:t}){var h;const r=fn(),n=i.useRef(null),[a,o]=i.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=on({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o(t.isActive);const f=[t.onDidActiveChange(w=>o(w.isActive)),t.onDidActiveGroupChange(w=>{if(!t.isActive&&!w.isActive){o(!1);return}o(t.isActive)})];return()=>{for(const w of f)w.dispose()}},[t]);const u=i.useMemo(()=>c?r.ides.find(f=>f.id===c.routeId):void 0,[r.ides,c]),m=i.useMemo(()=>c?r.actionLogs.filter(f=>f.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(oo,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const d=!qe(c)&&_s(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(no,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:d,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:m,userName:r.userName,scrollToBottomRequestNonce:((h=r.scrollToBottomRequest)==null?void 0:h.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:a})})}function Zx({params:e}){var u;const t=fn(),r=i.useMemo(()=>_t([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=i.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:c,handleRemoteAction:l}=gl({doId:a,targetSessionId:r?fc(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(Ji,{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 eb(){const e=fn();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(oo,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function tb(e){var w,k;Xx(e);const t=fn(),r=i.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=_t([...t.conversationsByTabKey.values()],e.params.routeId),y=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,x=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${y?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,o=e.api.isGroupActive,c=rn(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,u=c.isConnecting,m=c.isGenerating,d=c.isWaiting,h=c.unread,f=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:p=>{var y;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((y=p.target)==null?void 0:y.ownerDocument)??document})},children:[h&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?s.jsx("div",{className:"tab-spinner"}):d?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:"○"}):u?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:ss(n)}):u?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ss(n)}):s.jsx("span",{children:ss(n)})})]}),f&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:f,children:f})]})}function sb({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:u,userName:m,toggleHiddenTab:d,actionShortcuts:h,registerActionHandlers:f,onActiveTabChange:w,onOpenNewSession:k,onRequestScrollToBottom:p,requestedActiveTabKey:y,requestedRemoteIdeId:x,onRequestedActiveTabConsumed:b,scrollToBottomRequest:v,liveSessionInboxState:R,layoutProfile:g}){var Ge,ct,ft;const{theme:M}=Qa(),{sendCommand:C}=vt(),S=i.useRef(null),j=i.useRef(null),W=i.useRef(null),L=i.useRef(!1),I=i.useRef(!1),D=i.useRef(!1),U=i.useRef(null),K=i.useRef([]),[N,A]=i.useState(null),[z,$]=i.useState(0),B=i.useRef(typeof window>"u"?{}:Th(g)),V=i.useMemo(()=>new Map(e.map(H=>[H.tabKey,H])),[e]),G=i.useMemo(()=>{const H=S.current;return H?H.groups.some(_=>{try{const T=_.model.location.type;return T!=="floating"&&T!=="popout"?!1:_.panels.some(P=>V.has(P.id))}catch{return!1}}):!1},[V,z,e]),me=i.useCallback(()=>{var H;(H=S.current)==null||H.focus()},[]),ne=i.useCallback((H,_)=>{p==null||p(H,_)},[p]),xe=i.useCallback(H=>{const _=document,T=H.document;for(const ce of _.querySelectorAll('link[rel="stylesheet"]')){const Ne=T.createElement("link");Ne.rel="stylesheet",Ne.href=ce.href,ce.crossOrigin&&(Ne.crossOrigin=ce.crossOrigin),T.head.appendChild(Ne)}for(const ce of _.querySelectorAll("style")){const Ne=T.createElement("style");Ne.textContent=ce.textContent,T.head.appendChild(Ne)}const P=[];for(const ce of _.styleSheets)try{for(const Ne of ce.cssRules)Ne instanceof CSSStyleRule&&(Ne.selectorText===":root"||Ne.selectorText==="html")&&P.push(Ne.cssText)}catch{}if(P.length>0){const ce=T.createElement("style");ce.textContent=P.join(`
52
- `),T.head.appendChild(ce)}const F=_.documentElement.getAttribute("data-theme");F&&T.documentElement.setAttribute("data-theme",F),T.documentElement.style.colorScheme=F==="light"?"light":"dark",T.body.className=_.body.className;const Q=_.documentElement.getAttribute("style");Q&&T.documentElement.setAttribute("style",Q);const ye=T.getElementById("dv-popout-window");ye instanceof HTMLElement&&(ye.classList.add("adhdev-dockview"),Kn(ye,M))},[M]),de=i.useCallback(()=>{var _;const H=S.current;if(H)for(const T of H.groups)try{const P=(_=T.element)==null?void 0:_.ownerDocument;if(!P||P===document)continue;const F=P.getElementById("dv-popout-window");F instanceof HTMLElement&&(F.classList.add("adhdev-dockview"),Kn(F,M));const Q=document.documentElement.getAttribute("data-theme");Q&&P.documentElement.setAttribute("data-theme",Q),P.documentElement.style.colorScheme=Q==="light"?"light":"dark",P.body.className=document.body.className;const ye=document.documentElement.getAttribute("style");ye?P.documentElement.setAttribute("style",ye):P.documentElement.removeAttribute("style")}catch{}},[M]),be=i.useCallback(H=>{const _=S.current;if(!_)return;const T=_.getPanel(H);T&&_.addPopoutGroup(T,{popoutUrl:"/popout.html",onDidOpen:({window:P})=>{xe(P),pe();const F=V.get(H);P.document.title=F?`${it(F)} — ADHDev`:"ADHDev — Popout"}})},[V,xe]),he=i.useCallback(H=>{const _=S.current,T=_==null?void 0:_.getPanel(H);if(!_||!T)return;const P=_.groups.filter(F=>{var Q;try{return((Q=F.element)==null?void 0:Q.ownerDocument)===document}catch{return!0}});P.length>0?T.api.moveTo({group:P[0],position:"center"}):T.api.moveTo({position:"center"}),T.api.setActive()},[]),Y=i.useCallback(H=>{var P;const _=S.current;if(!_)return!1;const T=_.getPanel(H);if(!T)return!1;try{return((P=T.group.element)==null?void 0:P.ownerDocument)!==document}catch{return!1}},[]),oe=i.useCallback(H=>{Y(H)&&he(H),d(H)},[Y,he,d]),J=i.useCallback(H=>{const _=S.current,T=_==null?void 0:_.getPanel(H);!_||!T||_.addFloatingGroup(T,{width:600,height:500})},[]),ue=i.useCallback(H=>{var T;const _=(T=S.current)==null?void 0:T.getPanel(H);if(!_)return!1;try{return _.group.model.location.type==="floating"}catch{return!1}},[]),le=i.useCallback(()=>{var _,T;const H=(T=(_=S.current)==null?void 0:_.activePanel)==null?void 0:T.id;return!H||At(H)?null:V.has(H)?H:null},[V]),Se=i.useCallback(H=>{const _=S.current,T=_==null?void 0:_.getPanel(H);if(!_||!T)return;const P=_.groups.filter(F=>{try{return F.model.location.type==="grid"}catch{return!0}});P.length>0?T.api.moveTo({group:P[0],position:"center"}):T.api.moveTo({position:"center"}),T.api.setActive()},[]),ie=i.useCallback(()=>{var Q;const H=S.current;if(!H)return;const T=H.groups.filter(ye=>{var ce;try{return((ce=ye.element)==null?void 0:ce.ownerDocument)===document&&ye.model.location.type==="grid"}catch{return!1}})[0]||null,P=[...H.panels];for(const ye of P){const ce=(Q=ye.group.element)==null?void 0:Q.ownerDocument,Ne=ye.group.model.location.type;ce===document&&Ne==="grid"||(T&&T.id!==ye.group.id?ye.api.moveTo({group:T,position:"center"}):ye.api.moveTo({position:"center"}))}const F=H.activePanel;F&&(F.group.model.openPanel(F),F.api.setActive()),Bn(document)},[]),pe=i.useCallback(()=>{var _,T;const H=S.current;if(H)for(const P of H.groups){const F=(_=P.element)==null?void 0:_.ownerDocument;if(!F||F===document)continue;const Q=F.getElementById("dv-popout-window");if(!(Q instanceof HTMLElement))continue;let ye=null,ce=F.title||"ADHDev",Ne="Popout workspace";const De=P.activePanel;if(De)if(ye=De.id,At(De.id)){const Ae=((T=De.params)==null?void 0:T.routeId)||De.id.slice(7),Je=_t([...V.values()],Ae);ce=_c(Je),Ne=Je!=null&&Je.machineName?`Remote view · ${Je.machineName}`:"Remote view"}else{const Ae=V.get(De.id);ce=Ae?it(Ae):De.title||De.id,Ne=Ae?ss(Ae):"Dockview panel"}F.title=`${ce} — ADHDev`;const $e=Array.from(F.querySelectorAll("#adhdev-popout-header"));for(const Ae of $e)Ae.remove();const Ie=F.createElement("div");Ie.id="adhdev-popout-header",F.body.appendChild(Ie),Ie.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),Ie.innerHTML=`
51
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:k,onCancel:()=>d(null)})]})}const Xp=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Jp(){const{preference:e,setPreference:t}=Qa();return s.jsx("div",{className:"flex gap-2",children:Xp.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 Qp(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 Zp(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function In(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Yo(e){const{r:t,g:r,b:n}=Zp(e);return .2126*In(t)+.7152*In(r)+.0722*In(n)}function Xo(e,t){const r=Yo(e),n=Yo(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function Qc(e){const t=Qp(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Xo(t,r)>=Xo(t,n)?r:n}const ba={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},ga={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},eh=[{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"}}}],Zc="adhdev-chat-theme",el="adhdev-chat-theme-custom";function Pr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Zc)||"ember"}catch{return"ember"}}function Rt(e){try{const t=localStorage.getItem(el);if(t){const r=JSON.parse(t);return{...e==="dark"?ba:ga,...r[e]}}}catch{}return e==="dark"?ba:ga}function kr(e,t){try{localStorage.setItem(el,JSON.stringify({dark:e,light:t}))}catch{}}function Ct(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 Qr(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 th={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Js(e,t){var a;const r=(a=th[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",Qr(r,24)),n.style.setProperty("--accent-on-primary",Qc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Qr(r,18)})`),n.style.setProperty("--border-accent",Ct(r,.35)),n.style.setProperty("--nav-active-bg",Ct(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Ct(r,.06)}`)}function as(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Ct(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Ct(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Ct(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",Ct(e.borderSubtle,.5)),t.style.setProperty("--border-default",Ct(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Qr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Qc(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Qr(e.accentColor,40)})`),t.style.setProperty("--border-accent",Ct(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Ct(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Ct(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 ${Ct(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 Za(){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 sh(e){try{localStorage.setItem(Zc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=os()?"dark":"light";as(Rt(t))}else Za(),Js(e,os()?"dark":"light")}function rh(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Pr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=os()?"dark":"light";as(Rt(t))}else Za(),Js(e,os()?"dark":"light")}function os(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function xt({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 Os({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 nh({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=i.useState(()=>Rt(r));i.useEffect(()=>{a(Rt(r))},[r]);const o=i.useCallback((c,l)=>{a(u=>{const m={...u,[c]:l},h=Rt(r==="dark"?"light":"dark");return r==="dark"?kr(m,h):kr(h,m),as(m),t(m),m})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",s.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(Os,{title:"App Background",children:[s.jsx(xt,{label:"Background",value:n.bgPrimary,onChange:c=>o("bgPrimary",c)}),s.jsx(xt,{label:"Surface",value:n.bgSecondary,onChange:c=>o("bgSecondary",c)}),s.jsx(xt,{label:"Card",value:n.surfacePrimary,onChange:c=>o("surfacePrimary",c)})]}),s.jsxs(Os,{title:"App Text",children:[s.jsx(xt,{label:"Primary",value:n.textPrimary,onChange:c=>o("textPrimary",c)}),s.jsx(xt,{label:"Secondary",value:n.textSecondary,onChange:c=>o("textSecondary",c)}),s.jsx(xt,{label:"Muted",value:n.textMuted,onChange:c=>o("textMuted",c)})]}),s.jsxs(Os,{title:"Borders & Accent",children:[s.jsx(xt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>o("borderSubtle",c)}),s.jsx(xt,{label:"Border default",value:n.borderDefault,onChange:c=>o("borderDefault",c)}),s.jsx(xt,{label:"Accent",value:n.accentColor,onChange:c=>o("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Os,{title:"Chat Bubbles",children:[s.jsx(xt,{label:"User bubble",value:n.userBubble,onChange:c=>o("userBubble",c)}),s.jsx(xt,{label:"User text",value:n.userText,onChange:c=>o("userText",c)}),s.jsx(xt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>o("assistantBubble",c)}),s.jsx(xt,{label:"Agent text",value:n.assistantText,onChange:c=>o("assistantText",c)})]}),s.jsxs(Os,{title:"Chat Layout",children:[s.jsx(xt,{label:"Chat BG",value:n.containerBg,onChange:c=>o("containerBg",c)}),s.jsx(xt,{label:"Send button",value:n.sendButton,onChange:c=>o("sendButton",c)}),s.jsx(xt,{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?ba:ga,u=Rt(e?"light":"dark");e?kr(c,u):kr(u,c),a(c),as(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 ah(){const[e,t]=i.useState(Pr),[r,n]=i.useState(!0),[a,o]=i.useState(()=>Rt("dark"));i.useEffect(()=>{n(os());const u=new MutationObserver(()=>{const h=os();n(h);const f=Pr();f==="custom"?as(Rt(h?"dark":"light")):Js(f,h?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const h=os();n(h);const f=Pr();f==="custom"?as(Rt(h?"dark":"light")):Js(f,h?"dark":"light")};return m.addEventListener("change",d),()=>{u.disconnect(),m.removeEventListener("change",d)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?as(Rt(r?"dark":"light")):(Za(),Js(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o(Rt(r?"dark":"light"))},[r]);const c=u=>{t(u),sh(u)},l=[...eh,{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(u=>{const m=e===u.id,d=r?u.preview.dark:u.preview.light,h=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:d.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.userBubble,color:h},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[m&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&s.jsx(nh,{dark:r,onColorsChange:u=>o(u)})]})}const eo="adhdev_mobileDashboardMode_v1",ya="adhdev:mobile-dashboard-mode-change";function to(){try{return localStorage.getItem(eo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function oh(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??to())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==eo||t()};return window.addEventListener(ya,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ya,r),window.removeEventListener("storage",n)}}function ih(e){try{localStorage.setItem(eo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ya,{detail:e}))}function ch(){const[e,t]=i.useState(!0);return i.useEffect(()=>{t(to()==="chat")},[]),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ht,{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),ih(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const An=new Map,Jo=new Map;function lh(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 dh(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 tl(){const{sendCommand:e}=vt(),{injectEntries:t,getIdes:r}=er();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??af,c=Jo.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<o)return;const l=An.get(n);if(l)return l;const u=(async()=>{const m=await e(n,"get_machine_runtime_stats"),d=lh(m);if(!d)return;const h=r().find(v=>v.id===n),f=dh(h,n,d.machine,d.timestamp||Date.now());t([f]),Jo.set(n,Date.now())})().finally(()=>{An.delete(n)});return An.set(n,u),u},[r,t,e])}function uh(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 mh(e,t){const{sendData:r}=vt(),{injectEntries:n,getIdes:a}=er(),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(u=>qt.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const h=a().find(v=>v.id===u),f=uh(h,u,d);n([f])}));return()=>{l.forEach(u=>u())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function fh(e,t){const{sendData:r}=vt(),[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 u=qt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},m=>{l&&(clearTimeout(l),l=null),a(m.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},df):c(!1),()=>{l&&clearTimeout(l),u()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:o,applyDiagnostics:a}}function ph(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function sl(e){const{sendData:t}=vt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=ph(e);if(!a||!e.sessionId||!t){n({});return}const o=qt.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),Ss.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 rl="adhdev_hiddenTabs";function hh(){try{const e=localStorage.getItem(rl);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function xs(e){try{localStorage.setItem(rl,JSON.stringify([...e]))}catch{}}function Ln(e){return Wa(e)}function so(e,t){return js(t).some(r=>e.has(r))}function xh(){const[e,t]=i.useState(hh),r=i.useCallback(m=>{const d=Ln(m);t(h=>{const f=new Set(h);return f.has(d)?f.delete(d):f.add(d),xs(f),f})},[]),n=i.useCallback(m=>{const d=Ln(m);t(h=>{if(h.has(d))return h;const f=new Set(h);return f.add(d),xs(f),f})},[]),a=i.useCallback(m=>{const d=Ln(m);t(h=>{if(!h.has(d))return h;const f=new Set(h);return f.delete(d),xs(f),f})},[]),o=i.useCallback(()=>{t(m=>{if(m.size===0)return m;const d=new Set;return xs(d),d})},[]),c=i.useCallback((m,d)=>{t(h=>{const f=new Set(h);for(const v of d)f.add(v);return xs(f),f})},[]),l=i.useCallback((m,d)=>{t(h=>{const f=new Set(h);for(const v of d)f.delete(v);return xs(f),f})},[]),u=i.useCallback(m=>so(e,m),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:o,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function nl(e){return e instanceof Error?e.message:String(e||"")}function al(e){const t=nl(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 ol(e){const t=nl(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function il({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Ze(e)||qe(e))return;const o=_s(e);if(o===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(hs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:$t(e),mode:t})}catch(l){const u=ol(l);c&&!u&&a(m=>{const d={...m};return o===cl(r,c)?delete d[c]:d[c]=o,d}),al(l)?console.warn(u?"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 Qo(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 bh(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=Qo(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>Qo(u,t)):a.childSessions,l=c!==a.childSessions;return o!==a||l?(r=!0,{...o,...l?{childSessions:c}:{}}):a});return r?n:e}function cl(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 gh(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))cl(t,a)===o&&(delete n[a],r=!0);return r?n:e}function yh({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{oc()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:Dc(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return um(a),i.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),m={};for(const[d,h]of Object.entries(l))u-h<5e3&&(m[d]=h);return Object.keys(m).length===Object.keys(l).length?l:m})},5500);return()=>clearTimeout(c)},[t,r]),i.useEffect(()=>{const o=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(m=>m.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(o)},[n]),null}function vh(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 Rn(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 wh(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 Zo(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?wh(Bt(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 kh(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||""),Zo(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||""),Zo(r.activeChat)].join(":"))].join("|")}function jh(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 Sh(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of js({routeId:n.routeId}))r.set(o,a);for(const o of js({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of js({tabKey:n.tabKey}))r.set(o,n)}return r}function Nh(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Ch(e){const t=Nh(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=Bt(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Th({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>vh(e),[e]),o=i.useMemo(()=>Hc(e),[e]),c=i.useRef([]),l=i.useRef([]),u=i.useRef([]),m=i.useRef(new Map),d=i.useRef(new Map),h=i.useMemo(()=>{const R=new Map,g=[];for(const k of a){const{connectionState:W="new",machineName:L}=Fc(k,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),M=kh(k),E=m.current.get(k.id);if(E&&E.ide===k&&E.sourceSignature===M&&E.connectionState===W&&E.machineName===L){R.set(k.id,E),g.push(...E.conversations);continue}const U=Ja(k,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),K={ide:k,sourceSignature:M,connectionState:W,machineName:L,conversations:U};R.set(k.id,K),g.push(...U)}m.current=R;const I=new Map,C=k=>{const W=Ch(k),L=d.current.get(k.tabKey);if(L&&L.signature===W)return I.set(k.tabKey,L),L.timestamp;const M={signature:W,timestamp:vc(k)||(L==null?void 0:L.timestamp)||0};return I.set(k.tabKey,M),M.timestamp},S=[...g].sort((k,W)=>wc(k,W,C));return d.current=I,S},[a,t,o]),f=i.useMemo(()=>{const R=jh(h,r);return Rn(c.current,R)?c.current:(c.current=R,R)},[h,r]),v=i.useMemo(()=>{const R=new Map,g=Array.from(new Set(f.map(I=>I.routeId)));for(const I of g){const C=_t(f,I);C&&R.set(I,C)}return R},[f]),j=i.useMemo(()=>{const R=new Map;for(const g of f){const I=v.get(g.routeId),C=g.streamSource==="native"&&I?I:g;for(const S of js({providerSessionId:g.providerSessionId,sessionId:g.sessionId}))R.set(S,C)}return R},[f,v]),p=i.useMemo(()=>Sh(f,v),[f,v]),y=i.useCallback(R=>{if(R)return j.get(R)},[j]),x=i.useCallback(R=>{if(R)return p.get(R)},[p]),b=i.useMemo(()=>{const R=f.filter(g=>!so(n,g));return Rn(l.current,R)?l.current:(l.current=R,R)},[f,n]),w=i.useMemo(()=>{const R=b.map(g=>g.tabKey);return Rn(u.current,R)?u.current:(u.current=R,R)},[b]);return{chatIdes:a,conversations:f,visibleConversations:b,visibleTabKeys:w,resolveConversationBySessionId:y,resolveConversationByTarget:x}}function Mh({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 u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:c}}function Ih({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){i.useEffect(()=>{et.setIdes(e)},[e]),i.useEffect(()=>{et.setResolveAction((a,o,c)=>{t(a,o,c).catch(()=>{})})},[t]),i.useEffect(()=>{const a=et.onToast(o=>{r(l=>l.some(m=>m.message===o.message&&o.timestamp-m.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(u=>u.id!==o.id)),c)});return()=>{a()}},[r]),i.useEffect(()=>{const a=Rc.on("status_event",o=>{et.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=c=>{var p;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 u=l.targetSessionId||l.targetKey||l.daemonId,m=n(u),d=(m==null?void 0:m.routeId)||l.daemonId;if(!d)return;const h=Number(l.buttonIndex),f=l.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[h])||"Approve",v=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),j=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(v);t(d,"resolve_action",{action:j?"approve":"reject",button:f,...Number.isFinite(h)&&{buttonIndex:h},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};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 Ah="adhdev_dashboardLayout_v1",Lh="adhdev_dashboardDockview_v1",Rh="adhdev_dashboardDockviewHiddenRestore_v1",Ws={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function ro(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function _h(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function ll(e){return`${Ah}:${e}`}function Ph(e){const t=ll(e);return ro(t,null)}function Dh(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=ll(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function dl(e){return`${Lh}:${e}`}function Eh(e){const t=dl(e);return ro(t,null)}function $h(e,t){try{const r=dl(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function ul(e){return`${Rh}:${e}`}function Bh(e){const t=ul(e);return ro(t,{})}function Kh(e,t){try{const r=ul(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Oh(){return{groupAssignments:[...Ws.groupAssignments],focusedGroup:Ws.focusedGroup,groupActiveTabIds:{...Ws.groupActiveTabIds},groupTabOrders:{...Ws.groupTabOrders},groupSizes:[...Ws.groupSizes]}}function Wh(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Hh(){const[e]=i.useState(()=>_h(typeof window<"u"?window.innerWidth:1280)),[t,r]=i.useState(()=>new Map),[n,a]=i.useState(0),[o,c]=i.useState({}),[l,u]=i.useState({}),[m,d]=i.useState([]),[h,f]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[v,j]=i.useState(!1),p=i.useCallback(()=>{if(v)return;const k=Ph(e)??Oh();r(new Map(k.groupAssignments)),a(k.focusedGroup),c(k.groupActiveTabIds),u(k.groupTabOrders),d(k.groupSizes),j(!0)},[v,e]);i.useEffect(()=>{v&&Dh(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:l,groupSizes:m})},[v,e,t,n,o,l,m]),i.useEffect(()=>{const k=window.matchMedia("(max-width: 767px)"),W=L=>f(L.matches);return k.addEventListener("change",W),()=>k.removeEventListener("change",W)},[]);const y=i.useCallback(k=>{r(k)},[]),x=i.useCallback(k=>{a(k)},[]),b=i.useCallback(k=>{c(k)},[]),w=i.useCallback(k=>{u(k)},[]),R=i.useCallback(k=>{d(k)},[]),g=i.useCallback(k=>{x(k)},[x]),I=i.useCallback((k,W)=>{c(L=>(L[k]??null)===(W??null)?L:{...L,[k]:W})},[]),C=i.useCallback((k,W)=>{u(L=>{const M=L[k];return Wh(M,W)?L:{...L,[k]:W}})},[]),S=i.useCallback((k,W)=>{const L=W.get(k)??0;return I(L,k),g(L),L},[g,I]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:y,focusedGroup:n,updateFocusedGroup:x,focusGroup:g,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:I,groupTabOrders:l,updateGroupTabOrders:w,setGroupTabOrder:C,groupSizes:m,updateGroupSizes:R,isMobile:h,hasHydratedStoredLayout:v,hydrateStoredLayout:p,focusConversationTab:S}}function Fh(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Oa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Uh({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:c,setSearchParams:l,historyModalOpen:u,activeConv:m,isRefreshingHistory:d,ides:h,handleRefreshHistory:f}){const v=i.useRef(!1),j=i.useRef(!1),p=i.useRef(null),y=i.useRef(!1);i.useEffect(()=>{if(!e||v.current||t.length===0)return;if(!a){o();return}const x=r(e);x&&(c(x.tabKey,n),v.current=!0,j.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(b=>{const w=new URLSearchParams(b);return w.delete("activeTab"),w},{replace:!0}))},[e,t,r,n,a,o,c,l]),i.useEffect(()=>{if(!(j.current||a)&&t.length!==0){if(!e){o(),j.current=!0;return}if(v.current){j.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(j.current||a)&&(o(),j.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,o]),i.useEffect(()=>{if(!u){y.current=!1;return}if(!m||y.current||d)return;const x=h.find(b=>b.id===m.routeId);x&&(!x.chats||x.chats.length===0||Fh(x.chats,m))&&(y.current=!0,f())},[u,m,d,h,f])}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=Oa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function ml({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[c,l]=i.useState(!1),[u,m]=i.useState(!1),d=i.useCallback(async j=>{try{await e("standalone","launch_ide",{ideType:j,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=i.useCallback(async(j,p)=>{try{const y=j||(t==null?void 0:t.daemonId)||"",x=await e(y,"switch_chat",{id:p,sessionId:p,...es(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"?Bs(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Bs(a,`⚠️ Switch error: ${b}`):Bs(a,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),Bs(a,`❌ Switch failed: ${y.message||"connection error"}`)}},[t,e,a]),f=i.useCallback(async()=>{if(!(!t||c)){l(!0);try{const j=Ts(t);await e(j,"new_chat",{...es(t)}),o(p=>({...p,[t.tabKey]:Date.now()}))}catch(j){console.error("New chat failed",j)}finally{l(!1)}}},[t,c,e,o]),v=i.useCallback(async()=>{var j,p;if(!(!t||u)){m(!0);try{const y=Ts(t),x=async()=>e(y,"list_chats",{forceExpand:!0,...es(t)});let b=await x(),w=(b==null?void 0:b.chats)||((j=b==null?void 0:b.result)==null?void 0:j.chats);_n(w,t)&&(await new Promise(R=>setTimeout(R,450)),b=await x(),w=(b==null?void 0:b.chats)||((p=b==null?void 0:b.result)==null?void 0:p.chats)),b!=null&&b.success&&Array.isArray(w)&&(n(t.routeId,w),_n(w,t)&&!_n(r,t)&&Bs(a,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{m(!1)}}},[t,r,u,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:h,handleNewChat:f,handleRefreshHistory:v}}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 Vh(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function ei(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 jr(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 u=a[l];typeof u=="number"&&u>0&&o.set(c,u)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function ti(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 Gh(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 qh(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 si(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 ri(e){return Array(e).fill(100/e)}function Yh({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:m}){const d=i.useRef(null),h=i.useMemo(()=>jr(e,m),[e,m]),f=h.assignments,v=i.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),j=v>1,p=i.useCallback((g,I)=>{t(C=>{const S=new Map(jr(C,m).assignments);return I===0?S.delete(g):S.set(g,I),S}),n(C=>({...C,[I]:g})),r(I)},[t,m,n,r]),y=i.useCallback(g=>{t(I=>{const C=jr(I,m).assignments,S=new Map;for(const[k,W]of C)W!==g&&(W>g?S.set(k,W-1):S.set(k,W));return S}),c(I=>{if(I.length<=1)return[];const C=[...I];C.splice(g,1);const S=C.reduce((k,W)=>k+W,0);return S>0?C.map(k=>k/S*100):[]}),r(0)},[t,m,c,r]),x=i.useCallback((g,I)=>{I.preventDefault();const C=d.current;if(!C)return;const S=I.clientX,k=C.offsetWidth,W=o.length===v?[...o]:ri(v),L=E=>{const K=(E.clientX-S)/k*100,N=[...W];N[g]=Math.max(15,W[g]+K),N[g+1]=Math.max(15,W[g+1]-K),c(N)},M=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",M),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",M)},[o,v,c]),b=i.useCallback((g,I,C)=>{if(v>=4)return;const S=C==="left"?I:I+1;t(k=>{const W=jr(k,m).assignments,L=new Map;for(const M of u){const E=W.get(M.tabKey)??0,U=E>=S?E+1:E;U>0&&L.set(M.tabKey,U)}return S>0&&L.set(g,S),L}),c(k=>{const W=k.length===v?[...k]:ri(v),L=W[I]??100/v,M=Math.max(15,L/2),E=Math.max(15,L/2),U=[...W];U[I]=M,U.splice(S,0,E);const K=U.reduce((N,A)=>N+A,0);return U.map(N=>N/K*100)}),n(k=>{const W=si(k,S);return W[S]=g,W}),a(k=>{const W=si(k,S);return W[S]=[g],W}),r(S)},[v,t,m,u,c,n,a,r]);i.useEffect(()=>{zh(e,f)||t(f)},[e,f,t]),i.useEffect(()=>{const{mapping:g,usedGroups:I}=h;n(C=>{const S=ti(C,g);return ei(C,S)?C:S}),a(C=>{const S=ti(C,g);return ei(C,S)?C:S}),r(C=>{const S=l?0:Gh(C,I,g);return C===S?C:S}),c(C=>{const S=l?[]:qh(C,I,h.groupCount);return Vh(C,S)?C:S})},[h,l,n,a,r,c]);const w=i.useMemo(()=>{const g=Array.from({length:v},()=>[]);for(const I of u){const C=f.get(I.tabKey)??0,S=Math.min(C,v-1);g[S].push(I)}return g},[u,f,v]),R=i.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:d,normalizedGroupAssignments:f,numGroups:v,isSplitMode:j,groupedConvs:w,moveTabToGroup:p,closeGroup:y,handleResizeStart:x,splitTabRelative:b,clearAllSplits:R}}function Xh({ides:e,sendDaemonCommand:t}){const r="0.9.56",n=i.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:Jc(d,r)).sort((d,h)=>Number(Xs(h,r))-Number(Xs(d,r))),[r,e]),a=i.useMemo(()=>n.some(d=>Xs(d,r)),[r,n]),[o,c]=i.useState(!1),[l,u]=i.useState({}),m=i.useCallback(async d=>{var h,f;u(v=>({...v,[d]:"upgrading"}));try{const v=await t(d,"daemon_upgrade",{});(h=v==null?void 0:v.result)!=null&&h.upgraded||(f=v==null?void 0:v.result)!=null&&f.success?u(j=>({...j,[d]:"done"})):u(j=>({...j,[d]:"error"}))}catch{u(v=>({...v,[d]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:o,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:m}}const fl=80;function Dr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function Jh(e){return{...e,createdAt:Dr(e.createdAt),updatedAt:Dr(e.updatedAt,e.createdAt),lastEventAt:Dr(e.lastEventAt,e.updatedAt||e.createdAt)}}function Qh(e){const t=Wa(e);return t==="unknown:"?e.id:t}function Zh(e){return[e.type,yc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function ex(e,t=fl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Qh(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 tx(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=nn(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const u=Dr(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=Zh({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(Jh({id:m,dedupKey:m,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:uc(a),preview:Em(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return ex(n)}function sx(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function rx(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=fl}=e,a=i.useMemo(()=>tx(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=i.useMemo(()=>sx(a),[a]);return{notifications:a,unreadCount:o}}function nx({notifications:e,sendDaemonCommand:t}){const r=i.useCallback(o=>{const c=e.find(u=>u.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 dn(...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 ax(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 un(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=ax(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 ox(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 ix(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function mn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=ix(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=(m,d)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${d}`:m==="/"||m==="\\"?`${c}${d}`:`${m.replace(/[\\/]+$/,"")}${c}${d}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:typeof(m==null?void 0:m.path)=="string"&&m.path.trim()?m.path:l(o,m.name)})).sort((m,d)=>m.name.localeCompare(d.name)):[];return{path:o,directories:u}}function cx(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ni(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function lx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function dx({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=ni(n.workspacePath),l=e.find(m=>{var j,p,y,x;if(!m||m.type==="adhdev-daemon"||cx(m.daemonId||m.id)!==n.machineId||(rr(m)?"cli":ws(m)?"acp":"ide")!==n.kind||String(m.agentType||m.type||"")!==n.providerType)return!1;if(n.resumeSessionId)return String(m.providerSessionId||"")===n.resumeSessionId;if(c){const b=ni(m.workspace||m.runtimeWorkspaceLabel);return b?b===c:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((x=(y=(p=(j=m.activeChat)==null?void 0:j.messages)==null?void 0:p.at)==null?void 0:y.call(p,-1))==null?void 0:x.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const u=kc({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});u&&(a(null),r(u))},[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 ux({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const c=i.useCallback(async(f,v)=>mn(e,f,v),[e]),l=i.useCallback(async(f,v)=>{if(!v.trim())return{ok:!1,error:"Choose a workspace path first."};try{const j=await e(f,"workspace_add",{path:v.trim()});return j!=null&&j.success?{ok:!0}:{ok:!1,error:(j==null?void 0:j.error)||"Could not save workspace"}}catch(j){return{ok:!1,error:j instanceof Error?j.message:"Could not save workspace"}}},[e]),u=i.useCallback(async(f,v,j)=>{var p;try{const y={ideType:v,enableCdp:!0};(p=j==null?void 0:j.workspacePath)!=null&&p.trim()&&(y.workspace=j.workspacePath.trim());const x=await e(f,"launch_ide",y);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:f,kind:"ide",providerType:v,workspacePath:(j==null?void 0:j.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(y){return{ok:!1,error:y instanceof Error?y.message:"Could not launch IDE"}}},[e,t]),m=i.useCallback(async(f,v,j,p)=>{var x,b,w;const y=Date.now();try{const R={cliType:j};(x=p==null?void 0:p.workspacePath)!=null&&x.trim()?R.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(R.workspaceId=p.workspaceId),(b=p==null?void 0:p.resumeSessionId)!=null&&b.trim()&&(R.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(R.cliArgs=p.cliArgs),(w=p==null?void 0:p.initialModel)!=null&&w.trim()&&(R.initialModel=p.initialModel.trim());const g=await e(f,"launch_cli",R),I=(g==null?void 0:g.result)||g,C=(I==null?void 0:I.sessionId)||(I==null?void 0:I.id);return g!=null&&g.success&&C?(r(C),{ok:!0}):g!=null&&g.success?(t({machineId:f,kind:v,providerType:j,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:y}),{ok:!0}):{ok:!1,error:(g==null?void 0:g.error)||(I==null?void 0:I.error)||`Could not launch ${v.toUpperCase()} session`}}catch(R){return lx(R)?(t({machineId:f,kind:v,providerType:j,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:y}),{ok:!0}):{ok:!1,error:R instanceof Error?R.message:`Could not launch ${v.toUpperCase()} session`}}},[r,e,t]),d=i.useCallback(async(f,v)=>{if(!f||!v)return[];try{const j=await e(f,"list_saved_sessions",{providerType:v,kind:"cli",limit:30}),p=(j==null?void 0:j.result)??j;return Array.isArray(p==null?void 0:p.sessions)?p.sessions:[]}catch(j){return console.error("List saved sessions failed",j),[]}},[e]),h=i.useCallback(async f=>{await il({conversation:n,mode:f,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineSavedSessions:d,setActiveCliViewMode:h}}function mx(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 fx(e,t,r=Date.now()){return!e||!mx(t)?null:{tabKey:e,nonce:r}}function px({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:c}){const[l,u]=i.useState(null),[m,d]=i.useState(null),h=i.useMemo(()=>{var y,x;if(!e){if(l){const b=t.find(w=>w.tabKey===l);if(b)return b}return r[0]}const p=n[a];if(p){const b=t.find(w=>w.tabKey===p);if(b)return b}return((y=o[a])==null?void 0:y[0])||((x=o[0])==null?void 0:x[0])},[t,l,a,n,o,e,r]),f=i.useCallback(p=>{u(p)},[]),v=i.useCallback(p=>{u(p.tabKey),c(y=>{const x=new URLSearchParams(y),b=Bm(p);return b?x.set("activeTab",b):x.delete("activeTab"),x},{replace:!0})},[c]),j=i.useCallback((p,y)=>{const x=fx(p,y);x&&d(x)},[]);return{activeConv:h,openDesktopConversation:v,requestScrollToBottom:j,scrollToBottomRequest:m,setDesktopActiveTab:f}}function hx(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 xx(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 bx({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),u=i.useRef(null);i.useEffect(()=>{const m=()=>{c.current&&(clearTimeout(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null),o.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const d=Ur(e,r),h=xx({tabKey:e.tabKey,historySessionId:cr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:ts(e),liveState:d}),f=h.autoReadKey,v=hx({autoReadKey:f,shouldMarkSeen:h.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!h.shouldMarkSeen){v.shouldCancelPending&&m(),a.current=f;return}if(!v.shouldSchedule)return;v.shouldCancelPending&&m();const j=()=>{if(document.visibilityState!=="visible"||a.current===f)return;a.current=f,o.current=null,c.current=null,l.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null);const y=h.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:y,completionMarker:h.completionMarker}).catch(()=>{})};if(o.current=v.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(j,1500);const y=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};u.current=y,document.addEventListener("visibilitychange",y);return}const p=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(j,800),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null))};u.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),i.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function ai(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 gx({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:c,setClearedTabs:l,setSearchParams:u}){var N;const[m,d]=i.useState(!1),[h,f]=i.useState([]),[v,j]=i.useState(()=>ht()),[p,y]=i.useState(!1),[x,b]=i.useState(null),w=i.useRef(null),R=i.useMemo(()=>r||t||e,[e,r,t]),g=!!R&&Ze(R)&&!qe(R),I=i.useMemo(()=>{if(!R||!g)return null;const A=R.daemonId||R.routeId||"",z=$t(R),$=ai(R);return`${A}:${z}:${R.providerSessionId||""}:${$}`},[R,g]),{isCreatingChat:C,isRefreshingHistory:S,handleSwitchSession:k,handleNewChat:W,handleRefreshHistory:L}=ml({sendDaemonCommand:a,activeConv:R,chats:(N=n.find(A=>A.id===(R==null?void 0:R.routeId)))==null?void 0:N.chats,updateRouteChats:o,setToasts:c,setClearedTabs:l}),M=i.useCallback(()=>{d(!0)},[]),E=i.useCallback(()=>{d(!1)},[]),U=i.useCallback(async()=>{if(!(!R||!g||p)){y(!0);try{const A=R.daemonId||R.routeId,z=$t(R),$=ai(R),B=await a(A,"list_saved_sessions",{agentType:z,providerType:z,kind:"cli",limit:50,...R.providerSessionId?{providerSessionId:R.providerSessionId}:{},...$?{workspace:$}:{}}),G=(B==null?void 0:B.result)??B;f(Array.isArray(G==null?void 0:G.sessions)?G.sessions:[])}catch(A){console.error("Refresh saved sessions failed",A),f([])}finally{y(!1)}}},[R,p,g,a]);i.useEffect(()=>{if(!m){w.current=null;return}if(!g){w.current=null,f([]),y(!1);return}!I||p||w.current!==I&&(w.current=I,U())},[U,m,p,g,I]);const K=i.useCallback(async A=>{if(!R||!g||!A.providerSessionId||!A.workspace)return;const z=R.daemonId||R.routeId,$=$t(R);try{b(A.providerSessionId);const B=await a(z,"launch_cli",{cliType:$,dir:A.workspace,resumeSessionId:A.providerSessionId,initialModel:nc(A.summaryMetadata,"model",{preferShortValue:!0})||void 0}),G=(B==null?void 0:B.result)??B,V=typeof(G==null?void 0:G.sessionId)=="string"?G.sessionId:typeof(G==null?void 0:G.id)=="string"?G.id:"";V&&u(me=>{const ae=new URLSearchParams(me);return ae.set("activeTab",V),ae},{replace:!0}),E()}catch(B){console.error("Resume saved session failed",B)}finally{b(null)}},[E,R,g,a,u]);return{historyModalOpen:m,openHistoryModal:M,closeHistoryModal:E,historyTargetConv:R,isSavedSessionHistoryTarget:g,isHistoryCreatingChat:C,isHistoryRefreshingHistory:S,handleHistorySwitchSession:k,handleHistoryNewChat:W,handleHistoryRefresh:L,savedHistorySessions:h,savedHistoryFilters:v,setSavedHistoryFilters:j,isSavedHistoryLoading:p,resumingSavedHistorySessionId:x,handleRefreshSavedHistory:U,handleResumeSavedHistorySession:K}}function yx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}){const[u,m]=i.useState(null),[d,h]=i.useState(null),f=i.useMemo(()=>{if(e||!n)return null;const x=l(n);return x&&!Ze(x)&&!qe(x)?x:null},[e,n,l]),v=i.useMemo(()=>{const x=u==null?void 0:u.routeId;if(!x)return null;const b=u!=null&&u.tabKey?o.find(w=>w.tabKey===u.tabKey):a?o.find(w=>w.tabKey===a):null;return(b==null?void 0:b.routeId)===x?b:_t(o,x)},[o,u,a]),j=i.useMemo(()=>{if(v)return c.find(x=>x.id===v.routeId)},[c,v]);i.useEffect(()=>{f&&(m({routeId:f.routeId,tabKey:Lo(f)}),h(f),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,f]);const p=i.useCallback(x=>{x&&(m({routeId:x.routeId,tabKey:Lo(x)}),h(x))},[]),y=i.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:v,remoteDialogIdeEntry:j,remoteDialogActiveConv:d,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:y}}function vx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l,activeConv:u,sendDaemonCommand:m}){const{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:v,openRemoteDialog:j,closeRemoteDialog:p}=yx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}),[y,x]=i.useState(!1),[b,w]=i.useState(null),R=i.useCallback(async C=>{const S=C||u;!S||!Ze(S)&&!qe(S)||(w(S),x(!0))},[u]),g=i.useCallback(()=>{x(!1),w(null)},[]),I=i.useCallback(async C=>{const S=b||u;if(!S||!Ze(S)&&!qe(S)){g();return}x(!1);try{const k=$t(S),W=S.routeId||S.daemonId||"";await m(W,"stop_cli",{cliType:k,targetSessionId:S.sessionId,mode:C})}catch(k){console.error("Stop CLI failed:",k)}finally{w(null)}},[u,g,b,m]);return{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:v,openRemoteDialog:j,closeRemoteDialog:p,cliStopDialogOpen:y,cliStopTargetConv:b,requestCliStop:R,cancelCliStop:g,confirmCliStop:I}}function Pn(e,t=!0){return(e??!0)&&t}const no=i.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d=null,handleFocusAgent:h,isFocusingAgent:f,actionLogs:v,userName:j,scrollToBottomRequestNonce:p,isInputActive:y=!0,isVisible:x=!0}){const b=n,w=!n,R=Pn(x,b),g=Pn(x,w),I=Pn(x),C=sl(t),S=C.status||C.modalMessage||C.modalButtons?{...t,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(ec,{activeConv:S,onModalButton:c}),S.transport!=="pty"&&S.transport!=="acp"&&S.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(tr,{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,S.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(np,{activeConv:S,clearToken:r,terminalRef:o,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,isVisible:R,isInputActive:y&&R})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:w?"visible":"hidden",pointerEvents:w?"auto":"none"},children:s.jsx(ha,{activeConv:S,ideEntry:a,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:f,actionLogs:v,userName:j,scrollToBottomRequestNonce:p,isInputActive:y&&g,isVisible:g})})]}):s.jsx(ha,{activeConv:S,ideEntry:a,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:f,actionLogs:v,userName:j,scrollToBottomRequestNonce:p,isInputActive:y&&I,isVisible:I})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.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 wx({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:m,onOpenNativeConversation:d,onOpenMachine:h,onOpenHistory:f,onOpenRemote:v,onHideConversation:j,onStopCli:p,cliViewMode:y,onSetCliViewMode:x,handleSendChat:b,handleFocusAgent:w,handleModalButton:R,handleRelaunch:g}){const I=i.useRef(null),C=Ze(e)&&!t,S=C&&y==="terminal",k=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 ${k} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(Ta,{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(jc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>h(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[C&&y&&s.jsx(za,{mode:y,onChange:x,compact:!0}),C&&p&&s.jsx("button",{onClick:()=>{p(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(wt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Ma,{size:14})}),!t&&!C&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),type:"button",children:s.jsx(Nt,{size:14})}),j&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>j(e),type:"button",title:"Close chat",children:s.jsx(wt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(no,{activeConv:e,clearToken:0,isCliTerminal:S,ideEntry:n,terminalRef:I,handleModalButton:R,handleRelaunch:g,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:w,isFocusingAgent:u,actionLogs:a,userName:o})})]})}const Dn={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 kx(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function pl(){const[e,t]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),c=e==="unix"?"unix":r;i.useEffect(()=>{t(kx())},[]);const l=i.useCallback(()=>{navigator.clipboard.writeText(Dn[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:Dn[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Dn[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 hl({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Nt},{key:"chats",label:"Chats",icon:Ht}];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 Sr({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 bs({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 Hs({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 Nr({item:e,type:t,getAvatarText:r,onOpenConversation:n,onCollectChatDebugBundle:a}){const o=t==="needs_attention"||t==="task_complete",c=t==="working",l=t==="earlier",u=t==="task_complete",{isReconnecting:m,isConnecting:d}=Rs(e.conversation),h=it(e.conversation),f=ms(e.conversation),v=Pc(e.conversation,{requiresAction:t==="needs_attention"}),j=o?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":l?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",p=o?"bg-accent-primary shadow-glow":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":l?"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",y=l?"text-text-secondary":"text-text-primary",x=l?"text-text-muted":"text-text-secondary",b=l?"text-text-secondary opacity-80":"text-text-muted",w=l?"text-text-muted opacity-80":"text-text-muted",R=!c&&!u,g="text-[color:var(--status-warning)]",I=C=>{if(!a)return;C.preventDefault(),C.stopPropagation();const S=a==null?void 0:a(e.conversation);Promise.resolve(S).catch(k=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",k)})};return s.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${j}`,onClick:()=>n(e.conversation),onContextMenu:I,type:"button",children:[o||c?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 ${p}`,style:o?{color:"var(--accent-on-primary)"}:void 0,children:r(h)}),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 ${y}`,children:h}),R&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${w}`,children:Zi(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${x}`,children:[s.jsx("span",{className:"truncate",children:f}),s.jsx(ln,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),m?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${g} animate-pulse`,children:"Reconnecting…"})]}):d?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):v==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:g,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${b}`,children:e.preview})]}),o&&!u&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),u&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),c&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]},e.conversation.tabKey)}function oi({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 jx({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:c,getAvatarText:l,actionLogs:u,sendDaemonCommand:m,onOpenConversation:d,onShowConversation:h,onShowAllHidden:f,onOpenNewSession:v,onOpenMachine:j,onOpenSettings:p,onSectionChange:y,wsStatus:x="connected",isStandalone:b=!1,onCollectChatDebugBundle:w}){const R=x==="disconnected"||x==="reconnecting"||x==="offline"||x==="auth_failed",g=c.length>0,I=t.length>0||r.length>0||n.length>0||a.length>0,C=e==="machines"?"Machines":"Chats",S=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",k=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",W=i.useCallback(async E=>{var G;const U=Ts(E);if(!U)return;const K=Array.isArray(E.messages)?E.messages:[],N=xc({activeConv:E,visibleMessages:K,actionLogs:u,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:K.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),A=await m(U,"get_chat_debug_bundle",{...es(E),delivery:"daemon_file",frontendSnapshot:N}),z=Gr(A),$=gc(z);let B=!1;if((G=navigator.clipboard)!=null&&G.writeText&&window.isSecureContext)try{await navigator.clipboard.writeText($),B=!0}catch(V){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",V)}if(!B){let V=null;try{V=document.createElement("textarea"),V.value=$,V.setAttribute("readonly","true"),V.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(V),V.focus(),V.select(),B=document.execCommand("copy")}catch{}finally{V==null||V.remove()}}B||console.warn("[chat-debug-bundle] failed to copy mobile inbox debug bundle locator to clipboard"),et.showToast(bc(z,{locatorCopied:B}),B?"success":"warning")},[u,m]),L=w||W,M=i.useCallback((E,U)=>{E.preventDefault(),E.stopPropagation(),Promise.resolve(L(U)).catch(K=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",K),et.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[L]);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 ${S}`,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:C}),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(sn,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:p,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(tn,{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] ${k}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:R?s.jsx(Hs,{icon:s.jsx(oi,{}),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(Hs,{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(pl,{})})}):s.jsx(bs,{children:c.map((E,U)=>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] ${U>0?"border-t border-border-subtle/70":""}`,onClick:()=>j(E.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(E.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:E.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:E.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[E.unread," new"]}):E.total>0?`${E.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:E.subtitle}),E.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[E.total," chat",E.total!==1?"s":"",E.unread>0?` · ${E.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},E.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(Sr,{title:"Needs attention",className:"mb-0"}),s.jsx(bs,{children:t.map((E,U)=>s.jsx("div",{className:U>0?"border-t border-border-subtle/70":"",children:s.jsx(Nr,{item:E,type:"needs_attention",getAvatarText:l,onOpenConversation:d,onCollectChatDebugBundle:L})},E.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(Sr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(bs,{children:r.map((E,U)=>s.jsx("div",{className:U>0?"border-t border-border-subtle/70":"",children:s.jsx(Nr,{item:E,type:"task_complete",getAvatarText:l,onOpenConversation:d,onCollectChatDebugBundle:L})},E.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(Sr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(bs,{children:n.map((E,U)=>s.jsx("div",{className:U>0?"border-t border-border-subtle/70":"",children:s.jsx(Nr,{item:E,type:"working",getAvatarText:l,onOpenConversation:d,onCollectChatDebugBundle:L})},E.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(Sr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(bs,{children:a.map((E,U)=>s.jsx("div",{className:U>0?"border-t border-border-subtle/70":"",children:s.jsx(Nr,{item:E,type:"earlier",getAvatarText:l,onOpenConversation:d,onCollectChatDebugBundle:L})},E.conversation.tabKey))}):I?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):R?s.jsx(Hs,{icon:s.jsx(oi,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):g?s.jsx(Hs,{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(Ht,{size:20})}),title:"No conversations yet",subtitle:$c,children:v&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:v,"aria-label":Dt,title:Dt,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:Dt})]})}):s.jsx(Hs,{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.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[s.jsx("span",{children:"Hidden"}),s.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:f,children:"Restore all"})]}),s.jsx(bs,{className:"bg-bg-secondary/25",children:o.map((E,U)=>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] opacity-50 saturate-0 ${U>0?"border-t border-border-subtle/70":""}`,onClick:()=>h(E),onContextMenu:K=>M(K,E),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-bg-primary border border-border-subtle text-text-secondary",children:l(it(E))}),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:it(E)}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:ms(E)}),s.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},E.tabKey))})]})]}),e==="chats"&&v&&I&&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:v,"aria-label":Dt,title:Dt,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(hl,{section:e,onSectionChange:y})]})}function Sx(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 xl(e){const t=[e.workspace||"Workspace unknown"],r=us(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Sx(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function fn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:m}){const[d,h]=i.useState(r);i.useEffect(()=>{h(r)},[r]);const f=ox(r),v=d.trim();return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:s.jsx(wt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!f||a||u(f)},disabled:!f||a,children:[s.jsx(Ta,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:j=>h(j.target.value),onKeyDown:j=>{j.key!=="Enter"||!v||a||(j.preventDefault(),u(v))},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:()=>{!v||a||u(v)},disabled:!v||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(j=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(j.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Ns,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:j.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:j.path})]})]},j.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:()=>m(v||r),disabled:!v&&!r||a,children:c})]})]})})}function ao({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:m,argsValue:d,onArgsChange:h,showModelInput:f,modelValue:v,onModelChange:j,historyProviderNode:p,onConfirm:y,onCancel:x}){const b=n==null?void 0:n.find(w=>w.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(wt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:w=>o(w.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(w=>s.jsx("option",{value:w.key,children:w.label},w.key))}),(b==null?void 0:b.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:b.description})]}),p,r.map(w=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:w.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:w.value})]},`${w.label}:${w.value}`)),f&&j&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:v||"",onChange:w=>j(w.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),m&&h&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:d||"",onChange:w=>h(w.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:x,disabled:u,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:y,disabled:u,children:[s.jsx(Aa,{size:14}),u?l:c]})]})]})})}function ii(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function is(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,o=[];a&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])o.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${ii(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&o.push({key:`custom:${c}`,label:ii(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(o.some(m=>m.key===u))return{options:o,selectedKey:u}}return l?{options:o,selectedKey:`saved:${l.id}`}:c?{options:o,selectedKey:`custom:${c}`}:{options:o,selectedKey:"__home__"}}function Nx(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Cx(e){return[Nx(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Tx(e){return e.lastLaunchedAt?rn(e.lastLaunchedAt):""}function bl(e){return{metaText:Cx(e),updatedLabel:Tx(e)}}function En(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Mx({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var Ye,mt,pt,dt;const c=lr(),[l,u]=i.useState(!1),m=(((Ye=e.detectedIdes)==null?void 0:Ye.length)||0)>0,d=i.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),h=e.defaultWorkspaceId||null,[f,v]=i.useState(h||((mt=d[0])==null?void 0:mt.id)||""),[j,p]=i.useState(""),[y,x]=i.useState(""),[b,w]=i.useState([]),[R,g]=i.useState(!1),[I,C]=i.useState(""),[S,k]=i.useState(!1),[W,L]=i.useState(En(m,t.length,r.length)),M=i.useRef(null),[E,U]=i.useState(null),K=i.useRef("__home__"),[N,A]=i.useState("__home__"),[z,$]=i.useState(""),[B,G]=i.useState(""),[V,me]=i.useState(""),[ae,xe]=i.useState([]),[de,be]=i.useState(()=>ht().textQuery),[he,Y]=i.useState(()=>ht().workspaceQuery),[oe,J]=i.useState(()=>ht().modelQuery),[ue,le]=i.useState(()=>ht().resumableOnly),[Se,ie]=i.useState(()=>ht().sortMode),[pe,ne]=i.useState(!1),[Z,ee]=i.useState(!1),q=i.useRef(null),X=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const re=f==="__custom__"?j.trim():((pt=d.find(Te=>Te.id===f))==null?void 0:pt.path)||"",je=f==="__custom__"&&!!re&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),we=f!=="__custom__"&&((dt=d.find(Te=>Te.id===f))==null?void 0:dt.path)||"",te=i.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),D=i.useCallback(async Te=>{g(!0),C("");try{const Fe=await a(Te);x(Fe.path),p(Fe.path),w(Fe.directories)}catch(Fe){C(Fe instanceof Error?Fe.message:"Could not load folder")}finally{g(!1)}},[a]),ve=i.useCallback(()=>{var Fe;v("__custom__"),k(!0);const Te=un(e.platform,dn(j.trim(),we,te,e.defaultWorkspacePath,(Fe=d.find(Ge=>Ge.id===h))==null?void 0:Fe.path,d.map(Ge=>Ge.path)));D(Te)},[j,h,D,te,we,e.platform,d]),Ce=i.useCallback(Te=>{if(Te!=null&&Te.workspaceId){v(Te.workspaceId),p("");return}if(Te!=null&&Te.workspacePath){v("__custom__"),p(Te.workspacePath);return}v(""),p("")},[]),ke=i.useCallback(Te=>{if(v(Te),Te==="__custom__"){ve();return}p("")},[ve]),Pe=i.useCallback(Te=>{v("__custom__"),p(Te)},[]),Le=i.useCallback((Te,Fe)=>{M.current=Fe,K.current=Te.selectedWorkspaceKey||"__home__",A(Te.selectedWorkspaceKey||"__home__"),$(Te.initialArgs||""),G(Te.initialModel||""),me(""),xe([]);const Ge=Te.providerType?`${e.id}:${Te.providerType}`:null;if(hp(X.current,Ge)){const ct=ht();be(ct.textQuery),Y(ct.workspaceQuery),J(ct.modelQuery),le(ct.resumableOnly),ie(ct.sortMode)}X.current=Ge,U(Te),Te.providerType&&o&&(ne(!0),o(Te.providerType).then(ct=>xe(ct||[])).catch(ct=>console.warn("Failed to load saved sessions",ct)).finally(()=>ne(!1)))},[o,e.id]),Oe=i.useMemo(()=>Bc(ae,{textQuery:de,workspaceQuery:he,modelQuery:oe,resumableOnly:ue,sortMode:Se}),[oe,ue,ae,Se,de,he]);i.useEffect(()=>{V&&(Oe.some(Te=>Te.providerSessionId===V)||me(""))},[Oe,V]);const ze=i.useCallback(()=>{M.current&&(ee(!0),M.current().finally(()=>{M.current=null,ee(!1),U(null)}))},[]),tt=i.useCallback(()=>{M.current=null,U(null)},[]),Xe=i.useCallback(Te=>{K.current=Te,A(Te)},[]);return i.useEffect(()=>{var Te;q.current!==e.id&&(q.current=e.id,v(h||((Te=d[0])==null?void 0:Te.id)||"__custom__"),p(""),x(""),w([]),C(""),k(!1),be(ht().textQuery),Y(ht().workspaceQuery),J(ht().modelQuery),le(ht().resumableOnly),ie(ht().sortMode),X.current=null,L(En(m,t.length,r.length)))},[r.length,t.length,h,m,e.id,d]),i.useEffect(()=>{var Te;f!=="__custom__"&&(f&&d.some(Fe=>Fe.id===f)||v(h||((Te=d[0])==null?void 0:Te.id)||"__custom__"))},[h,f,d]),i.useEffect(()=>{W==="ide"&&m||W==="cli"&&t.length>0||W==="acp"&&r.length>0||L(En(m,t.length,r.length))},[W,r.length,t.length,m]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:m,workspaceRows:d,defaultWorkspaceId:h,workspaceChoice:f,customWorkspacePath:j,browseCurrentPath:y,browseDirectories:b,browseBusy:R,browseError:I,browseDialogOpen:S,activeLauncherKind:W,launchConfirm:E,launchConfirmWorkspaceKeyRef:K,launchConfirmWorkspaceKey:N,launchConfirmArgs:z,launchConfirmModel:B,launchConfirmResumeId:V,launchConfirmSavedSessions:ae,launchConfirmTextFilter:de,launchConfirmWorkspaceFilter:he,launchConfirmModelFilter:oe,launchConfirmResumableOnly:ue,launchConfirmSortMode:Se,filteredLaunchConfirmSavedSessions:Oe,launchConfirmSessionsLoading:pe,launchConfirmBusy:Z,resolvedWorkspacePath:re,canCreateMissingWorkspace:je,openBrowseDialog:ve,loadBrowsePath:D,handleWorkspaceChoiceChange:ke,chooseCustomWorkspacePath:Pe,setCustomWorkspacePath:p,setBrowseDialogOpen:k,setActiveLauncherKind:L,openLaunchConfirm:Le,handleConfirmLaunch:ze,closeLaunchConfirm:tt,setWorkspaceSelectionFromOption:Ce,setLaunchConfirmWorkspaceKeyAndSync:Xe,setLaunchConfirmArgs:$,setLaunchConfirmModel:G,setLaunchConfirmResumeId:me,setLaunchConfirmTextFilter:be,setLaunchConfirmWorkspaceFilter:Y,setLaunchConfirmModelFilter:J,setLaunchConfirmResumableOnly:le,setLaunchConfirmSortMode:ie}}function Ix({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:c,machineAction:l,isStandalone:u,section:m,showBottomNav:d,onBack:h,onSectionChange:f,onOpenConversation:v,onOpenRecent:j,onOpenMachineDetails:p,onMachineUpgrade:y,onLaunchDetectedIde:x,onAddWorkspace:b,onBrowseDirectory:w,onLaunchWorkspaceProvider:R,onListSavedSessions:g}){const I=N=>N==="ide"?"IDE":N==="cli"?"CLI":"ACP",C=r.slice(0,4),S=t.slice(0,3),k=Mx({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:w,onListSavedSessions:g}),W=i.useMemo(()=>C.map(N=>{const{metaText:A,updatedLabel:z}=bl(N);return{key:`recent-launch:${N.id}`,primary:N.label,secondary:A,updatedLabel:z,onClick:()=>{const{options:$,selectedKey:B}=is({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspacePath:N.workspace});k.openLaunchConfirm({title:N.kind==="ide"?rs("restart-ide",N.label):N.providerSessionId?qa(N.label):rs("start-fresh",N.label),description:N.kind==="ide"?ns("restart-ide"):N.providerSessionId?Ya():ns("start-fresh"),confirmLabel:N.kind==="ide"?Ms("restart-ide"):N.providerSessionId?Xr(!0):Ms("start-fresh"),busyLabel:N.kind==="ide"?Is("restart-ide"):N.providerSessionId?Va(!0):Is("start-fresh"),workspaceOptions:$,selectedWorkspaceKey:B,details:[{label:"Mode",value:I(N.kind)},...N.providerType?[{label:"Provider",value:N.providerType}]:[]]},async()=>{const G=$.find(V=>V.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption(G),await j({...N,workspace:(G==null?void 0:G.workspacePath)??null})})}}}),[k,j,C]),L=i.useMemo(()=>S.map(N=>({key:`recent-chat:${N.conversation.tabKey}`,primary:it(N.conversation),secondary:ep(N.conversation,{timestampLabel:N.timestamp?Zi(N.timestamp):null}),unread:N.unread,onClick:()=>v(N.conversation)})),[v,S]),M=k.showAllRecent?W:W.slice(0,4),E=W.length>0,U=L.length>0,K=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${K} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:s.jsx(Ta,{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:St(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:L.map(N=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${N.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:N.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:N.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))})]}),E&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:M.map(N=>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:N.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:N.primary}),N.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:N.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))}),W.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:()=>k.setShowAllRecent(N=>!N),children:k.showAllRecent?"Show fewer":`Show ${W.length-4} more`})})]}),(k.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:k.workspaceChoice,onChange:N=>k.handleWorkspaceChoiceChange(N.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:k.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[k.workspaceRows.map(N=>s.jsxs("option",{value:N.id,children:[N.id===k.defaultWorkspaceId?"⭐ ":"",an(N.path,N.label)||N.path]},N.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),k.workspaceChoice==="__custom__"&&s.jsxs("div",{className:"flex flex-col gap-2.5",children:[s.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Ns,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),s.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:k.resolvedWorkspacePath||k.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:k.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:()=>{k.resolvedWorkspacePath&&b(k.resolvedWorkspacePath)},disabled:!k.resolvedWorkspacePath||k.browseBusy,children:"Save as workspace"})]})]}),k.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[k.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.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:()=>k.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.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:()=>k.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.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:()=>k.setActiveLauncherKind("acp"),children:"ACP"})]}),k.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:k.activeLauncherKind==="ide"?"Choose an IDE":k.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:k.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(N=>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:A,selectedKey:z}=is({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspaceId:k.workspaceChoice!=="__custom__"?k.workspaceChoice:null,currentWorkspacePath:k.resolvedWorkspacePath});k.openLaunchConfirm({title:`Launch ${N.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:A,selectedWorkspaceKey:z,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:N.name}]},async()=>{const $=A.find(B=>B.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption($),x(N.type,{workspacePath:($==null?void 0:$.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:N.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath||"Use selected workspace"})]},N.type)):(k.activeLauncherKind==="cli"?n:a).map(N=>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 A=k.activeLauncherKind==="cli"?"cli":"acp",{options:z,selectedKey:$}=is({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspaceId:k.workspaceChoice!=="__custom__"?k.workspaceChoice:null,currentWorkspacePath:k.resolvedWorkspacePath});k.openLaunchConfirm({title:`Launch ${N.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${A.toUpperCase()}`,workspaceOptions:z,selectedWorkspaceKey:$,details:[{label:"Mode",value:A.toUpperCase()},{label:"Provider",value:N.displayName}],showArgsInput:!0,showModelInput:A==="acp",initialArgs:"",initialModel:"",providerType:N.type},async()=>{const B=z.find(G=>G.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption(B),R(A,N.type,{workspaceId:(B==null?void 0:B.workspaceId)??null,workspacePath:(B==null?void 0:B.workspacePath)??null,args:k.launchConfirmArgs,model:k.launchConfirmModel,resumeSessionId:k.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[N.icon?`${N.icon} `:"",N.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath||"Use selected workspace"})]},N.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,k.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(k.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:y,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:p,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),k.browseDialogOpen&&s.jsx(fn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:k.browseCurrentPath,directories:k.browseDirectories,busy:k.browseBusy,error:k.browseError,confirmLabel:"Use this folder",onClose:()=>k.setBrowseDialogOpen(!1),onNavigate:N=>{k.loadBrowsePath(N)},onConfirm:N=>{k.chooseCustomWorkspacePath(N),k.setBrowseDialogOpen(!1)}}),k.launchConfirm&&s.jsx(ao,{title:k.launchConfirm.title,description:k.launchConfirm.description,details:k.launchConfirm.details,workspaceOptions:k.launchConfirm.workspaceOptions,selectedWorkspaceKey:k.launchConfirmWorkspaceKey,onWorkspaceChange:k.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:k.launchConfirm.providerType?Xr(!!k.launchConfirmResumeId):k.launchConfirm.confirmLabel,busyLabel:k.launchConfirm.providerType?void 0:k.launchConfirm.busyLabel,busy:k.launchConfirmBusy,showArgsInput:k.launchConfirm.showArgsInput,argsValue:k.launchConfirmArgs,onArgsChange:k.setLaunchConfirmArgs,showModelInput:k.launchConfirm.showModelInput,modelValue:k.launchConfirmModel,onModelChange:k.setLaunchConfirmModel,historyProviderNode:k.launchConfirm.providerType&&(k.launchConfirmSessionsLoading||k.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"}),k.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:Ga()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:k.launchConfirmTextFilter,onChange:N=>k.setLaunchConfirmTextFilter(N.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:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:k.launchConfirmWorkspaceFilter,onChange:N=>k.setLaunchConfirmWorkspaceFilter(N.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:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:k.launchConfirmModelFilter,onChange:N=>k.setLaunchConfirmModelFilter(N.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:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),s.jsxs("select",{value:k.launchConfirmSortMode,onChange:N=>k.setLaunchConfirmSortMode(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.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:k.launchConfirmResumableOnly,onChange:N=>k.setLaunchConfirmResumableOnly(N.target.checked),disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:k.launchConfirmResumeId,onChange:N=>k.setLaunchConfirmResumeId(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:gp()}),k.filteredLaunchConfirmSavedSessions.map(N=>s.jsxs("option",{value:N.providerSessionId,disabled:!N.canResume,children:[N.title||N.providerSessionId," ",N.canResume?"":"(workspace missing)"]},N.providerSessionId))]}),!k.launchConfirmSessionsLoading&&k.launchConfirmSavedSessions.length>0&&k.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),k.launchConfirmResumeId&&(()=>{const N=k.filteredLaunchConfirmSavedSessions.find(z=>z.providerSessionId===k.launchConfirmResumeId);if(!N)return null;const A=xl(N);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:A.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:A.providerSessionId}),s.jsx("div",{className:"mt-1",children:A.metaLine}),A.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:A.updatedLabel}),A.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:A.preview})]})})()]}),onConfirm:k.handleConfirmLaunch,onCancel:k.closeLaunchConfirm}),d&&s.jsx(hl,{section:m,onSectionChange:f})]})}function Er(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Ax(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:Er(e)}function Lx(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 Rx(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:us(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,u,m,d;const a=rr(n)?"cli":ws(n)?"acp":"ide",o=us(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(rr(n)?n.cliName||n.type:ws(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:ws(n)?o||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((d=(m=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:m.call(u,-1))==null?void 0:d.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function _x(e,t){const r=new Map;for(const n of t){const a=hs(n.conversation),o=r.get(a);o?o.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],o=[...a].sort((h,f)=>f.timestamp-h.timestamp)[0]||null,c=(o==null?void 0:o.conversation)||null,l=oa(n),u=a.filter(h=>h.unread||h.requiresAction).length,m=Lx(n),d=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:St(n,{fallbackId:n.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:l,preview:c?tp(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 Px(e){return e==="chat"}function Cr(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 Dx({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:v,setSelectedTabKey:j,setScreen:p,setSelectedMachineId:y,setSection:x,setMachineBackTarget:b,resetMachineAction:w}){const R=i.useRef(null),g=i.useCallback(I=>{if(!(I!=null&&I.sessionId))return;const C=Ur(I,c),S=Math.max(Date.now(),ts(I),C.lastUpdated||0);Cr("mark_read:start",{tabKey:I.tabKey,sessionId:I.sessionId,displayPrimary:it(I),inboxBucket:C.inboxBucket,unread:C.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:ts(I),readAt:S}),l(hs(I)||I.routeId,"mark_session_seen",{sessionId:I.sessionId,providerSessionId:I.providerSessionId,seenAt:S,completionMarker:C.completionMarker}).then(k=>{Cr("mark_read:result",{tabKey:I.tabKey,sessionId:I.sessionId,result:k})}).catch(k=>{Cr("mark_read:error",{tabKey:I.tabKey,sessionId:I.sessionId,error:k instanceof Error?k.message:String(k)})})},[c,l]);return i.useEffect(()=>{var C;if(!n){Px(o)&&p("inbox"),j(((C=e[0])==null?void 0:C.tabKey)||null),R.current=null;return}if(o!=="chat"){R.current=null;return}const I=`${n.tabKey}:${n.sessionId||""}`;R.current!==I&&(R.current=I,g(n))},[e,g,o,n,p,j]),i.useEffect(()=>{if(!u)return;const I=e.find(C=>C.tabKey===u);I&&(j(I.tabKey),p("chat"),m==null||m())},[e,m,u,p,j]),i.useEffect(()=>{if(!d)return;const I=t.find(C=>C.id===d);I&&(y(I.id),w(),x("machines"),b("inbox"),p("machine"),h==null||h())},[t,h,d,w,b,p,x,y]),i.useEffect(()=>{f&&(x(f),p("inbox"),v==null||v())},[v,f,p,x]),i.useEffect(()=>{const I=r.filter(C=>C.inboxBucket==="task_complete"||C.unread);I.length!==0&&Cr("inbox_state",{screen:o,selectedTabKey:a,items:I.map(C=>{const S=Ur(C.conversation,c);return{liveState:S,tabKey:C.conversation.tabKey,sessionId:C.conversation.sessionId,displayPrimary:it(C.conversation),serverBucket:S.inboxBucket,computedBucket:C.inboxBucket,serverUnread:S.unread,computedUnread:C.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:ts(C.conversation)}})})},[r,c,o,a]),{markConversationRead:g}}function Ex(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ci(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function $x(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Bx({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,o]=i.useState("idle"),[c,l]=i.useState(""),[u,m]=i.useState(null),d=i.useCallback(()=>{o("idle"),l(""),m(null)},[]),h=i.useCallback(async(b,w,R)=>{var g;try{o("loading"),l(`Launching ${w}…`);const I={ideType:w,enableCdp:!0};(g=R==null?void 0:R.workspacePath)!=null&&g.trim()&&(I.workspace=R.workspacePath.trim()),await e(b,"launch_ide",I),o("done"),l(`${w} launch requested`)}catch(I){o("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),f=i.useCallback(async(b,w,R)=>{if(w.trim())try{o("loading"),l(R!=null&&R.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(b,"workspace_add",{path:w.trim(),createIfMissing:(R==null?void 0:R.createIfMissing)===!0});if(g!=null&&g.success){o("done"),l(R!=null&&R.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]),v=i.useCallback(async b=>{var w,R,g,I,C,S;try{o("loading"),l("Starting daemon upgrade…");const k=await e(b,"daemon_upgrade",{});if((w=k==null?void 0:k.result)!=null&&w.alreadyLatest){o("done"),l(`Already on v${((R=k==null?void 0:k.result)==null?void 0:R.version)||"latest"}.`);return}if((g=k==null?void 0:k.result)!=null&&g.upgraded||(I=k==null?void 0:k.result)!=null&&I.success){o("done"),l(`Upgrade to v${((C=k==null?void 0:k.result)==null?void 0:C.version)||"latest"} started. Daemon is restarting…`);return}o("error"),l(((S=k==null?void 0:k.result)==null?void 0:S.error)||"Upgrade failed")}catch(k){o("error"),l(k instanceof Error?k.message:"Upgrade failed")}},[e]),j=i.useCallback(async(b,w,R,g)=>{var S,k,W;const I=Date.now(),C={machineId:b,kind:w,providerType:R,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:I};try{o("loading"),l(`Launching ${R}…`),m(C);const L={cliType:R};(S=g==null?void 0:g.workspacePath)!=null&&S.trim()?L.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(L.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(L.resumeSessionId=g.resumeSessionId),(k=g==null?void 0:g.args)!=null&&k.trim()&&(L.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),(W=g==null?void 0:g.model)!=null&&W.trim()&&(L.initialModel=g.model.trim());const M=await e(b,"launch_cli",L),E=(M==null?void 0:M.result)||M,U=(E==null?void 0:E.sessionId)||(E==null?void 0:E.id);if(M!=null&&M.success&&U){m(null),o("done"),l(`${R} launched`),t(Gt(U));return}if(M!=null&&M.success){o("loading"),l(`${R} launch requested — waiting for session…`);return}m(null),o("error"),l((M==null?void 0:M.error)||(E==null?void 0:E.error)||`Could not launch ${w.toUpperCase()} workspace`)}catch(L){if($x(L)){o("loading"),l(`${R} launch requested — waiting for session…`);return}m(null),o("error"),l(L instanceof Error?L.message:`Could not launch ${w.toUpperCase()} workspace`)}},[t,e]),p=i.useCallback(async(b,w)=>{try{const R=await e(b,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),g=(R==null?void 0:R.result)??R;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(R){return console.error("Failed to list saved sessions on mobile:",R),[]}},[e]),y=i.useCallback(async(b,w)=>mn(e,b,w),[e]);i.useEffect(()=>{if(!u)return;const b=ci(u.workspacePath),w=r.find(g=>{var L,M,E,U;if(!g||g.type==="adhdev-daemon"||Ex(g.daemonId||g.id)!==u.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==u.kind||String(g.agentType||g.type||"")!==u.providerType)return!1;const k=String(g.providerSessionId||"");if(u.resumeSessionId&&k)return k===u.resumeSessionId;if(b){const K=ci(g.workspace||g.runtimeWorkspaceLabel);return K?K===b:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((U=(E=(M=(L=g.activeChat)==null?void 0:L.messages)==null?void 0:M.at)==null?void 0:E.call(M,-1))==null?void 0:U.timestamp)||0)>=u.startedAt-5e3});if(!w)return;const R=kc({entrySessionId:w.sessionId,entryInstanceId:w.instanceId,entryRouteId:w.id,conversations:n});R&&(m(null),o("done"),l(`${u.providerType} launched`),t(Gt(R)))},[n,r,t,u]),i.useEffect(()=>{if(!u)return;const b=window.setTimeout(()=>{m(w=>!w||w.startedAt!==u.startedAt?w:(o("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(b)},[u]);const x=i.useCallback(async(b,w)=>{if(w.kind==="ide"&&w.providerType){await h(b,w.providerType,{workspacePath:w.workspace||null});return}(w.kind==="cli"||w.kind==="acp")&&w.providerType&&await j(b,w.kind,w.providerType,{workspacePath:w.workspace||null,resumeSessionId:w.providerSessionId||null})},[h,j]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:h,handleAddWorkspace:f,handleMachineUpgrade:v,handleLaunchWorkspaceProvider:j,handleListSavedSessions:p,handleBrowseDirectory:y,handleOpenRecent:x}}function Kx({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:m}){const d=i.useCallback(x=>{o(x.tabKey),c("chat"),n(x)},[n,c,o]),h=i.useCallback(x=>{const b=e.find(w=>w.routeId===x.routeId&&w.streamSource==="native");b&&(o(b.tabKey),c("chat"),n(b))},[e,n,c,o]),f=i.useCallback(()=>{n(t),c("inbox")},[n,t,c]),v=i.useCallback((x,b="inbox")=>{l(x),a(),u("machines"),m(b),c("machine")},[a,m,c,u,l]),j=i.useCallback(x=>{const b=hs(x);b&&v(b,"chat")},[v]),p=i.useCallback(()=>{a(),c(r)},[r,a,c]),y=i.useCallback(x=>{u(x),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:h,backFromConversation:f,openMachine:v,openConversationMachine:j,backFromMachine:p,changeMachineSection:y}}function ps(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function Ox(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Wx({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,userName:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:v,onOpenHistory:j,onOpenRemote:p,onStopCli:y,wsStatus:x,isConnected:b,onShowHiddenConversation:w,onShowAllHiddenConversations:R,onHideConversation:g,onOpenNewSession:I,liveSessionInboxState:C,setCliViewModeOverrides:S}){const[k,W]=i.useState(()=>{var te;return((te=e[0])==null?void 0:te.tabKey)||null}),[L,M]=i.useState(()=>e[0]?"chat":"inbox"),[E,U]=i.useState("chats"),[K,N]=i.useState(null),[A,z]=i.useState("inbox"),$=i.useRef([]),B=Ls(),G="0.9.56",V=i.useMemo(()=>e.find(te=>te.tabKey===k)||e[0]||null,[e,k]),me=i.useMemo(()=>V?r.find(te=>te.id===V.routeId):void 0,[r,V]),ae=i.useMemo(()=>!V||qe(V)||!Ze(V)?null:_s(V),[V]),xe=i.useMemo(()=>r.filter(te=>te.type==="adhdev-daemon").sort(Pa),[r]),de=i.useMemo(()=>xe.find(te=>te.id===K)||null,[xe,K]),be=cn({sendDaemonCommand:a,activeConv:V||void 0,setActionLogs:o,isStandalone:c}),he=Bx({sendDaemonCommand:a,navigate:B,ides:r,conversations:e}),Y=i.useMemo(()=>e.map(te=>{const D=L==="chat"&&(V==null?void 0:V.tabKey)===te.tabKey,ve=nn(te,C,{hideOpenTaskCompleteUnread:!0,isOpenConversation:D}),Ce=ts(te),ke=_c(te);return{conversation:te,timestamp:Ce,preview:ke,unread:ve.unread,requiresAction:ve.requiresAction,isWorking:ve.isWorking,inboxBucket:ve.inboxBucket}}),[e,C,L,V]),{markConversationRead:oe}=Dx({conversations:e,machineEntries:xe,items:Y,selectedConversation:V,selectedTabKey:k,screen:L,liveSessionInboxState:C,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:v,setSelectedTabKey:W,setScreen:M,setSelectedMachineId:N,setSection:U,setMachineBackTarget:z,resetMachineAction:he.resetMachineAction}),J=Kx({conversations:e,selectedConversation:V,machineBackTarget:A,markConversationRead:oe,resetMachineAction:he.resetMachineAction,setSelectedTabKey:W,setScreen:M,setSelectedMachineId:N,setSection:U,setMachineBackTarget:z}),ue=i.useMemo(()=>Er(Y.filter(te=>te.requiresAction)),[Y]),le=i.useMemo(()=>Er(Y.filter(te=>te.unread&&!te.requiresAction)),[Y]),Se=i.useMemo(()=>Ax(Y.filter(te=>!te.unread&&!te.requiresAction&&te.isWorking),$.current),[Y]);i.useEffect(()=>{$.current=Se.map(te=>te.conversation.tabKey)},[Se]);const ie=i.useMemo(()=>Er(Y.filter(te=>!te.unread&&!te.requiresAction&&!te.isWorking)),[Y]),pe=i.useMemo(()=>de?Y.filter(te=>hs(te.conversation)===de.id):[],[Y,de]),ne=i.useMemo(()=>Rx(de,r),[r,de]),Z=(de==null?void 0:de.version)||null,ee=!!de&&!!Z&&!0&&Z!==G,q=i.useMemo(()=>(de==null?void 0:de.availableProviders)||[],[de]),X=i.useMemo(()=>q.filter(te=>ps(te,"cli")).map(te=>({type:te.type,displayName:te.displayName||te.type,icon:te.icon})),[q]),re=i.useMemo(()=>q.filter(te=>ps(te,"acp")).map(te=>({type:te.type,displayName:te.displayName||te.type,icon:te.icon})),[q]),je=i.useMemo(()=>_x(xe,Y),[Y,xe]),we=i.useCallback(async te=>{de&&await he.handleOpenRecent(de.id,te)},[he,de]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:L==="chat"&&V?s.jsx(wx,{selectedConversation:V,isAcp:qe(V),isStandalone:c,selectedIdeEntry:me,actionLogs:n,userName:l,isSendingChat:be.isSendingChat,sendFeedbackMessage:be.sendFeedbackMessage,isFocusingAgent:be.isFocusingAgent,handleModalButton:be.handleModalButton,handleRelaunch:be.handleRelaunch,onBack:J.backFromConversation,onOpenNativeConversation:J.openNativeConversation,onOpenMachine:J.openConversationMachine,onHideConversation:g,onOpenHistory:j,onOpenRemote:p,onStopCli:y,cliViewMode:ae,onSetCliViewMode:async te=>{await il({conversation:V,mode:te,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:S})},handleSendChat:be.handleSendChat,handleFocusAgent:be.handleFocusAgent}):L==="machine"&&de?s.jsx(Ix,{selectedMachineEntry:de,selectedMachineConversations:pe,selectedMachineRecentLaunches:ne,cliProviders:X,acpProviders:re,selectedMachineNeedsUpgrade:ee,appVersion:G,machineAction:he.machineAction,isStandalone:c,section:E,showBottomNav:A==="inbox",onBack:J.backFromMachine,onSectionChange:J.changeMachineSection,onOpenConversation:J.openConversation,onOpenRecent:we,onOpenMachineDetails:()=>B(`/machines/${de.id}`),onMachineUpgrade:()=>he.handleMachineUpgrade(de.id),onLaunchDetectedIde:(te,D)=>he.handleLaunchDetectedIde(de.id,te,D),onAddWorkspace:(te,D)=>he.handleAddWorkspace(de.id,te,D),onBrowseDirectory:te=>he.handleBrowseDirectory(de.id,te),onLaunchWorkspaceProvider:(te,D,ve)=>he.handleLaunchWorkspaceProvider(de.id,te,D,ve),onListSavedSessions:te=>he.handleListSavedSessions(de.id,te)}):s.jsx(jx,{section:E,attentionItems:ue,unreadItems:le,workingItems:Se,completedItems:ie,hiddenConversations:t,machineCards:je,getAvatarText:Ox,actionLogs:n,sendDaemonCommand:a,onOpenConversation:J.openConversation,onShowConversation:w,onShowAllHidden:R,onOpenNewSession:I,onOpenMachine:J.openMachine,onOpenSettings:()=>B("/settings"),onSectionChange:U,wsStatus:x,isConnected:b,isStandalone:c})})}function $n(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Hx({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const c=i.useRef(0),[l,u]=i.useState(!1),[m,d]=i.useState(null),h=i.useCallback(()=>{c.current=0,u(!1),d(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const f=i.useCallback(y=>{y.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),v=i.useCallback(y=>{if(!y.dataTransfer.types.includes("text/tab-key"))return;if(y.preventDefault(),!$n(t,r)){d("merge");return}const x=y.currentTarget.getBoundingClientRect(),b=y.clientX-x.left,w=x.width/3;b<w?d("split-left"):b>w*2?d("split-right"):d("merge")},[t,r]),j=i.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),d(null))},[]),p=i.useCallback(y=>{c.current=0,u(!1);const x=y.dataTransfer.getData("text/tab-key"),b=x?e.some(R=>R.tabKey===x):!1,w=m;if(d(null),o(),!!x){if(y.preventDefault(),w==="split-left"&&$n(t,r)){r==null||r(x,"split-left");return}if(w==="split-right"&&$n(t,r)){r==null||r(x,"split-right");return}if(b){a(x);return}n==null||n(x)}},[e,m,t,r,n,a,o]);return{dragOver:l,dropAction:m,resetDragState:h,handleDragEnter:f,handleDragOver:v,handleDragLeave:j,handleDrop:p}}function Fx(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 Ux({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,c]=i.useState(t??null),[l,u]=i.useState(r??[]),[m,d]=i.useState(null),h=i.useRef(null),f=i.useRef(null),v=i.useRef(n),j=i.useRef(a);i.useEffect(()=>{v.current=n},[n]),i.useEffect(()=>{j.current=a},[a]),i.useEffect(()=>{t&&t!==o&&c(t)},[t,o]),i.useEffect(()=>{u(C=>{const S=Fx(C,e);return S.length===C.length&&S.every((k,W)=>k===C[W])?C:S})},[e]);const p=i.useMemo(()=>{const C=m??l;if(C.length===0)return e;const S=new Map(C.map((k,W)=>[k,W]));return[...e].sort((k,W)=>{const L=S.get(k.tabKey)??999,M=S.get(W.tabKey)??999;return L-M})},[e,m,l]);i.useEffect(()=>{var S,k;if(p.length===0){o!==null&&(c(null),(S=v.current)==null||S.call(v,null));return}if(o&&p.some(W=>W.tabKey===o))return;const C=p[0].tabKey;C!==o&&(c(C),(k=v.current)==null||k.call(v,C))},[p,o]);const y=i.useMemo(()=>p.find(C=>C.tabKey===o),[p,o]),x=i.useCallback(C=>{var S;c(C),(S=v.current)==null||S.call(v,C)},[]),b=i.useCallback((C,S,k)=>{u(W=>{var U;const L=W.filter(K=>K!==C),M=L.indexOf(S);if(M<0)return W;const E=k==="left"?M:M+1;return L.splice(E,0,C),(U=j.current)==null||U.call(j,L),L}),d(null)},[]),w=i.useCallback((C,S,k)=>{const L=(l.length>0?l:e.map(U=>U.tabKey)).filter(U=>U!==C),M=L.indexOf(S);if(M<0)return;const E=k==="left"?M:M+1;L.splice(E,0,C),h.current=L,d(L)},[l,e]),R=i.useCallback(()=>{var S;const C=h.current;C&&(u(C),(S=j.current)==null||S.call(j,C))},[]),g=i.useCallback(()=>{h.current=null,d(null)},[]),I=i.useCallback(C=>{u(S=>{var W;const k=S.filter(L=>L!==C);return k.push(C),(W=j.current)==null||W.call(j,k),k})},[]);return{activeTabId:o,activeConv:y,sortedConversations:p,previewOrderRef:h,draggingTabRef:f,selectTab:x,handleTabReorder:b,updatePreviewOrder:w,commitPreviewOrder:R,clearPreviewOrder:g,moveTabToEnd:I,setDraggingTabKey:C=>{f.current=C}}}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 oo({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,u=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?$c: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:u}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),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:Dt,"aria-label":Dt,children:[s.jsx(Vi,{size:14}),s.jsx("span",{children:Dt})]})}),c&&s.jsx(pl,{}),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 gl="adhdev-tab-shortcuts";function yl(){try{return JSON.parse(localStorage.getItem(gl)||"{}")}catch{return{}}}function vl({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,c]=i.useState(()=>yl()),[l,u]=i.useState(null),m=i.useCallback(h=>{const f=[];return h.metaKey&&f.push(a?"⌘":"Meta"),h.ctrlKey&&f.push("Ctrl"),h.altKey&&f.push(a?"⌥":"Alt"),h.shiftKey&&f.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(f.push(h.key.length===1?h.key.toUpperCase():h.key),f.join("+"))},[a]),d=i.useCallback(h=>{c(h);try{localStorage.setItem(gl,JSON.stringify(h))}catch{}},[]);return i.useEffect(()=>{if(!e||!l)return;const h=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){u(null);return}const v=m(f);if(!v)return;const j={...o};for(const[p,y]of Object.entries(j))y===v&&delete j[p];j[l]=v,d(j),u(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,o,d,m]),i.useEffect(()=>{if(!e)return;const h=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[v,j]of Object.entries(o))if(t.includes(v)&&m(f)===j){f.preventDefault(),r(),n(v);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,o,t,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const Bn=e=>{e.preventDefault()},Vx=i.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:m,onConversationActivated:d,onPreviewReorder:h,onReorderTab:f,onCommitPreviewOrder:v,onClearPreviewOrder:j,onDragStateReset:p,onDragTabKeyChange:y,onReceiveTab:x,onOpenContextMenu:b,longPressTimer:w,isGroupActive:R}){const g=Rs(t),I=g.isGenerating?"agent-tab-generating":g.isWaiting?"agent-tab-waiting":"",C=g.isReconnecting,S=i.useCallback(A=>{l.current=t.tabKey,y(t.tabKey),A.dataTransfer.setData("text/tab-key",t.tabKey),A.dataTransfer.effectAllowed="move"},[t.tabKey,l,y]),k=i.useCallback(()=>{l.current=null,y(null),v(),j(),p()},[l,y,v,j,p]),W=i.useCallback(A=>{const z=l.current;if(!(!z||z===t.tabKey)&&A.dataTransfer.types.includes("text/tab-key")){A.preventDefault(),A.stopPropagation();const $=A.currentTarget.getBoundingClientRect(),B=A.clientX<$.left+$.width/2?"left":"right";h(z,t.tabKey,B)}},[t.tabKey,l,h]),L=i.useCallback(A=>{A.preventDefault(),A.stopPropagation();const z=A.dataTransfer.getData("text/tab-key");if(z&&z!==t.tabKey){const $=A.currentTarget.getBoundingClientRect(),B=A.clientX<$.left+$.width/2?"left":"right";c.includes(z)?f(z,t.tabKey,B):x&&x(z)}j()},[t.tabKey,c,f,x,j]),M=i.useCallback(A=>{A.stopPropagation(),u(),m(t.tabKey),d(t)},[t,d,u,m]),E=i.useCallback(A=>{A.preventDefault(),b(A.clientX,A.clientY,t.tabKey)},[t.tabKey,b]),U=i.useCallback(A=>{const z=A.touches[0];w.current=setTimeout(()=>{b(z.clientX,z.clientY,t.tabKey)},600)},[t.tabKey,w,b]),K=i.useCallback(()=>{w.current&&clearTimeout(w.current)},[w]),N=["adhdev-dockview-tab",I,r&&"is-active",R&&"is-group-active",C&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:N,draggable:!0,onDragStart:S,onDragEnd:k,onDragOver:W,onDrop:L,onClick:M,onContextMenu:E,onTouchStart:U,onTouchEnd:K,onTouchMove:K,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:"▲"}):C?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:[C?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:ss(t)}):g.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[ss(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:ss(t)}),s.jsx(ln,{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 Gx({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:v,onReceiveTab:j,onHideTab:p,isGroupActive:y,allowTabShortcuts:x=!0}){const[b,w]=i.useState(null),R=i.useRef(null),g=i.useRef(null),I=i.useMemo(()=>e.map(E=>E.tabKey),[e]);ir("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:C,tabShortcuts:S,shortcutListening:k,setShortcutListening:W,saveShortcuts:L}=vl({enabled:x,sortedTabKeys:e.map(E=>E.tabKey),onFocus:o,onSelectTab:c});i.useEffect(()=>{if(!b)return;const E=U=>{const K=document.querySelector("[data-pane-context-menu]");K&&K.contains(U.target)||w(null)};return window.addEventListener("mousedown",E,!0),()=>window.removeEventListener("mousedown",E,!0)},[b]),i.useEffect(()=>{const E=g.current;if(!E)return;const U=K=>{Math.abs(K.deltaY)<=Math.abs(K.deltaX)||(K.preventDefault(),E.scrollLeft+=K.deltaY)};return E.addEventListener("wheel",U,{passive:!1}),()=>E.removeEventListener("wheel",U)},[]);const M=i.useCallback((E,U,K)=>{w({x:E,y:U,tabKey:K})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:g,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(E=>s.jsx(Vx,{conv:E,isActive:t===E.tabKey,isDraggedTab:a.current===E.tabKey,isTaskCompleteUnread:n.has(E.tabKey),shortcut:x?S[E.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:v,onReceiveTab:j,onOpenContextMenu:M,longPressTimer:R,isGroupActive:y},E.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:Bn,onClick:E=>{E.stopPropagation(),W(b.tabKey),w(null)},children:["⌨ ",S[b.tabKey]?`Change shortcut (${S[b.tabKey]})`:"Set shortcut"]}),S[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:Bn,onClick:()=>{const E={...S};delete E[b.tabKey],L(E),w(null)},children:"✕ Remove shortcut"})]}),p&&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:Bn,onClick:()=>{p(b.tabKey),w(null)},children:"🚫 Hide from Dashboard"})]})]}),x&&k&&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:()=>W(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:E=>E.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",C?"⌘+1":"Ctrl+1",", ",C?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function qx({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,userName:u,groupIndex:m,onFocus:d,isSplitMode:h,numGroups:f,onMoveTab:v,onReceiveTab:j,style:p,onActiveTabChange:y,initialActiveTabId:x,initialTabOrder:b,onTabOrderChange:w,onHideTab:R,isFocused:g,allowTabShortcuts:I=!0,onOpenNewSession:C,liveSessionInboxState:S}){const{sendCommand:k}=vt(),W=i.useRef(null),{activeTabId:L,activeConv:M,sortedConversations:E,draggingTabRef:U,selectTab:K,handleTabReorder:N,updatePreviewOrder:A,commitPreviewOrder:z,clearPreviewOrder:$,moveTabToEnd:B,setDraggingTabKey:G}=Ux({conversations:e,initialActiveTabId:x,initialTabOrder:b,onActiveTabChange:y,onTabOrderChange:w}),V=cn({sendDaemonCommand:a,activeConv:M,setActionLogs:o,isStandalone:c}),{dragOver:me,dropAction:ae,resetDragState:xe,handleDragEnter:de,handleDragOver:be,handleDragLeave:he,handleDrop:Y}=Hx({conversations:e,numGroups:f,onMoveTab:v,onReceiveTab:j,onOwnTabDrop:B,onClearPreviewOrder:$}),oe=M&&!qe(M)&&_s(M)==="terminal",J=i.useMemo(()=>M?t.find(ie=>ie.id===M.routeId):void 0,[t,M]),ue=i.useMemo(()=>M?n.filter(ie=>ie.routeId===M.tabKey):[],[n,M]),le=i.useMemo(()=>new Set(E.filter(ie=>Ou(ie,S,{isOpenConversation:ie.tabKey===L})).map(ie=>ie.tabKey)),[L,S,E]);ir("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:L,dragOver:me});const Se=i.useCallback(ie=>{ie.streamSource==="agent-stream"&&ie.agentType&&k(ie.routeId,hc(),{agentType:ie.agentType,...ie.sessionId&&{targetSessionId:ie.sessionId}}).catch(()=>{})},[k]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...p,outline:me?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(Gx,{conversations:E,activeTabId:L,groupIndex:m,numGroups:f,unreadTabKeys:le,draggingTabRef:U,onFocus:d,onSelectTab:K,onConversationActivated:Se,onPreviewReorder:A,onReorderTab:N,onCommitPreviewOrder:z,onClearPreviewOrder:$,onDragStateReset:xe,onDragTabKeyChange:G,onMoveTab:v,onReceiveTab:j,onHideTab:R,isGroupActive:g??!1,allowTabShortcuts:I}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:de,onDragOver:be,onDragLeave:he,onDrop:Y,children:[me&&s.jsx(zx,{dropAction:ae,canSplit:!!(f<4&&v)}),M?s.jsx(no,{activeConv:M,clearToken:r[M.tabKey]||0,isCliTerminal:!!oe,ideEntry:J,terminalRef:W,handleModalButton:V.handleModalButton,handleRelaunch:V.handleRelaunch,handleSendChat:V.handleSendChat,isSendingChat:V.isSendingChat,sendFeedbackMessage:V.sendFeedbackMessage,handleFocusAgent:V.handleFocusAgent,isFocusingAgent:V.isFocusingAgent,actionLogs:ue,userName:u,isInputActive:!h||!!g}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(oo,{conversationsCount:e.length,isSplitMode:h,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:C})})]})]})}function Yx({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:m,isStandalone:d,hasRegisteredMachines:h,userName:f,focusedGroup:v,focusGroup:j,moveTabToGroup:p,splitTabRelative:y,closeGroup:x,handleResizeStart:b,groupActiveTabIds:w,setGroupActiveTab:R,groupTabOrders:g,setGroupTabOrder:I,toggleHiddenTab:C,onOpenNewSession:S,allowTabShortcuts:k=!0,liveSessionInboxState:W}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((L,M)=>{const E=t&&n.length===r?`${n[M]}%`:void 0;return s.jsxs(kt.Fragment,{children:[t&&M>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:U=>b(M-1,U),onDoubleClick:()=>x(M),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(qx,{style:t?{flexBasis:E??`${100/r}%`,flexGrow:E?0:1,flexShrink:E?0:1}:void 0,conversations:L,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:m,isStandalone:d,hasRegisteredMachines:h,userName:f,groupIndex:M,isFocused:t&&v===M,onFocus:()=>j(M),isSplitMode:t,numGroups:r,onMoveTab:(U,K)=>{K==="left"&&M>0?p(U,M-1):K==="right"&&M<r-1?p(U,M+1):K==="split-left"&&r<4?y(U,M,"left"):K==="split-right"&&r<4&&y(U,M,"right")},onReceiveTab:U=>p(U,M),onActiveTabChange:U=>R(M,U),initialActiveTabId:w[M],initialTabOrder:g[M],onTabOrderChange:U=>I(M,U),onHideTab:C,onOpenNewSession:S,allowTabShortcuts:k,liveSessionInboxState:W})]},M)})})}function wl({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=i.useState(null),[c,l]=i.useState(null);i.useEffect(()=>e?lt.onScreenshot("ide-page",(d,h)=>{if(d!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(h)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var d;return e?((d=lt.onStatus)==null?void 0:d.call(lt,(h,f)=>{h===e&&f!=null&&f.screenshotUsage&&l(f.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,t]),i.useEffect(()=>{const m=e?lt.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&t?m.startScreenshots(t):m.stopScreenshots(t),()=>{m.stopScreenshots(t)}},[n,r,t,e]);const u=i.useCallback(async(m,d)=>{const h=e?lt.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(m,d,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const kl="adhdev-dashboard-action-shortcuts",Xx=1200,Jx=[["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 Qx(){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 jl(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 va(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Zr(e){const t=Object.fromEntries(jl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(kl)||"{}"),n={...t,...r};for(const[a,o]of Jx)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function Sl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Zx({enabled:e=!0,onTrigger:t}){const r=Qx(),[n,a]=i.useState(()=>Zr(r)),[o,c]=i.useState(null),[l,u]=i.useState([]),m=i.useRef({parts:[],timer:null}),d=i.useCallback(p=>{const y=[];return p.metaKey&&y.push(r?"⌘":"Meta"),p.ctrlKey&&y.push("Ctrl"),p.altKey&&y.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&y.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(y.push(Sl(p.key)),y.join("+"))},[r]),h=i.useCallback(p=>{a(p);try{localStorage.setItem(kl,JSON.stringify(p))}catch{}},[]);i.useEffect(()=>{const p=Zr(r),y=Object.entries(n),x=Object.entries(p);y.length===x.length&&y.every(([b,w])=>p[b]===w)||h(p)},[n,r,h]);const f=i.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),v=i.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},Xx))},[]);i.useEffect(()=>{if(!o)return;const p=y=>{if(y.preventDefault(),y.stopPropagation(),y.key==="Escape"){c(null),u([]);return}const x=d(y);if(!x)return;const w=!(y.metaKey||y.ctrlKey||y.altKey)&&/^[A-Z0-9]$/.test(x);if(l.length===0&&w){u([x]);return}const g=[...l,x].slice(0,2).join(" "),I={...n};for(const[C,S]of Object.entries(I))S===g&&delete I[C];I[o]=g,h(I),c(null),u([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,d,h,o,l]),i.useEffect(()=>{if(!e||o)return;const p=y=>{if(y.defaultPrevented)return;const x=d(y);if(!x)return;const b=y.metaKey||y.ctrlKey||y.altKey;if(va(y.target))return;const w=m.current.parts,R=b?[x]:[...w.slice(-1),x].slice(-2),g=R.join(" "),I=R[R.length-1],C=Object.entries(n).filter(([,M])=>!!M),S=C.find(([,M])=>M===g);if(S){y.preventDefault(),f(),t(S[0]);return}if(C.some(([,M])=>M.startsWith(`${g} `))){y.preventDefault(),m.current.parts=R,v();return}const W=C.find(([,M])=>M===I);if(W){y.preventDefault(),f(),t(W[0]);return}if(C.some(([,M])=>M.startsWith(`${I} `))){y.preventDefault(),m.current.parts=[I],v();return}f()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,v,e,d,t,f,o]),i.useEffect(()=>()=>f(),[f]);const j=i.useMemo(()=>jl(r),[r]);return{isMac:r,actionDefinitions:j,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:h}}function eb({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 Nl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function li({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!Nl(n):!0}function tb({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:Nl(r)}const Cl=1e3,sb=4;function di(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function ui(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function rb({detachDelayMs:e=Cl,stillnessThresholdPx:t=sb,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,c=null,l=null,u=null,m=null,d=!1;const h=()=>{m!=null&&(a(m),m=null)},f=()=>{h(),l=null},v=()=>{h(),o=null,c=null,l=null,u=null,d=!1},j=()=>{!o||!l||!u||d||m!=null||(m=n(()=>{m=null,!(!o||!l||!u||d)&&di(u,c)&&(ui(l,u,t)||(d=!0,r({panelId:o,clientX:u.clientX,clientY:u.clientY})))},e))},p=x=>{if(!(!o||d)){if(!di(x,c)){u={clientX:x.clientX,clientY:x.clientY},f();return}(!l||ui(l,x,t))&&(h(),l={clientX:x.clientX,clientY:x.clientY}),u={clientX:x.clientX,clientY:x.clientY},j()}},y=x=>{!o||d||(x&&(u={clientX:x.clientX,clientY:x.clientY}),f())};return{startDrag:x=>{h(),o=x.panelId,c=x.selfPanelBounds??null,l=null,u={clientX:x.clientX,clientY:x.clientY},d=!1},markSelfPanel:p,markNonSelfPanel:y,markNoDropTarget:y,markDockTarget:y,endDrag:v,isDragging:()=>o!=null,hasDetached:()=>d,dispose:v}}function nb(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}const Tl=i.createContext(null);function pn(){const e=i.useContext(Tl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function $r(e){return it(e)||e.tabKey}function ab(e){return`remote:${e}`}function At(e){return e.startsWith("remote:")}function mi(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ob(e){e.preventDefault()}function Kn(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 On(e,t){e.classList.remove(Zn.className,ea.className),e.classList.add(t==="light"?Zn.className:ea.className)}function fi(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 ib(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 cb(e,t,r){var c;const n=[t];let a;for(const l of n){let u;for(const m of l){const d=e.addPanel({id:m.tabKey,component:"conversation",title:$r(m),params:{kind:"conversation",tabKey:m.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return r??((c=t[0])==null?void 0:c.tabKey)??null}function pi(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])At(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!==$r(n)&&a.api.setTitle($r(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:$r(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 hi(e,t,r){var u,m;const n=r?ab(r):null;for(const d of[...e.panels])At(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=_t(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),c=Ec(a);if(o){o.title!==c&&o.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((m=e.panels.find(d=>!At(d.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function lb({params:e,api:t}){var h;const r=pn(),n=i.useRef(null),[a,o]=i.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=cn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o(t.isActive);const f=[t.onDidActiveChange(v=>o(v.isActive)),t.onDidActiveGroupChange(v=>{if(!t.isActive&&!v.isActive){o(!1);return}o(t.isActive)})];return()=>{for(const v of f)v.dispose()}},[t]);const u=i.useMemo(()=>c?r.ides.find(f=>f.id===c.routeId):void 0,[r.ides,c]),m=i.useMemo(()=>c?r.actionLogs.filter(f=>f.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(oo,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const d=!qe(c)&&_s(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(no,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:d,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:m,userName:r.userName,scrollToBottomRequestNonce:((h=r.scrollToBottomRequest)==null?void 0:h.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:a})})}function db({params:e}){var u;const t=pn(),r=i.useMemo(()=>_t([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=i.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:c,handleRemoteAction:l}=wl({doId:a,targetSessionId:r?pc(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(Qi,{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 ub(){const e=pn();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(oo,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function mb(e){var v,j;ib(e);const t=pn(),r=i.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=_t([...t.conversationsByTabKey.values()],e.params.routeId),y=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,x=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${y?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((j=e.api.group.activePanel)==null?void 0:j.id)===e.api.id,o=e.api.isGroupActive,c=nn(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,u=c.isConnecting,m=c.isGenerating,d=c.isWaiting,h=c.unread,f=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:p=>{var y;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((y=p.target)==null?void 0:y.ownerDocument)??document})},children:[h&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?s.jsx("div",{className:"tab-spinner"}):d?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:"○"}):u?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:ss(n)}):u?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ss(n)}):s.jsx("span",{children:ss(n)})})]}),f&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:f,children:f})]})}function fb({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:u,userName:m,toggleHiddenTab:d,actionShortcuts:h,registerActionHandlers:f,onActiveTabChange:v,onOpenNewSession:j,onRequestScrollToBottom:p,requestedActiveTabKey:y,requestedRemoteIdeId:x,onRequestedActiveTabConsumed:b,scrollToBottomRequest:w,liveSessionInboxState:R,layoutProfile:g}){var Ge,ct,ft;const{theme:I}=Qa(),{sendCommand:C}=vt(),S=i.useRef(null),k=i.useRef(null),W=i.useRef(null),L=i.useRef(!1),M=i.useRef(!1),E=i.useRef(!1),U=i.useRef(null),K=i.useRef([]),[N,A]=i.useState(null),[z,$]=i.useState(0),B=i.useRef(typeof window>"u"?{}:Bh(g)),G=i.useMemo(()=>new Map(e.map(H=>[H.tabKey,H])),[e]),V=i.useMemo(()=>{const H=S.current;return H?H.groups.some(_=>{try{const T=_.model.location.type;return T!=="floating"&&T!=="popout"?!1:_.panels.some(P=>G.has(P.id))}catch{return!1}}):!1},[G,z,e]),me=i.useCallback(()=>{var H;(H=S.current)==null||H.focus()},[]),ae=i.useCallback((H,_)=>{p==null||p(H,_)},[p]),xe=i.useCallback(H=>{const _=document,T=H.document;for(const ce of _.querySelectorAll('link[rel="stylesheet"]')){const Ne=T.createElement("link");Ne.rel="stylesheet",Ne.href=ce.href,ce.crossOrigin&&(Ne.crossOrigin=ce.crossOrigin),T.head.appendChild(Ne)}for(const ce of _.querySelectorAll("style")){const Ne=T.createElement("style");Ne.textContent=ce.textContent,T.head.appendChild(Ne)}const P=[];for(const ce of _.styleSheets)try{for(const Ne of ce.cssRules)Ne instanceof CSSStyleRule&&(Ne.selectorText===":root"||Ne.selectorText==="html")&&P.push(Ne.cssText)}catch{}if(P.length>0){const ce=T.createElement("style");ce.textContent=P.join(`
52
+ `),T.head.appendChild(ce)}const F=_.documentElement.getAttribute("data-theme");F&&T.documentElement.setAttribute("data-theme",F),T.documentElement.style.colorScheme=F==="light"?"light":"dark",T.body.className=_.body.className;const Q=_.documentElement.getAttribute("style");Q&&T.documentElement.setAttribute("style",Q);const ye=T.getElementById("dv-popout-window");ye instanceof HTMLElement&&(ye.classList.add("adhdev-dockview"),On(ye,I))},[I]),de=i.useCallback(()=>{var _;const H=S.current;if(H)for(const T of H.groups)try{const P=(_=T.element)==null?void 0:_.ownerDocument;if(!P||P===document)continue;const F=P.getElementById("dv-popout-window");F instanceof HTMLElement&&(F.classList.add("adhdev-dockview"),On(F,I));const Q=document.documentElement.getAttribute("data-theme");Q&&P.documentElement.setAttribute("data-theme",Q),P.documentElement.style.colorScheme=Q==="light"?"light":"dark",P.body.className=document.body.className;const ye=document.documentElement.getAttribute("style");ye?P.documentElement.setAttribute("style",ye):P.documentElement.removeAttribute("style")}catch{}},[I]),be=i.useCallback(H=>{const _=S.current;if(!_)return;const T=_.getPanel(H);T&&_.addPopoutGroup(T,{popoutUrl:"/popout.html",onDidOpen:({window:P})=>{xe(P),pe();const F=G.get(H);P.document.title=F?`${it(F)} — ADHDev`:"ADHDev — Popout"}})},[G,xe]),he=i.useCallback(H=>{const _=S.current,T=_==null?void 0:_.getPanel(H);if(!_||!T)return;const P=_.groups.filter(F=>{var Q;try{return((Q=F.element)==null?void 0:Q.ownerDocument)===document}catch{return!0}});P.length>0?T.api.moveTo({group:P[0],position:"center"}):T.api.moveTo({position:"center"}),T.api.setActive()},[]),Y=i.useCallback(H=>{var P;const _=S.current;if(!_)return!1;const T=_.getPanel(H);if(!T)return!1;try{return((P=T.group.element)==null?void 0:P.ownerDocument)!==document}catch{return!1}},[]),oe=i.useCallback(H=>{Y(H)&&he(H),d(H)},[Y,he,d]),J=i.useCallback(H=>{const _=S.current,T=_==null?void 0:_.getPanel(H);!_||!T||_.addFloatingGroup(T,{width:600,height:500})},[]),ue=i.useCallback(H=>{var T;const _=(T=S.current)==null?void 0:T.getPanel(H);if(!_)return!1;try{return _.group.model.location.type==="floating"}catch{return!1}},[]),le=i.useCallback(()=>{var _,T;const H=(T=(_=S.current)==null?void 0:_.activePanel)==null?void 0:T.id;return!H||At(H)?null:G.has(H)?H:null},[G]),Se=i.useCallback(H=>{const _=S.current,T=_==null?void 0:_.getPanel(H);if(!_||!T)return;const P=_.groups.filter(F=>{try{return F.model.location.type==="grid"}catch{return!0}});P.length>0?T.api.moveTo({group:P[0],position:"center"}):T.api.moveTo({position:"center"}),T.api.setActive()},[]),ie=i.useCallback(()=>{var Q;const H=S.current;if(!H)return;const T=H.groups.filter(ye=>{var ce;try{return((ce=ye.element)==null?void 0:ce.ownerDocument)===document&&ye.model.location.type==="grid"}catch{return!1}})[0]||null,P=[...H.panels];for(const ye of P){const ce=(Q=ye.group.element)==null?void 0:Q.ownerDocument,Ne=ye.group.model.location.type;ce===document&&Ne==="grid"||(T&&T.id!==ye.group.id?ye.api.moveTo({group:T,position:"center"}):ye.api.moveTo({position:"center"}))}const F=H.activePanel;F&&(F.group.model.openPanel(F),F.api.setActive()),Kn(document)},[]),pe=i.useCallback(()=>{var _,T;const H=S.current;if(H)for(const P of H.groups){const F=(_=P.element)==null?void 0:_.ownerDocument;if(!F||F===document)continue;const Q=F.getElementById("dv-popout-window");if(!(Q instanceof HTMLElement))continue;let ye=null,ce=F.title||"ADHDev",Ne="Popout workspace";const De=P.activePanel;if(De)if(ye=De.id,At(De.id)){const Ae=((T=De.params)==null?void 0:T.routeId)||De.id.slice(7),Je=_t([...G.values()],Ae);ce=Ec(Je),Ne=Je!=null&&Je.machineName?`Remote view · ${Je.machineName}`:"Remote view"}else{const Ae=G.get(De.id);ce=Ae?it(Ae):De.title||De.id,Ne=Ae?ss(Ae):"Dockview panel"}F.title=`${ce} — ADHDev`;const $e=Array.from(F.querySelectorAll("#adhdev-popout-header"));for(const Ae of $e)Ae.remove();const Me=F.createElement("div");Me.id="adhdev-popout-header",F.body.appendChild(Me),Me.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(";")),Me.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
- <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${ui(ce)}</div>
56
- <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${ui(Ne)}</div>
55
+ <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${mi(ce)}</div>
56
+ <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${mi(Ne)}</div>
57
57
  </div>
58
58
  <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
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
- `,Q.style.top="52px",Q.style.height="calc(100% - 52px)";const Re=Ie.querySelector("[data-adhdev-popout-focus]");Re&&(Re.onclick=()=>{window.focus()});const We=Ie.querySelector("[data-adhdev-popout-dock]");We&&(We.disabled=!ye,We.style.opacity=ye?"1":"0.5",We.style.cursor=ye?"pointer":"default",We.onclick=()=>{var Ae;ye&&he(ye),(Ae=F.defaultView)==null||Ae.focus()})}},[V,he]),re=i.useCallback(H=>{var P;const _=S.current,T=_==null?void 0:_.getPanel(H);if(!(!_||!T)){T.group.model.openPanel(T),T.api.setActive(),ne(H,"dockview-shortcut");try{const F=T.group.model.location;F.type==="popout"?F.getWindow().focus():Bn((P=T.group.element)==null?void 0:P.ownerDocument)}catch{}}},[ne]),Z=i.useCallback(H=>{const _=S.current,T=_==null?void 0:_.activePanel,P=(_==null?void 0:_.activeGroup)||(T==null?void 0:T.group);if(!_||!T||!P)return;const F=P.panels||[];if(F.length<=1)return;const Q=F.findIndex(Ne=>Ne.id===T.id);if(Q<0)return;const ye=(Q+H+F.length)%F.length,ce=F[ye];ce&&(ce.group.model.openPanel(ce),ce.api.setActive(),At(ce.id)||ne(ce.id,"dockview-shortcut"))},[ne]),ee=i.useCallback(H=>{var Re;const _=S.current,T=(_==null?void 0:_.activeGroup)||((Re=_==null?void 0:_.activePanel)==null?void 0:Re.group);if(!_||!T)return;const P=_.groups||[],F=P.find(We=>We.id===T.id);if(!F)return;const Q=F.element.getBoundingClientRect(),ye=Q.left+Q.width/2,ce=Q.top+Q.height/2,Ne=(We,Ae,Je,Qe)=>Math.max(0,Math.min(Ae,Qe)-Math.max(We,Je)),De=We=>{const Ae=We.element.getBoundingClientRect(),Je=Ae.left+Ae.width/2,Qe=Ae.top+Ae.height/2;let fe=0,_e=0,rt=0,nt=!1;if(H==="left"?(nt=Je<ye,fe=Math.max(0,Q.left-Ae.right),_e=Math.abs(Qe-ce),rt=Ne(Q.top,Q.bottom,Ae.top,Ae.bottom)):H==="right"?(nt=Je>ye,fe=Math.max(0,Ae.left-Q.right),_e=Math.abs(Qe-ce),rt=Ne(Q.top,Q.bottom,Ae.top,Ae.bottom)):H==="above"?(nt=Qe<ce,fe=Math.max(0,Q.top-Ae.bottom),_e=Math.abs(Je-ye),rt=Ne(Q.left,Q.right,Ae.left,Ae.right)):(nt=Qe>ce,fe=Math.max(0,Ae.top-Q.bottom),_e=Math.abs(Je-ye),rt=Ne(Q.left,Q.right,Ae.left,Ae.right)),!nt)return Number.POSITIVE_INFINITY;const He=rt>0?0:120;return fe*3+_e+He};let $e=null,Ie=Number.POSITIVE_INFINITY;for(const We of P){if(We.id===F.id)continue;const Ae=De(We);Number.isFinite(Ae)&&(Ae>=Ie||(Ie=Ae,$e=We))}return $e||void 0},[]),q=i.useCallback(H=>{var P;const _=ee(H);if(!_)return;const T=_.activePanel||_.panels[0];T&&(_.model.openPanel(T),T.api.setActive(),At(T.id)||ne(T.id,"dockview-focus"),Bn((P=_.element)==null?void 0:P.ownerDocument))},[ee,ne]),X=i.useCallback((H,_)=>{const T=S.current,P=T==null?void 0:T.activePanel,F=(T==null?void 0:T.activeGroup)||(P==null?void 0:P.group);if(!T||!P||!F)return;let Q=ee(H);!Q&&(_!=null&&_.createGroupIfMissing)&&(Q=T.addGroup({referenceGroup:F,direction:H})),Q&&(P.api.moveTo({group:Q,position:"center"}),P.group.model.openPanel(P),P.api.setActive(),At(P.id)||ne(P.id,_!=null&&_.createGroupIfMissing?"dockview-split":"dockview-move"))},[ee,ne]),{isMac:ae,tabShortcuts:je,shortcutListening:ke,setShortcutListening:te,saveShortcuts:E}=bl({sortedTabKeys:e.map(H=>H.tabKey),onFocus:me,onSelectTab:re}),ve=i.useCallback(()=>{var T;const H=S.current;if(!H)return;const _=H.activePanel;if(_){if(At(_.id)){const P=((T=_.params)==null?void 0:T.routeId)||_.id.slice(7),F=_t(e,P);F!=null&&F.tabKey&&te(F.tabKey);return}V.has(_.id)&&te(_.id)}},[V,re,te,e]),Ce=i.useCallback(H=>{const _=[];return H.metaKey&&_.push(ae?"⌘":"Meta"),H.ctrlKey&&_.push("Ctrl"),H.altKey&&_.push(ae?"⌥":"Alt"),H.shiftKey&&H.key.length!==1&&_.push(ae?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(H.key)?null:(_.push(wl(H.key)),_.join("+"))},[ae]),we=i.useCallback(H=>{var _,T;switch(H){case"splitActiveTabRight":X("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":X("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const P=le();P&&J(P);return}case"popoutActiveTab":{const P=le();P&&be(P);return}case"dockActiveTab":{const P=le();if(!P)return;Y(P)?he(P):ue(P)&&Se(P);return}case"focusLeftPane":q("left");return;case"focusRightPane":q("right");return;case"focusUpPane":q("above");return;case"focusDownPane":q("below");return;case"moveActiveTabToLeftPane":X("left");return;case"moveActiveTabToRightPane":X("right");return;case"moveActiveTabToUpPane":X("above");return;case"moveActiveTabToDownPane":X("below");return;case"selectPreviousGroupTab":Z(-1);return;case"selectNextGroupTab":Z(1);return;case"setActiveTabShortcut":ve();return;case"hideCurrentTab":{const P=(T=(_=S.current)==null?void 0:_.activePanel)==null?void 0:T.id;P&&!At(P)&&oe(P);return}default:return}},[Z,Se,q,J,le,oe,ue,Y,he,X,be,ve]);i.useEffect(()=>{if(!N)return;const H=N.sourceDocument,_=H.defaultView??window,T=P=>{const F=H.querySelector("[data-dockview-tab-context-menu]");F&&F.contains(P.target)||A(null)};return _.addEventListener("mousedown",T,!0),_!==window&&window.addEventListener("mousedown",()=>A(null),!0),()=>{_.removeEventListener("mousedown",T,!0),_!==window&&window.removeEventListener("mousedown",()=>A(null),!0)}},[N]);const Pe=i.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:V,hasDetachedConversationPanels:G,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:k,liveSessionInboxState:R,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:oe,userName:m,scrollToBottomRequest:v,tabShortcuts:je,openTabContextMenu:({x:H,y:_,tabKey:T,sourceDocument:P})=>A({x:H,y:_,tabKey:T,sourceDocument:P??document}),popoutTab:be,moveTabBackToMain:he,isTabInPopout:Y,floatTab:J,isTabFloating:ue}),[n,t,V,G,r,c,l,k,R,a,o,oe,m,v,je,be,he,Y,J,ue]),Le=N?Fx({isTabInPopout:Y(N.tabKey),isTabFloating:ue(N.tabKey),tabShortcut:je[N.tabKey],actionShortcuts:h}):[],Oe=i.useCallback(H=>{var P;const _=S.current;if((((P=_==null?void 0:_.activePanel)==null?void 0:P.id)??null)===H.id){H.group.model.openPanel(H);return}H.group.model.openPanel(H),H.api.setActive()},[]),ze=i.useCallback((H,_="requested-tab")=>{if(!H)return!1;const T=S.current;if(!T)return!1;const P=T.getPanel(H);return P?(Oe(P),ne(H,_),b==null||b(),!0):!1},[Oe,b,ne]),tt=i.useCallback(()=>{if(D.current)return!1;const H=ze(U.current,"stored-layout-restore");return H&&(D.current=!0),H},[ze]),Xe=i.useCallback(()=>{var _;const H=S.current;H&&Ch(g,{activeTabId:((_=H.activePanel)==null?void 0:_.id)??null,layout:H.toJSON()})},[g]),Ye=i.useCallback(()=>{Ih(g,B.current)},[g]),mt=i.useCallback(H=>{var P,F,Q,ye;const _=S.current;if(!_)return{kind:"grid"};const T=_.toJSON();for(const ce of T.floatingGroups||[])if((F=(P=ce.data)==null?void 0:P.views)!=null&&F.includes(H)&&ce.position)return{kind:"floating",position:ce.position};for(const ce of T.popoutGroups||[])if((ye=(Q=ce.data)==null?void 0:Q.views)!=null&&ye.includes(H))return{kind:"popout",position:ce.position,popoutUrl:ce.url};return{kind:"grid"}},[]),pt=i.useCallback(H=>{const _=S.current;if(!_)return;const T=_.getPanel(H),P=B.current[H];if(!T||!P||P.kind==="grid")return;if(T.group.model.location.type===P.kind){delete B.current[H],Ye();return}if(P.kind==="floating"){_.addFloatingGroup(T,{x:P.position.left??24,y:P.position.top??24,width:P.position.width,height:P.position.height}),delete B.current[H],Ye();return}delete B.current[H],Ye()},[Ye]);i.useEffect(()=>(f==null||f({setShortcutForActiveTab:ve,restoreHiddenTabToSavedLocation:pt,activateConversationTab:re,resetAllPanelsToMain:ie,activatePreviousTabInGroup:()=>Z(-1),activateNextTabInGroup:()=>Z(1),floatActiveTab:()=>{const H=le();H&&J(H)},popoutActiveTab:()=>{const H=le();H&&be(H)},dockActiveTab:()=>{const H=le();H&&(Y(H)?he(H):ue(H)&&Se(H))},splitActiveTabRight:()=>X("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>X("below",{createGroupIfMissing:!0}),focusLeftPane:()=>q("left"),focusRightPane:()=>q("right"),focusUpPane:()=>q("above"),focusDownPane:()=>q("below"),moveActiveTabToLeftPane:()=>X("left"),moveActiveTabToRightPane:()=>X("right"),moveActiveTabToUpPane:()=>X("above"),moveActiveTabToDownPane:()=>X("below")}),()=>f==null?void 0:f(null)),[Z,Se,J,q,le,ue,Y,X,he,be,f,ie,pt,re,ve]),i.useEffect(()=>()=>{var H;(H=W.current)==null||H.call(W),W.current=null},[]);const dt=i.useCallback(H=>{var T,P;S.current=H.api,(T=W.current)==null||T.call(W),W.current=null;const _=Nh(g);if(U.current=(_==null?void 0:_.activeTabId)??null,_!=null&&_.layout&&H.api.fromJSON(_.layout,{reuseExistingPanels:!1}),I.current=ci({hasStoredLayout:!!(_!=null&&_.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:r}),I.current||(fi(H.api,e),pi(H.api,e,x)),H.api.totalPanels===0&&e.length>0){const F=Jx(H.api,e,y);if(F){const Q=H.api.getPanel(F);Q&&Oe(Q)}}else!I.current&&!ze(y)&&tt();if(L.current=!0,H.api.onDidActivePanelChange(F=>{var ye;if(U.current=(F==null?void 0:F.id)??null,D.current=!0,pe(),F&&At(F.id)){const ce=((ye=F.params)==null?void 0:ye.routeId)||F.id.slice(7),Ne=_t(e,ce);w((Ne==null?void 0:Ne.tabKey)??null),Xe();return}if(w((F==null?void 0:F.id)??null),Xe(),!F)return;const Q=V.get(F.id);(Q==null?void 0:Q.streamSource)==="agent-stream"&&Q.agentType&&C(Q.routeId,pc(),{agentType:Q.agentType,...Q.sessionId&&{targetSessionId:Q.sessionId}}).catch(()=>{})}),H.api.onDidLayoutChange(()=>{Xe(),pe(),$(F=>F+1)}),Gx()){const F=Ie=>({clientX:Ie.clientX,clientY:Ie.clientY}),Q=Ie=>{const Re=Ie==null?void 0:Ie.getBoundingClientRect();return Re?{left:Re.left,right:Re.right,top:Re.top,bottom:Re.bottom}:null},ye=Ie=>{var We;const Re=(We=j.current)==null?void 0:We.getBoundingClientRect();return Re?Ie.clientX<Re.left||Ie.clientX>Re.right||Ie.clientY<Re.top||Ie.clientY>Re.bottom:!1},ce=Vx({detachDelayMs:kl,onDetach:({panelId:Ie,clientX:Re,clientY:We})=>{var rt,nt;const Ae=H.api.getPanel(Ie);if(!Ae)return;try{if(Ae.group.model.location.type!=="grid")return}catch{return}const Je=(rt=j.current)==null?void 0:rt.getBoundingClientRect(),Qe=(nt=Ae.group.element)==null?void 0:nt.getBoundingClientRect(),fe=Math.round(Math.min(Math.max((Qe==null?void 0:Qe.width)??600,360),720)),_e=Math.round(Math.min(Math.max((Qe==null?void 0:Qe.height)??500,260),640));H.api.addFloatingGroup(Ae,{x:Je?Math.max(0,Re-Je.left-32):void 0,y:Je?Math.max(0,We-Je.top-18):void 0,width:fe,height:_e}),Ae.api.setActive(),Xe(),pe(),$(He=>He+1)}}),Ne=[H.api.onWillDragPanel(Ie=>{if(!(Ie.nativeEvent.defaultPrevented||Ie.nativeEvent.shiftKey)){try{if(Ie.panel.group.model.location.type!=="grid")return}catch{return}ce.startDrag({panelId:Ie.panel.id,selfPanelBounds:Q(Ie.panel.group.element),...F(Ie.nativeEvent)})}}),H.api.onWillShowOverlay(Ie=>{if(ce.hasDetached()){Ie.preventDefault();return}ce.markDockTarget(F(Ie.nativeEvent))}),H.api.onWillDrop(Ie=>{if(ce.hasDetached()){Ie.preventDefault(),ce.endDrag();return}ce.markDockTarget(F(Ie.nativeEvent))}),H.api.onDidDrop(()=>ce.endDrag()),H.api.onUnhandledDragOverEvent(Ie=>{ce.isDragging()&&ce.markSelfPanel(F(Ie.nativeEvent))})],De=Ie=>{if(!ce.isDragging())return;const Re=F(Ie);ye(Re)&&ce.markNonSelfPanel(Re)},$e=()=>ce.endDrag();window.addEventListener("dragover",De,!0),window.addEventListener("drop",$e,!0),window.addEventListener("dragend",$e,!0),W.current=()=>{ce.dispose();for(const Ie of Ne)Ie.dispose();window.removeEventListener("dragover",De,!0),window.removeEventListener("drop",$e,!0),window.removeEventListener("dragend",$e,!0)}}H.api.onDidAddGroup(F=>{requestAnimationFrame(()=>{var Q,ye;try{const ce=(Q=F.element)==null?void 0:Q.ownerDocument;if(!ce||ce===document)return;(ye=ce.getElementById("dv-popout-window"))==null||ye.classList.add("adhdev-dockview");const Ne=document.documentElement.getAttribute("data-theme");Ne&&ce.documentElement.setAttribute("data-theme",Ne),ce.body.className=document.body.className;const De=document.documentElement.getAttribute("style");De&&ce.documentElement.setAttribute("style",De)}catch{}pe(),$(ce=>ce+1)})}),w(((P=H.api.activePanel)==null?void 0:P.id)??null)},[Oe,ze,V,r,u,g,w,Xe,y,x,C,pe,e]);i.useLayoutEffect(()=>{const H=S.current;if(!H||!L.current||I.current&&ci({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:r}))return;I.current&&(I.current=!1);const _=K.current,T=new Set(_),P=e.map($e=>$e.tabKey),F=new Set(P),Q=Ux({previousVisibleConversationCount:_.length,visibleConversationCount:e.length,ides:r});let ye=!1;for(const $e of _)F.has($e)||Q||(B.current[$e]=mt($e),ye=!0);ye&&Ye(),Q||(fi(H,e),pi(H,e,x));const ce=P.filter($e=>!T.has($e));let Ne=!1;for(const $e of ce){const Ie=H.getPanel($e),Re=B.current[$e];if(!Ie||!Re||Re.kind==="grid")continue;if(Ie.group.model.location.type===Re.kind){delete B.current[$e],Ne=!0;continue}if(Re.kind==="floating"){H.addFloatingGroup(Ie,{x:Re.position.left??24,y:Re.position.top??24,width:Re.position.width,height:Re.position.height}),delete B.current[$e],Ne=!0;continue}}if(Ne&&Ye(),K.current=P,y&&ze(y))return;!H.activePanel&&H.panels[0]&&Oe(H.panels[0]),!!(H.activePanel&&H.getPanel(H.activePanel.id))||tt()},[Oe,ze,tt,r,u,Ye,mt,y,x,e]),i.useEffect(()=>{L.current&&ze(y)},[ze,y]),i.useEffect(()=>{const H=T=>{const P=T.target;if(!P)return;const F=P.querySelector("[data-tab-key]")||P.closest("[data-tab-key]");if(F){const Q=F.getAttribute("data-tab-key");if(Q&&T.dataTransfer){const ye=P.closest(".dv-tab")||F.closest(".dv-tab")||F;T.dataTransfer.effectAllowed="move",T.dataTransfer.setData("text/tab-key",Q),ye instanceof HTMLElement&&T.dataTransfer.setDragImage(ye,Math.max(12,Math.round(ye.clientWidth/2)),Math.max(10,Math.round(ye.clientHeight/2)))}}};window.addEventListener("dragstart",H);const _=mi(S.current);for(const T of _)T.addEventListener("dragstart",H);return()=>{window.removeEventListener("dragstart",H);for(const T of _)T.removeEventListener("dragstart",H)}},[z]),i.useEffect(()=>{var _;const H=(_=j.current)==null?void 0:_.querySelector(".adhdev-dockview");H instanceof HTMLElement&&Kn(H,M),de(),pe()},[pe,de,M]),i.useEffect(()=>{pe()},[pe]),i.useEffect(()=>{const H=_=>{if(_.defaultPrevented||ke)return;const T=Ce(_);if(!T)return;const P=_.metaKey||_.ctrlKey||_.altKey;va(_.target)&&!P||Qr(ae).setActiveTabShortcut!==T||(_.preventDefault(),_.stopPropagation(),ve())};return window.addEventListener("keydown",H,!0),()=>window.removeEventListener("keydown",H,!0)},[Ce,ae,ke,ve]),i.useEffect(()=>{const H=j.current;if(!H)return;const _=T=>{var ce,Ne;if(!T.isTrusted)return;const P=(Ne=(ce=T.target)==null?void 0:ce.closest)==null?void 0:Ne.call(ce,".dv-scrollable");if(!P)return;T.preventDefault(),T.stopPropagation();const F=Math.abs(T.deltaX),Q=Math.abs(T.deltaY),ye=F>Q?T.deltaX:T.deltaY;P.dispatchEvent(new WheelEvent("wheel",{deltaY:ye,deltaMode:T.deltaMode,bubbles:!1,cancelable:!0}))};return H.addEventListener("wheel",_,{passive:!1,capture:!0}),()=>H.removeEventListener("wheel",_,{capture:!0})},[]),i.useEffect(()=>{const H=mi(S.current);if(H.length===0)return;const _=H.map(T=>{let P=[],F=null;const Q=()=>{F!=null&&T.clearTimeout(F),F=null,P=[]},ye=()=>{F!=null&&T.clearTimeout(F),F=T.setTimeout(()=>{F=null,P=[]},1200)},ce=De=>{if(!De.ctrlKey&&!De.metaKey&&!De.altKey)return;const $e=Ce(De);if(!$e)return;const Ie=xl();for(const[Re,We]of Object.entries(Ie))if(e.some(Ae=>Ae.tabKey===Re)&&We===$e){De.preventDefault(),re(Re);return}},Ne=De=>{if(De.defaultPrevented||ke)return;const $e=Ce(De);if(!$e)return;const Ie=De.metaKey||De.ctrlKey||De.altKey;if(va(De.target))return;const Re=Qr(ae),We=Object.entries(Re).filter(([He,It])=>!!It&&(He==="splitActiveTabRight"||He==="splitActiveTabDown"||He==="floatActiveTab"||He==="popoutActiveTab"||He==="dockActiveTab"||He==="focusLeftPane"||He==="focusRightPane"||He==="focusUpPane"||He==="focusDownPane"||He==="moveActiveTabToLeftPane"||He==="moveActiveTabToRightPane"||He==="moveActiveTabToUpPane"||He==="moveActiveTabToDownPane"||He==="selectPreviousGroupTab"||He==="selectNextGroupTab"||He==="setActiveTabShortcut"||He==="hideCurrentTab")),Ae=Ie?[$e]:[...P.slice(-1),$e].slice(-2),Je=Ae.join(" "),Qe=Ae[Ae.length-1],fe=We.find(([,He])=>He===Je);if(fe){De.preventDefault(),Q(),we(fe[0]);return}if(We.some(([,He])=>He.startsWith(`${Je} `))){De.preventDefault(),P=Ae,ye();return}const rt=We.find(([,He])=>He===Qe);if(rt){De.preventDefault(),Q(),we(rt[0]);return}if(We.some(([,He])=>He.startsWith(`${Qe} `))){De.preventDefault(),P=[Qe],ye();return}Q()};return T.addEventListener("keydown",ce),T.addEventListener("keydown",Ne),()=>{Q(),T.removeEventListener("keydown",ce),T.removeEventListener("keydown",Ne)}});return()=>{for(const T of _)T()}},[Ce,ae,z,re,ke,we,e]);const Te=M==="light"?Qn:Zn,Fe=((ft=(ct=(Ge=S.current)==null?void 0:Ge.activePanel)==null?void 0:ct.group.element)==null?void 0:ft.ownerDocument)??document;return s.jsxs(Sl.Provider,{value:Pe,children:[s.jsx("div",{ref:j,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(hd,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:Qx,remote:Zx},defaultTabComponent:tb,watermarkComponent:eb,onReady:dt,singleTabMode:"default",tabAnimation:"smooth",theme:Te,popoutUrl:"/popout.html"})}),N&&Zs.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:N.x,top:N.y},children:Le.map(H=>{if(H.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},H.id);let _=s.jsx(lu,{size:13,className:"shrink-0 opacity-70"}),T=()=>{};switch(H.id){case"dockInWindow":case"dockBackToGrid":_=s.jsx(uu,{size:13,className:"shrink-0 opacity-70"}),T=()=>{Se(N.tabKey),A(null)};break;case"moveBackToMain":_=s.jsx(cu,{size:13,className:"shrink-0 opacity-70"}),T=()=>{he(N.tabKey),A(null)};break;case"floatAsPanel":_=s.jsx(du,{size:13,className:"shrink-0 opacity-70"}),T=()=>{J(N.tabKey),A(null)};break;case"openInNewWindow":_=s.jsx(iu,{size:13,className:"shrink-0 opacity-70"}),T=()=>{be(N.tabKey),A(null)};break;case"setShortcut":T=P=>{P.stopPropagation(),te(N.tabKey),A(null)};break;case"removeShortcut":_=s.jsx(wt,{size:13,className:"shrink-0 opacity-70"}),T=()=>{const P={...je};delete P[N.tabKey],E(P),A(null)};break;case"hideTab":_=s.jsx(Fi,{size:13,className:"shrink-0 opacity-70"}),T=()=>{oe(N.tabKey),A(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${H.tone==="muted"?"text-text-muted":""}`,onMouseDown:Yx,onClick:T,children:[_,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)})}),N.sourceDocument.body),ke&&Zs.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:()=>te(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. ",ae?"⌘+1":"Ctrl+1",", ",ae?"⌥+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"})]})}),Fe.body)]})}const Nl="adhdev-recent-launch-args-v1",rb=8;function nb(e){return String(e||"").trim().replace(/\s+/g," ")}function Cl(e,t){return`${e.trim()}::${t.trim()}`}function Tl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Nl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function ab(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Nl,JSON.stringify(e))}catch{}}function Il(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=Tl().byKey[Cl(r,n)])==null?void 0:o.items)||[]}function Ml(e,t,r){var d;const n=String(e||"").trim(),a=String(t||"").trim(),o=nb(r);if(!n||!a||!o)return;const c=Tl(),l=Cl(n,a),u=((d=c.byKey[l])==null?void 0:d.items)||[],m=[o,...u.filter(h=>h!==o)].slice(0,rb);c.byKey[l]={items:m},ab(c)}function Al(e){return!e.hasLoadedInitialResults&&!e.isLoading}function $r({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 ob({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 Ll({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:c,onOpenHistory:l,onClearSelection:u}){const m=o?fl(o):null,d=ob({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs($r,{title:"Saved history",description:Ga(),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:lp()})]}),children:[m?s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:m.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:m.providerSessionId}),s.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:u,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:d}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function On(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 Tr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ib({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:c,onListSavedSessions:l}){var H,_;const u=lr(),m=i.useMemo(()=>[...e].sort(Pa),[e]),[d,h]=i.useState(((H=m[0])==null?void 0:H.id)||""),f=i.useMemo(()=>m.find(T=>T.id===d)||m[0],[d,m]),w=i.useMemo(()=>((f==null?void 0:f.workspaces)||[]).map(T=>({id:T.id,path:T.path,label:T.label})),[f]),k=(f==null?void 0:f.defaultWorkspaceId)||null,[p,y]=i.useState(""),[x,b]=i.useState(""),[v,R]=i.useState(On(m[0])),[g,M]=i.useState(""),[C,S]=i.useState(""),[j,W]=i.useState([]),[L,I]=i.useState(""),[D,U]=i.useState([]),[K,N]=i.useState(!1),[A,z]=i.useState(!1),[$,B]=i.useState(""),[V,G]=i.useState(!1),[me,ne]=i.useState(()=>ht()),[xe,de]=i.useState(null),[be,he]=i.useState(!1),[Y,oe]=i.useState(""),[J,ue]=i.useState(!1),[le,Se]=i.useState(""),[ie,pe]=i.useState([]),[re,Z]=i.useState(!1),[ee,q]=i.useState(""),[X,ae]=i.useState(!1),je=i.useRef(null),ke=i.useRef(0);i.useEffect(()=>{var T;!d&&((T=m[0])!=null&&T.id)&&h(m[0].id)},[d,m]),i.useEffect(()=>{!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||u(f.id,{minFreshMs:3e4}).catch(()=>{})},[u,f]);const te=i.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(T=>ps(T,"cli")),[f]),E=i.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(T=>ps(T,"acp")),[f]),ve=i.useMemo(()=>((f==null?void 0:f.detectedIdes)||[]).map(T=>({id:T.type,label:T.name||T.type,meta:T.running?"Detected locally":"Available to open"})),[f]),Ce=i.useMemo(()=>v==="cli"?te.map(T=>({id:T.type,label:T.displayName||T.type,meta:"CLI provider"})):v==="acp"?E.map(T=>({id:T.type,label:T.displayName||T.type,meta:"ACP provider"})):ve,[E,v,te,ve]);i.useEffect(()=>{var P;if(!f)return;if(je.current!==f.id){je.current=f.id,y(k||((P=w[0])==null?void 0:P.id)||"__home__"),b(""),R(On(f)),M(""),S(""),I(""),U([]),z(!1),B(""),ne(ht()),oe("");return}y(F=>{var Q;return F==="__custom__"||F==="__home__"||w.some(ye=>ye.id===F)?F:k||((Q=w[0])==null?void 0:Q.id)||"__home__"}),R(F=>F==="ide"&&ve.length>0||F==="cli"&&te.length>0||F==="acp"&&E.length>0?F:On(f))},[E.length,te.length,k,ve.length,f,w]),i.useEffect(()=>{var T;v&&(Ce.some(P=>P.id===g)||M(((T=Ce[0])==null?void 0:T.id)||""))},[v,Ce,g]);const we=i.useCallback(async(T,P)=>{const F=ke.current+1;return ke.current=F,N(!0),B(""),l(T,P).then(Q=>{ke.current===F&&U(Q)}).catch(Q=>{ke.current===F&&(U([]),B(Q instanceof Error?Q.message:"Could not load saved sessions"))}).finally(()=>{ke.current===F&&(N(!1),z(!0))})},[l]),Pe=i.useCallback((T,P)=>{W(Il(T,P))},[]);i.useEffect(()=>{ke.current+=1,I(""),ne(ht()),!f||!g||v==="ide"?W([]):Pe(f.id,g),z(!1),U([]),B(""),N(!1)},[v,Pe,we,f,g]),i.useEffect(()=>{if(!L)return;const T=D.find(P=>P.providerSessionId===L);T!=null&&T.canResume||I("")},[D,L]);const Le=p==="__custom__"?x.trim():p==="__home__"?"":((_=w.find(T=>T.id===p))==null?void 0:_.path)||"",Oe=i.useMemo(()=>f?t.filter(T=>T.id!==f.id&&T.daemonId===f.id).map(T=>T.workspace):[],[t,f]),ze=i.useMemo(()=>((f==null?void 0:f.recentLaunches)||[]).map(T=>T.workspace),[f]),tt=i.useCallback(T=>{const P=String(T.workspace||"").trim();if(!P)return;const F=w.find(Q=>Tr(Q.path)===Tr(P));if(F){y(F.id),b("");return}y("__custom__"),b(P)},[w]),Xe=i.useCallback(T=>{const P=String(T.workspace||"").trim();if(!P)return{workspaceId:null,workspacePath:null};const F=w.find(Q=>Tr(Q.path)===Tr(P));return F?{workspaceId:F.id,workspacePath:null}:{workspaceId:null,workspacePath:P}},[w]),Ye=i.useMemo(()=>D.find(T=>T.providerSessionId===L)||null,[D,L]),mt=i.useMemo(()=>{var P;if(v!=="cli"||!f||!g)return null;const T=((P=te.find(F=>F.type===g))==null?void 0:P.displayName)||g;return{routeId:f.id,daemonId:f.id,providerSessionId:L||void 0,transport:"pty",mode:"chat",agentName:T,agentType:g,status:"idle",title:T,messages:[],ideType:g,workspaceName:Le,workspacePath:Le,displayPrimary:T,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${f.id}:${g}`,machineName:St(f,{fallbackId:f.id})}},[v,te,Le,f,L,g]),pt=i.useCallback(()=>{var P;if(!f)return;y("__custom__"),ue(!0),q("");const T=dn(f.platform,ln(x.trim(),Le,Oe,ze,f.defaultWorkspacePath,(P=w.find(F=>F.id===k))==null?void 0:P.path,w.map(F=>F.path)));Z(!0),n(f.id,T).then(F=>{Se(F.path),b(F.path),pe(F.directories)}).catch(F=>{q(F instanceof Error?F.message:"Could not load folder")}).finally(()=>Z(!1))},[x,k,ze,Oe,n,Le,f,w]),dt=i.useCallback(T=>{f&&(Z(!0),q(""),n(f.id,T).then(P=>{Se(P.path),b(P.path),pe(P.directories)}).catch(P=>{q(P instanceof Error?P.message:"Could not load folder")}).finally(()=>Z(!1)))},[n,f]),Te=i.useCallback(async()=>{if(!f||!Le)return;ae(!0),oe("");const T=await a(f.id,Le);if(ae(!1),!T.ok){oe(T.error||"Could not save workspace");return}oe("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,Le,f]),Fe=i.useCallback(async()=>{if(!f||!v||!g)return;he(!0),oe("");const T=C.trim()?C.trim().split(/\s+/).filter(Boolean):[],P=v==="ide"?await o(f.id,g,{workspacePath:Le||null}):await c(f.id,v,g,{workspaceId:p!=="__home__"&&p!=="__custom__"?p:null,workspacePath:p==="__custom__"&&Le||null,resumeSessionId:v==="cli"&&L?L:null,cliArgs:T});if(he(!1),!P.ok){oe(P.error||"Could not start session");return}v!=="ide"&&C.trim()&&(Ml(f.id,g,C),Pe(f.id,g)),r()},[v,C,Pe,r,o,c,Le,f,L,g,p]),Ge=v?Ec(v,v==="cli"&&!!L):"Start",ct=v?$c(v,v==="cli"&&!!L):"Starting…",ft=m.length>5;return f?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(wt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[s.jsx($r,{title:"Machine",children:ft?s.jsx("select",{"aria-label":"Machine",value:f.id,onChange:T=>h(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:be,children:m.map(T=>s.jsx("option",{value:T.id,children:St(T,{fallbackId:T.id})},T.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:m.map(T=>{const P=St(T,{fallbackId:T.id}),F=f.id===T.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${P}`,"aria-pressed":F,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${F?"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:()=>h(T.id),disabled:be,title:P,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${T.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:P})]},T.id)})})}),s.jsxs($r,{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:pt,disabled:be,children:"Browse…"}),children:[s.jsxs("select",{value:p,onChange:T=>{const P=T.target.value;y(P),P==="__custom__"?pt():oe("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:be,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),w.map(T=>s.jsxs("option",{value:T.id,children:[T.id===k?"⭐ ":"",nn(T.path,T.label)||T.path]},T.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:p==="__home__"?"Launch without a workspace.":Le||"Select a workspace folder."}),p==="__custom__"&&Le&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:pt,disabled:be,children:[s.jsx(Ns,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Te,disabled:be||X,children:X?"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:te.length>0},{id:"ide",label:"IDE",enabled:ve.length>0},{id:"acp",label:"ACP",enabled:E.length>0}].map(T=>s.jsx("button",{type:"button",className:`btn btn-sm ${v===T.id?"btn-primary":"btn-secondary"}`,onClick:()=>R(T.id),disabled:!T.enabled||be,children:T.label},T.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:[Ce.map(T=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${g===T.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>M(T.id),disabled:be,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:T.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:T.meta})]},T.id)),Ce.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($r,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:C,onChange:T=>S(T.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:be}),j.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:j.map(T=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>S(T),disabled:be,title:T,children:T},T))})]}),v==="cli"&&s.jsx(Ll,{busy:be,savedSessionsLoading:K,savedSessionsError:$,selectedSession:Ye,onRefresh:()=>{!f||!g||we(f.id,g)},onOpenHistory:()=>{!f||!g||(G(!0),Al({hasLoadedInitialResults:A,isLoading:K})&&we(f.id,g))},onClearSelection:()=>I("")}),Y&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${Y.includes("saved")||Y.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:Y})]}),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:be,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:Fe,disabled:be||!v||!g||p==="__custom__"&&!Le,children:[s.jsx(Aa,{size:14}),be?ct:Ge]})]})]})}),J&&s.jsx(mn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:le,directories:ie,busy:re,error:ee,onClose:()=>ue(!1),onNavigate:dt,onConfirm:T=>{b(T),Se(T),y("__custom__"),ue(!1)}}),V&&mt&&s.jsx(Xa,{activeConv:mt,ides:[],isCreatingChat:!1,isRefreshingHistory:K,savedSessions:D,isSavedSessionsLoading:K,isResumingSavedSessionId:xe,savedHistoryFilters:me,missingWorkspaceResumePath:Le||null,onSavedHistoryFiltersChange:ne,onClose:()=>G(!1),onNewChat:()=>{I(""),G(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!f||!g||we(f.id,g)},onResumeSavedSession:T=>{if(!f||!g||xe||!T.canResume)return;const P=Xe(T);I(T.providerSessionId),tt(T),de(T.providerSessionId),G(!1),he(!0),oe(""),c(f.id,"cli",g,{workspaceId:P.workspaceId,workspacePath:P.workspacePath,resumeSessionId:T.providerSessionId}).then(F=>{if(!F.ok){oe(F.error||"Could not resume session");return}r()}).finally(()=>{he(!1),de(F=>F===T.providerSessionId?null:F)})}})]}):null}function cb({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=i.useState(!1),[o,c]=i.useState(!1),[l,u]=i.useState(!1),[m,d]=i.useState(!1),[h,f]=i.useState(!1),[w,k]=i.useState("quickstart"),[p,y]=i.useState("workspace"),x=i.useMemo(()=>!t&&!e,[t,e]),b=i.useCallback(S=>{a(S),S&&c(!1)},[]),v=i.useCallback(S=>{c(S),S&&a(!1)},[]),R=i.useCallback(()=>{k(r===0?"quickstart":"shortcuts"),y("workspace"),u(!0),a(!1),c(!1)},[r]),g=i.useCallback(()=>{u(!1)},[]),M=i.useCallback(()=>{d(!0)},[]),C=i.useCallback(()=>{d(!1)},[]);return i.useEffect(()=>{if(!x){f(!1);return}f(!0);const S=window.setTimeout(()=>{f(!1)},1e4);return()=>window.clearTimeout(S)},[x]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:l,newSessionOpen:m,guideNudgeVisible:h,guideTab:w,shortcutSection:p,isDesktopDashboard:x,setGuideTab:k,setShortcutSection:y,handleInboxOpenChange:b,handleHiddenOpenChange:v,handleOpenShortcutHelp:R,closeShortcutHelp:g,openNewSession:M,closeNewSession:C}}function lb(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 db(e){return e instanceof Error?e.message:String(e||"")}function ub(e){const t=db(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function mb({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetActiveCliViewMode:m,mobileChatConversations:d,hiddenConversations:h,ides:f,actionLogs:w,sendDaemonCommand:k,setActionLogs:p,setCliViewModeOverrides:y,isStandalone:x,initialDataLoaded:b,userName:v,requestedMobileTabKey:R,onRequestedMobileTabConsumed:g,requestedMachineId:M,onRequestedMachineConsumed:C,requestedMobileSection:S,onRequestedMobileSectionConsumed:j,containerRef:W,isSplitMode:L,numGroups:I,groupSizes:D,groupedConvs:U,clearedTabs:K,focusedGroup:N,focusGroup:A,moveTabToGroup:z,splitTabRelative:$,closeGroup:B,handleResizeStart:V,groupActiveTabIds:G,setGroupActiveTab:me,groupTabOrders:ne,setGroupTabOrder:xe,toggleHiddenTab:de,visibleConversations:be,requestedDesktopTabKey:he,onRequestedDesktopTabConsumed:Y,onDesktopActiveTabChange:oe,onRequestScrollToBottom:J,onHideConversation:ue,onShowHiddenConversation:le,onShowAllHiddenConversations:Se,scrollToBottomRequest:ie,machineEntries:pe,layoutProfile:re,onBrowseMachineDirectory:Z,onSaveMachineWorkspace:ee,onLaunchMachineIde:q,onLaunchMachineProvider:X,onListMachineSavedSessions:ae,notifications:je,notificationUnreadCount:ke,liveSessionInboxState:te,onMarkNotificationRead:E,onMarkNotificationUnread:ve,onDeleteNotification:Ce}){const we=jt.useRef(null),{inboxOpen:Pe,hiddenOpen:Le,shortcutHelpOpen:Oe,newSessionOpen:ze,guideNudgeVisible:tt,guideTab:Xe,shortcutSection:Ye,isDesktopDashboard:mt,setGuideTab:pt,setShortcutSection:dt,handleInboxOpenChange:Te,handleHiddenOpenChange:Fe,handleOpenShortcutHelp:Ge,closeShortcutHelp:ct,openNewSession:ft,closeNewSession:H}=cb({isMobile:t,showMobileChatMode:e,visibleConversationCount:be.length}),_=jt.useCallback(fe=>{var _e;Zs.flushSync(()=>{le(fe)}),(_e=we.current)==null||_e.restoreHiddenTabToSavedLocation(fe.tabKey)},[le]),T=jt.useCallback(fe=>{var rt;const _e=d.find(nt=>ca(nt,fe))||h.find(nt=>ca(nt,fe));_e&&(h.some(nt=>nt.tabKey===_e.tabKey)&&_(_e),oe(_e.tabKey),(rt=we.current)==null||rt.activateConversationTab(_e.tabKey),J(_e.tabKey,"notification-open")),E(fe.id),Te(!1)},[_,h,d,oe,E,J]),P=jt.useCallback(()=>{var _e;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((_e=we.current)==null||_e.resetAllPanelsToMain(),Fe(!1))},[Fe]),F=jt.useCallback(async fe=>{var It;if(!r)return;const _e=(It=r.modalButtons)==null?void 0:It[fe];if(!_e)return;const rt=Ts(r);if(!rt)return;const nt=_e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),He=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(nt);try{await k(rt,"resolve_action",{button:_e,action:He?"approve":"reject",buttonIndex:fe,...es(r)})}catch(O){ub(O)||console.error("[Shortcut approval] Failed:",O)}},[r,k]),{isMac:Q,actionDefinitions:ye,actionShortcuts:ce,shortcutListening:Ne,shortcutListeningDraft:De,setShortcutListening:$e,setShortcutListeningDraft:Ie,saveShortcuts:Re}=Hx({enabled:mt&&!Oe,onTrigger:fe=>{var _e,rt,nt,He,It,O,se,ge,Be,Me,Ee,at,yt,ut,Ut,ur;if(fe==="openShortcutHelp"){Ge();return}if(fe==="openNewSession"){ft();return}if(fe==="hideCurrentTab"){r&&ue(r);return}if(fe==="toggleHiddenTabs"){Fe(!Le);return}if(fe==="openHistoryForActiveTab"){r&&!qe(r)&&o(r);return}if(fe==="openRemoteForActiveTab"){r&&!Ze(r)&&!qe(r)&&c(r);return}if(fe==="splitActiveTabRight"){(_e=we.current)==null||_e.splitActiveTabRight();return}if(fe==="splitActiveTabDown"){(rt=we.current)==null||rt.splitActiveTabDown();return}if(fe==="floatActiveTab"){(nt=we.current)==null||nt.floatActiveTab();return}if(fe==="popoutActiveTab"){(He=we.current)==null||He.popoutActiveTab();return}if(fe==="dockActiveTab"){(It=we.current)==null||It.dockActiveTab();return}if(fe==="focusLeftPane"){(O=we.current)==null||O.focusLeftPane();return}if(fe==="focusRightPane"){(se=we.current)==null||se.focusRightPane();return}if(fe==="focusUpPane"){(ge=we.current)==null||ge.focusUpPane();return}if(fe==="focusDownPane"){(Be=we.current)==null||Be.focusDownPane();return}if(fe==="moveActiveTabToLeftPane"){(Me=we.current)==null||Me.moveActiveTabToLeftPane();return}if(fe==="moveActiveTabToRightPane"){(Ee=we.current)==null||Ee.moveActiveTabToRightPane();return}if(fe==="moveActiveTabToUpPane"){(at=we.current)==null||at.moveActiveTabToUpPane();return}if(fe==="moveActiveTabToDownPane"){(yt=we.current)==null||yt.moveActiveTabToDownPane();return}if(fe==="triggerPrimaryApprovalAction"){F(0);return}if(fe==="triggerSecondaryApprovalAction"){F(1);return}if(fe==="triggerTertiaryApprovalAction"){F(2);return}if(fe==="setActiveTabShortcut"){(ut=we.current)==null||ut.setShortcutForActiveTab();return}if(fe==="selectPreviousGroupTab"){(Ut=we.current)==null||Ut.activatePreviousTabInGroup();return}if(fe==="selectNextGroupTab"){(ur=we.current)==null||ur.activateNextTabInGroup();return}!r||!Ze(r)||qe(r)||fe==="toggleCliView"&&m(u==="chat"?"terminal":"chat")}}),We=jt.useCallback(()=>{ct(),$e(null),Ie([])},[ct,$e,Ie]),Ae=jt.useMemo(()=>Ye==="all"?ye:ye.filter(fe=>lb(fe)===Ye),[ye,Ye]),Je=jt.useCallback(()=>{const fe=Object.fromEntries(ye.map(_e=>[_e.id,""]));Re(fe)},[ye,Re]),Qe=jt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const fe=Object.fromEntries(ye.map(_e=>[_e.id,_e.defaultShortcut]));Re(fe)},[ye,Re]);return jt.useEffect(()=>{const fe=_e=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?_e.metaKey&&_e.key.toLowerCase()==="w":_e.ctrlKey&&_e.key.toLowerCase()==="w")&&(_e.preventDefault(),r&&ue&&ue(r))};return window.addEventListener("keydown",fe),()=>window.removeEventListener("keydown",fe)},[r,ue]),jt.useEffect(()=>{if(!Oe||Ne)return;const fe=_e=>{_e.key==="Escape"&&(_e.preventDefault(),We())};return window.addEventListener("keydown",fe,!0),()=>window.removeEventListener("keydown",fe,!0)},[We,Oe,Ne]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(rp,{activeConv:r,wsStatus:n,isConnected:a,conversations:be,hiddenConversations:h,onOpenHistory:o,onHideConversation:ue,onShowConversation:_,onShowAllHidden:Se,onResetPanelsToMain:P,notifications:je,notificationUnreadCount:ke,onOpenNotification:T,onMarkNotificationRead:E,onMarkNotificationUnread:ve,onDeleteNotification:Ce,inboxOpen:Pe,onInboxOpenChange:Te,hiddenOpen:Le,onHiddenOpenChange:Fe,onOpenNewSession:t?void 0:ft,onOpenDashboardGuide:Ge,guideNudgeVisible:tt,actionShortcuts:ce,onOpenRemote:()=>{!r||Ze(r)||qe(r)||c(r)},onStopCli:l,activeCliViewMode:u,onSetCliViewMode:m}),e?s.jsx(Ax,{conversations:d,hiddenConversations:h,ides:f,actionLogs:w,sendDaemonCommand:k,setActionLogs:p,setCliViewModeOverrides:y,isStandalone:x,userName:v,requestedActiveTabKey:R,onRequestedActiveTabConsumed:g,requestedMachineId:M,onRequestedMachineConsumed:C,requestedMobileSection:S,onRequestedMobileSectionConsumed:j,onOpenHistory:o,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowHiddenConversation:_,onShowAllHiddenConversations:Se,onOpenNewSession:ft,liveSessionInboxState:te}):t?s.jsx(Bx,{containerRef:W,isSplitMode:L,numGroups:I,groupSizes:D,groupedConvs:U,clearedTabs:K,ides:f,actionLogs:w,sendDaemonCommand:k,setActionLogs:p,isStandalone:x,hasRegisteredMachines:pe.length>0,userName:v,focusedGroup:N,focusGroup:A,moveTabToGroup:z,splitTabRelative:$,closeGroup:B,handleResizeStart:V,groupActiveTabIds:G,setGroupActiveTab:me,groupTabOrders:ne,setGroupTabOrder:xe,toggleHiddenTab:de,onOpenNewSession:ft,allowTabShortcuts:!1,liveSessionInboxState:te}):s.jsx(sb,{visibleConversations:be,clearedTabs:K,ides:f,actionLogs:w,sendDaemonCommand:k,setActionLogs:p,isStandalone:x,hasRegisteredMachines:pe.length>0,initialDataLoaded:b,userName:v,toggleHiddenTab:de,actionShortcuts:ce,registerActionHandlers:fe=>{we.current=fe},onActiveTabChange:oe,requestedActiveTabKey:he,onRequestedActiveTabConsumed:Y,onRequestScrollToBottom:J,scrollToBottomRequest:ie,onOpenNewSession:ft,liveSessionInboxState:te,layoutProfile:re}),ze&&s.jsx(ib,{machines:pe,ides:f,onClose:H,onBrowseDirectory:Z,onSaveWorkspace:ee,onLaunchIde:q,onLaunchProvider:X,onListSavedSessions:ae}),Oe&&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:We,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:fe=>fe.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:We,"aria-label":"Close dashboard guide",children:s.jsx(wt,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(fe=>s.jsx("button",{type:"button",className:`btn btn-sm ${Xe===fe.id?"btn-primary":"btn-secondary"}`,onClick:()=>pt(fe.id),children:fe.label},fe.id))}),Xe==="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 ",Q?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Xe==="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."]})]})]})]}),Xe==="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(fe=>s.jsx("button",{type:"button",className:`btn btn-sm ${Ye===fe.id?"btn-primary":"btn-secondary"}`,onClick:()=>dt(fe.id),children:fe.label},fe.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Je,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:Qe,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Ae.map(fe=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ne===fe.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:fe.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:fe.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:fe.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===fe.id?De.length>0?`${De.join(" ")} ...`:"Listening...":ce[fe.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{$e(fe.id),Ie([])},children:Ne===fe.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const _e={...ce};_e[fe.id]="",Re(_e)},children:"Disable"})]})]})},fe.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Q?"⌘⇧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 Wn=[{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 fb({onClose:e}){const[t,r]=i.useState(0),n=Wn[t],a=t===Wn.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:o=>{o.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(wt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Wn.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
+ `,Q.style.top="52px",Q.style.height="calc(100% - 52px)";const Re=Me.querySelector("[data-adhdev-popout-focus]");Re&&(Re.onclick=()=>{window.focus()});const We=Me.querySelector("[data-adhdev-popout-dock]");We&&(We.disabled=!ye,We.style.opacity=ye?"1":"0.5",We.style.cursor=ye?"pointer":"default",We.onclick=()=>{var Ae;ye&&he(ye),(Ae=F.defaultView)==null||Ae.focus()})}},[G,he]),ne=i.useCallback(H=>{var P;const _=S.current,T=_==null?void 0:_.getPanel(H);if(!(!_||!T)){T.group.model.openPanel(T),T.api.setActive(),ae(H,"dockview-shortcut");try{const F=T.group.model.location;F.type==="popout"?F.getWindow().focus():Kn((P=T.group.element)==null?void 0:P.ownerDocument)}catch{}}},[ae]),Z=i.useCallback(H=>{const _=S.current,T=_==null?void 0:_.activePanel,P=(_==null?void 0:_.activeGroup)||(T==null?void 0:T.group);if(!_||!T||!P)return;const F=P.panels||[];if(F.length<=1)return;const Q=F.findIndex(Ne=>Ne.id===T.id);if(Q<0)return;const ye=(Q+H+F.length)%F.length,ce=F[ye];ce&&(ce.group.model.openPanel(ce),ce.api.setActive(),At(ce.id)||ae(ce.id,"dockview-shortcut"))},[ae]),ee=i.useCallback(H=>{var Re;const _=S.current,T=(_==null?void 0:_.activeGroup)||((Re=_==null?void 0:_.activePanel)==null?void 0:Re.group);if(!_||!T)return;const P=_.groups||[],F=P.find(We=>We.id===T.id);if(!F)return;const Q=F.element.getBoundingClientRect(),ye=Q.left+Q.width/2,ce=Q.top+Q.height/2,Ne=(We,Ae,Je,Qe)=>Math.max(0,Math.min(Ae,Qe)-Math.max(We,Je)),De=We=>{const Ae=We.element.getBoundingClientRect(),Je=Ae.left+Ae.width/2,Qe=Ae.top+Ae.height/2;let fe=0,_e=0,rt=0,nt=!1;if(H==="left"?(nt=Je<ye,fe=Math.max(0,Q.left-Ae.right),_e=Math.abs(Qe-ce),rt=Ne(Q.top,Q.bottom,Ae.top,Ae.bottom)):H==="right"?(nt=Je>ye,fe=Math.max(0,Ae.left-Q.right),_e=Math.abs(Qe-ce),rt=Ne(Q.top,Q.bottom,Ae.top,Ae.bottom)):H==="above"?(nt=Qe<ce,fe=Math.max(0,Q.top-Ae.bottom),_e=Math.abs(Je-ye),rt=Ne(Q.left,Q.right,Ae.left,Ae.right)):(nt=Qe>ce,fe=Math.max(0,Ae.top-Q.bottom),_e=Math.abs(Je-ye),rt=Ne(Q.left,Q.right,Ae.left,Ae.right)),!nt)return Number.POSITIVE_INFINITY;const He=rt>0?0:120;return fe*3+_e+He};let $e=null,Me=Number.POSITIVE_INFINITY;for(const We of P){if(We.id===F.id)continue;const Ae=De(We);Number.isFinite(Ae)&&(Ae>=Me||(Me=Ae,$e=We))}return $e||void 0},[]),q=i.useCallback(H=>{var P;const _=ee(H);if(!_)return;const T=_.activePanel||_.panels[0];T&&(_.model.openPanel(T),T.api.setActive(),At(T.id)||ae(T.id,"dockview-focus"),Kn((P=_.element)==null?void 0:P.ownerDocument))},[ee,ae]),X=i.useCallback((H,_)=>{const T=S.current,P=T==null?void 0:T.activePanel,F=(T==null?void 0:T.activeGroup)||(P==null?void 0:P.group);if(!T||!P||!F)return;let Q=ee(H);!Q&&(_!=null&&_.createGroupIfMissing)&&(Q=T.addGroup({referenceGroup:F,direction:H})),Q&&(P.api.moveTo({group:Q,position:"center"}),P.group.model.openPanel(P),P.api.setActive(),At(P.id)||ae(P.id,_!=null&&_.createGroupIfMissing?"dockview-split":"dockview-move"))},[ee,ae]),{isMac:re,tabShortcuts:je,shortcutListening:we,setShortcutListening:te,saveShortcuts:D}=vl({sortedTabKeys:e.map(H=>H.tabKey),onFocus:me,onSelectTab:ne}),ve=i.useCallback(()=>{var T;const H=S.current;if(!H)return;const _=H.activePanel;if(_){if(At(_.id)){const P=((T=_.params)==null?void 0:T.routeId)||_.id.slice(7),F=_t(e,P);F!=null&&F.tabKey&&te(F.tabKey);return}G.has(_.id)&&te(_.id)}},[G,ne,te,e]),Ce=i.useCallback(H=>{const _=[];return H.metaKey&&_.push(re?"⌘":"Meta"),H.ctrlKey&&_.push("Ctrl"),H.altKey&&_.push(re?"⌥":"Alt"),H.shiftKey&&H.key.length!==1&&_.push(re?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(H.key)?null:(_.push(Sl(H.key)),_.join("+"))},[re]),ke=i.useCallback(H=>{var _,T;switch(H){case"splitActiveTabRight":X("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":X("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const P=le();P&&J(P);return}case"popoutActiveTab":{const P=le();P&&be(P);return}case"dockActiveTab":{const P=le();if(!P)return;Y(P)?he(P):ue(P)&&Se(P);return}case"focusLeftPane":q("left");return;case"focusRightPane":q("right");return;case"focusUpPane":q("above");return;case"focusDownPane":q("below");return;case"moveActiveTabToLeftPane":X("left");return;case"moveActiveTabToRightPane":X("right");return;case"moveActiveTabToUpPane":X("above");return;case"moveActiveTabToDownPane":X("below");return;case"selectPreviousGroupTab":Z(-1);return;case"selectNextGroupTab":Z(1);return;case"setActiveTabShortcut":ve();return;case"hideCurrentTab":{const P=(T=(_=S.current)==null?void 0:_.activePanel)==null?void 0:T.id;P&&!At(P)&&oe(P);return}default:return}},[Z,Se,q,J,le,oe,ue,Y,he,X,be,ve]);i.useEffect(()=>{if(!N)return;const H=N.sourceDocument,_=H.defaultView??window,T=P=>{const F=H.querySelector("[data-dockview-tab-context-menu]");F&&F.contains(P.target)||A(null)};return _.addEventListener("mousedown",T,!0),_!==window&&window.addEventListener("mousedown",()=>A(null),!0),()=>{_.removeEventListener("mousedown",T,!0),_!==window&&window.removeEventListener("mousedown",()=>A(null),!0)}},[N]);const Pe=i.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:G,hasDetachedConversationPanels:V,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:j,liveSessionInboxState:R,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:oe,userName:m,scrollToBottomRequest:w,tabShortcuts:je,openTabContextMenu:({x:H,y:_,tabKey:T,sourceDocument:P})=>A({x:H,y:_,tabKey:T,sourceDocument:P??document}),popoutTab:be,moveTabBackToMain:he,isTabInPopout:Y,floatTab:J,isTabFloating:ue}),[n,t,G,V,r,c,l,j,R,a,o,oe,m,w,je,be,he,Y,J,ue]),Le=N?eb({isTabInPopout:Y(N.tabKey),isTabFloating:ue(N.tabKey),tabShortcut:je[N.tabKey],actionShortcuts:h}):[],Oe=i.useCallback(H=>{var P;const _=S.current;if((((P=_==null?void 0:_.activePanel)==null?void 0:P.id)??null)===H.id){H.group.model.openPanel(H);return}H.group.model.openPanel(H),H.api.setActive()},[]),ze=i.useCallback((H,_="requested-tab")=>{if(!H)return!1;const T=S.current;if(!T)return!1;const P=T.getPanel(H);return P?(Oe(P),ae(H,_),b==null||b(),!0):!1},[Oe,b,ae]),tt=i.useCallback(()=>{if(E.current)return!1;const H=ze(U.current,"stored-layout-restore");return H&&(E.current=!0),H},[ze]),Xe=i.useCallback(()=>{var _;const H=S.current;H&&$h(g,{activeTabId:((_=H.activePanel)==null?void 0:_.id)??null,layout:H.toJSON()})},[g]),Ye=i.useCallback(()=>{Kh(g,B.current)},[g]),mt=i.useCallback(H=>{var P,F,Q,ye;const _=S.current;if(!_)return{kind:"grid"};const T=_.toJSON();for(const ce of T.floatingGroups||[])if((F=(P=ce.data)==null?void 0:P.views)!=null&&F.includes(H)&&ce.position)return{kind:"floating",position:ce.position};for(const ce of T.popoutGroups||[])if((ye=(Q=ce.data)==null?void 0:Q.views)!=null&&ye.includes(H))return{kind:"popout",position:ce.position,popoutUrl:ce.url};return{kind:"grid"}},[]),pt=i.useCallback(H=>{const _=S.current;if(!_)return;const T=_.getPanel(H),P=B.current[H];if(!T||!P||P.kind==="grid")return;if(T.group.model.location.type===P.kind){delete B.current[H],Ye();return}if(P.kind==="floating"){_.addFloatingGroup(T,{x:P.position.left??24,y:P.position.top??24,width:P.position.width,height:P.position.height}),delete B.current[H],Ye();return}delete B.current[H],Ye()},[Ye]);i.useEffect(()=>(f==null||f({setShortcutForActiveTab:ve,restoreHiddenTabToSavedLocation:pt,activateConversationTab:ne,resetAllPanelsToMain:ie,activatePreviousTabInGroup:()=>Z(-1),activateNextTabInGroup:()=>Z(1),floatActiveTab:()=>{const H=le();H&&J(H)},popoutActiveTab:()=>{const H=le();H&&be(H)},dockActiveTab:()=>{const H=le();H&&(Y(H)?he(H):ue(H)&&Se(H))},splitActiveTabRight:()=>X("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>X("below",{createGroupIfMissing:!0}),focusLeftPane:()=>q("left"),focusRightPane:()=>q("right"),focusUpPane:()=>q("above"),focusDownPane:()=>q("below"),moveActiveTabToLeftPane:()=>X("left"),moveActiveTabToRightPane:()=>X("right"),moveActiveTabToUpPane:()=>X("above"),moveActiveTabToDownPane:()=>X("below")}),()=>f==null?void 0:f(null)),[Z,Se,J,q,le,ue,Y,X,he,be,f,ie,pt,ne,ve]),i.useEffect(()=>()=>{var H;(H=W.current)==null||H.call(W),W.current=null},[]);const dt=i.useCallback(H=>{var T,P;S.current=H.api,(T=W.current)==null||T.call(W),W.current=null;const _=Eh(g);if(U.current=(_==null?void 0:_.activeTabId)??null,_!=null&&_.layout&&H.api.fromJSON(_.layout,{reuseExistingPanels:!1}),M.current=li({hasStoredLayout:!!(_!=null&&_.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:r}),M.current||(pi(H.api,e),hi(H.api,e,x)),H.api.totalPanels===0&&e.length>0){const F=cb(H.api,e,y);if(F){const Q=H.api.getPanel(F);Q&&Oe(Q)}}else!M.current&&!ze(y)&&tt();if(L.current=!0,H.api.onDidActivePanelChange(F=>{var ye;if(U.current=(F==null?void 0:F.id)??null,E.current=!0,pe(),F&&At(F.id)){const ce=((ye=F.params)==null?void 0:ye.routeId)||F.id.slice(7),Ne=_t(e,ce);v((Ne==null?void 0:Ne.tabKey)??null),Xe();return}if(v((F==null?void 0:F.id)??null),Xe(),!F)return;const Q=G.get(F.id);(Q==null?void 0:Q.streamSource)==="agent-stream"&&Q.agentType&&C(Q.routeId,hc(),{agentType:Q.agentType,...Q.sessionId&&{targetSessionId:Q.sessionId}}).catch(()=>{})}),H.api.onDidLayoutChange(()=>{Xe(),pe(),$(F=>F+1)}),nb()){const F=Me=>({clientX:Me.clientX,clientY:Me.clientY}),Q=Me=>{const Re=Me==null?void 0:Me.getBoundingClientRect();return Re?{left:Re.left,right:Re.right,top:Re.top,bottom:Re.bottom}:null},ye=Me=>{var We;const Re=(We=k.current)==null?void 0:We.getBoundingClientRect();return Re?Me.clientX<Re.left||Me.clientX>Re.right||Me.clientY<Re.top||Me.clientY>Re.bottom:!1},ce=rb({detachDelayMs:Cl,onDetach:({panelId:Me,clientX:Re,clientY:We})=>{var rt,nt;const Ae=H.api.getPanel(Me);if(!Ae)return;try{if(Ae.group.model.location.type!=="grid")return}catch{return}const Je=(rt=k.current)==null?void 0:rt.getBoundingClientRect(),Qe=(nt=Ae.group.element)==null?void 0:nt.getBoundingClientRect(),fe=Math.round(Math.min(Math.max((Qe==null?void 0:Qe.width)??600,360),720)),_e=Math.round(Math.min(Math.max((Qe==null?void 0:Qe.height)??500,260),640));H.api.addFloatingGroup(Ae,{x:Je?Math.max(0,Re-Je.left-32):void 0,y:Je?Math.max(0,We-Je.top-18):void 0,width:fe,height:_e}),Ae.api.setActive(),Xe(),pe(),$(He=>He+1)}}),Ne=[H.api.onWillDragPanel(Me=>{if(!(Me.nativeEvent.defaultPrevented||Me.nativeEvent.shiftKey)){try{if(Me.panel.group.model.location.type!=="grid")return}catch{return}ce.startDrag({panelId:Me.panel.id,selfPanelBounds:Q(Me.panel.group.element),...F(Me.nativeEvent)})}}),H.api.onWillShowOverlay(Me=>{if(ce.hasDetached()){Me.preventDefault();return}ce.markDockTarget(F(Me.nativeEvent))}),H.api.onWillDrop(Me=>{if(ce.hasDetached()){Me.preventDefault(),ce.endDrag();return}ce.markDockTarget(F(Me.nativeEvent))}),H.api.onDidDrop(()=>ce.endDrag()),H.api.onUnhandledDragOverEvent(Me=>{ce.isDragging()&&ce.markSelfPanel(F(Me.nativeEvent))})],De=Me=>{if(!ce.isDragging())return;const Re=F(Me);ye(Re)&&ce.markNonSelfPanel(Re)},$e=()=>ce.endDrag();window.addEventListener("dragover",De,!0),window.addEventListener("drop",$e,!0),window.addEventListener("dragend",$e,!0),W.current=()=>{ce.dispose();for(const Me of Ne)Me.dispose();window.removeEventListener("dragover",De,!0),window.removeEventListener("drop",$e,!0),window.removeEventListener("dragend",$e,!0)}}H.api.onDidAddGroup(F=>{requestAnimationFrame(()=>{var Q,ye;try{const ce=(Q=F.element)==null?void 0:Q.ownerDocument;if(!ce||ce===document)return;(ye=ce.getElementById("dv-popout-window"))==null||ye.classList.add("adhdev-dockview");const Ne=document.documentElement.getAttribute("data-theme");Ne&&ce.documentElement.setAttribute("data-theme",Ne),ce.body.className=document.body.className;const De=document.documentElement.getAttribute("style");De&&ce.documentElement.setAttribute("style",De)}catch{}pe(),$(ce=>ce+1)})}),v(((P=H.api.activePanel)==null?void 0:P.id)??null)},[Oe,ze,G,r,u,g,v,Xe,y,x,C,pe,e]);i.useLayoutEffect(()=>{const H=S.current;if(!H||!L.current||M.current&&li({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:r}))return;M.current&&(M.current=!1);const _=K.current,T=new Set(_),P=e.map($e=>$e.tabKey),F=new Set(P),Q=tb({previousVisibleConversationCount:_.length,visibleConversationCount:e.length,ides:r});let ye=!1;for(const $e of _)F.has($e)||Q||(B.current[$e]=mt($e),ye=!0);ye&&Ye(),Q||(pi(H,e),hi(H,e,x));const ce=P.filter($e=>!T.has($e));let Ne=!1;for(const $e of ce){const Me=H.getPanel($e),Re=B.current[$e];if(!Me||!Re||Re.kind==="grid")continue;if(Me.group.model.location.type===Re.kind){delete B.current[$e],Ne=!0;continue}if(Re.kind==="floating"){H.addFloatingGroup(Me,{x:Re.position.left??24,y:Re.position.top??24,width:Re.position.width,height:Re.position.height}),delete B.current[$e],Ne=!0;continue}}if(Ne&&Ye(),K.current=P,y&&ze(y))return;!H.activePanel&&H.panels[0]&&Oe(H.panels[0]),!!(H.activePanel&&H.getPanel(H.activePanel.id))||tt()},[Oe,ze,tt,r,u,Ye,mt,y,x,e]),i.useEffect(()=>{L.current&&ze(y)},[ze,y]),i.useEffect(()=>{const H=T=>{const P=T.target;if(!P)return;const F=P.querySelector("[data-tab-key]")||P.closest("[data-tab-key]");if(F){const Q=F.getAttribute("data-tab-key");if(Q&&T.dataTransfer){const ye=P.closest(".dv-tab")||F.closest(".dv-tab")||F;T.dataTransfer.effectAllowed="move",T.dataTransfer.setData("text/tab-key",Q),ye instanceof HTMLElement&&T.dataTransfer.setDragImage(ye,Math.max(12,Math.round(ye.clientWidth/2)),Math.max(10,Math.round(ye.clientHeight/2)))}}};window.addEventListener("dragstart",H);const _=fi(S.current);for(const T of _)T.addEventListener("dragstart",H);return()=>{window.removeEventListener("dragstart",H);for(const T of _)T.removeEventListener("dragstart",H)}},[z]),i.useEffect(()=>{var _;const H=(_=k.current)==null?void 0:_.querySelector(".adhdev-dockview");H instanceof HTMLElement&&On(H,I),de(),pe()},[pe,de,I]),i.useEffect(()=>{pe()},[pe]),i.useEffect(()=>{const H=_=>{if(_.defaultPrevented||we)return;const T=Ce(_);if(!T)return;const P=_.metaKey||_.ctrlKey||_.altKey;va(_.target)&&!P||Zr(re).setActiveTabShortcut!==T||(_.preventDefault(),_.stopPropagation(),ve())};return window.addEventListener("keydown",H,!0),()=>window.removeEventListener("keydown",H,!0)},[Ce,re,we,ve]),i.useEffect(()=>{const H=k.current;if(!H)return;const _=T=>{var ce,Ne;if(!T.isTrusted)return;const P=(Ne=(ce=T.target)==null?void 0:ce.closest)==null?void 0:Ne.call(ce,".dv-scrollable");if(!P)return;T.preventDefault(),T.stopPropagation();const F=Math.abs(T.deltaX),Q=Math.abs(T.deltaY),ye=F>Q?T.deltaX:T.deltaY;P.dispatchEvent(new WheelEvent("wheel",{deltaY:ye,deltaMode:T.deltaMode,bubbles:!1,cancelable:!0}))};return H.addEventListener("wheel",_,{passive:!1,capture:!0}),()=>H.removeEventListener("wheel",_,{capture:!0})},[]),i.useEffect(()=>{const H=fi(S.current);if(H.length===0)return;const _=H.map(T=>{let P=[],F=null;const Q=()=>{F!=null&&T.clearTimeout(F),F=null,P=[]},ye=()=>{F!=null&&T.clearTimeout(F),F=T.setTimeout(()=>{F=null,P=[]},1200)},ce=De=>{if(!De.ctrlKey&&!De.metaKey&&!De.altKey)return;const $e=Ce(De);if(!$e)return;const Me=yl();for(const[Re,We]of Object.entries(Me))if(e.some(Ae=>Ae.tabKey===Re)&&We===$e){De.preventDefault(),ne(Re);return}},Ne=De=>{if(De.defaultPrevented||we)return;const $e=Ce(De);if(!$e)return;const Me=De.metaKey||De.ctrlKey||De.altKey;if(va(De.target))return;const Re=Zr(re),We=Object.entries(Re).filter(([He,Mt])=>!!Mt&&(He==="splitActiveTabRight"||He==="splitActiveTabDown"||He==="floatActiveTab"||He==="popoutActiveTab"||He==="dockActiveTab"||He==="focusLeftPane"||He==="focusRightPane"||He==="focusUpPane"||He==="focusDownPane"||He==="moveActiveTabToLeftPane"||He==="moveActiveTabToRightPane"||He==="moveActiveTabToUpPane"||He==="moveActiveTabToDownPane"||He==="selectPreviousGroupTab"||He==="selectNextGroupTab"||He==="setActiveTabShortcut"||He==="hideCurrentTab")),Ae=Me?[$e]:[...P.slice(-1),$e].slice(-2),Je=Ae.join(" "),Qe=Ae[Ae.length-1],fe=We.find(([,He])=>He===Je);if(fe){De.preventDefault(),Q(),ke(fe[0]);return}if(We.some(([,He])=>He.startsWith(`${Je} `))){De.preventDefault(),P=Ae,ye();return}const rt=We.find(([,He])=>He===Qe);if(rt){De.preventDefault(),Q(),ke(rt[0]);return}if(We.some(([,He])=>He.startsWith(`${Qe} `))){De.preventDefault(),P=[Qe],ye();return}Q()};return T.addEventListener("keydown",ce),T.addEventListener("keydown",Ne),()=>{Q(),T.removeEventListener("keydown",ce),T.removeEventListener("keydown",Ne)}});return()=>{for(const T of _)T()}},[Ce,re,z,ne,we,ke,e]);const Te=I==="light"?Zn:ea,Fe=((ft=(ct=(Ge=S.current)==null?void 0:Ge.activePanel)==null?void 0:ct.group.element)==null?void 0:ft.ownerDocument)??document;return s.jsxs(Tl.Provider,{value:Pe,children:[s.jsx("div",{ref:k,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(gd,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:lb,remote:db},defaultTabComponent:mb,watermarkComponent:ub,onReady:dt,singleTabMode:"default",tabAnimation:"smooth",theme:Te,popoutUrl:"/popout.html"})}),N&&Zs.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:N.x,top:N.y},children:Le.map(H=>{if(H.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},H.id);let _=s.jsx(mu,{size:13,className:"shrink-0 opacity-70"}),T=()=>{};switch(H.id){case"dockInWindow":case"dockBackToGrid":_=s.jsx(pu,{size:13,className:"shrink-0 opacity-70"}),T=()=>{Se(N.tabKey),A(null)};break;case"moveBackToMain":_=s.jsx(uu,{size:13,className:"shrink-0 opacity-70"}),T=()=>{he(N.tabKey),A(null)};break;case"floatAsPanel":_=s.jsx(fu,{size:13,className:"shrink-0 opacity-70"}),T=()=>{J(N.tabKey),A(null)};break;case"openInNewWindow":_=s.jsx(du,{size:13,className:"shrink-0 opacity-70"}),T=()=>{be(N.tabKey),A(null)};break;case"setShortcut":T=P=>{P.stopPropagation(),te(N.tabKey),A(null)};break;case"removeShortcut":_=s.jsx(wt,{size:13,className:"shrink-0 opacity-70"}),T=()=>{const P={...je};delete P[N.tabKey],D(P),A(null)};break;case"hideTab":_=s.jsx(Ui,{size:13,className:"shrink-0 opacity-70"}),T=()=>{oe(N.tabKey),A(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${H.tone==="muted"?"text-text-muted":""}`,onMouseDown:ob,onClick:T,children:[_,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)})}),N.sourceDocument.body),we&&Zs.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:()=>te(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. ",re?"⌘+1":"Ctrl+1",", ",re?"⌥+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"})]})}),Fe.body)]})}const Ml="adhdev-recent-launch-args-v1",pb=8;function hb(e){return String(e||"").trim().replace(/\s+/g," ")}function Il(e,t){return`${e.trim()}::${t.trim()}`}function Al(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Ml)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function xb(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Ml,JSON.stringify(e))}catch{}}function Ll(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=Al().byKey[Il(r,n)])==null?void 0:o.items)||[]}function Rl(e,t,r){var d;const n=String(e||"").trim(),a=String(t||"").trim(),o=hb(r);if(!n||!a||!o)return;const c=Al(),l=Il(n,a),u=((d=c.byKey[l])==null?void 0:d.items)||[],m=[o,...u.filter(h=>h!==o)].slice(0,pb);c.byKey[l]={items:m},xb(c)}function _l(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Br({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 bb({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 Pl({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:c,onOpenHistory:l,onClearSelection:u}){const m=o?xl(o):null,d=bb({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Br,{title:"Saved history",description:Ga(),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:vp()})]}),children:[m?s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:m.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:m.providerSessionId}),s.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:u,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:d}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function Wn(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 Tr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function gb({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:c,onListSavedSessions:l}){var H,_;const u=lr(),m=i.useMemo(()=>[...e].sort(Pa),[e]),[d,h]=i.useState(((H=m[0])==null?void 0:H.id)||""),f=i.useMemo(()=>m.find(T=>T.id===d)||m[0],[d,m]),v=i.useMemo(()=>((f==null?void 0:f.workspaces)||[]).map(T=>({id:T.id,path:T.path,label:T.label})),[f]),j=(f==null?void 0:f.defaultWorkspaceId)||null,[p,y]=i.useState(""),[x,b]=i.useState(""),[w,R]=i.useState(Wn(m[0])),[g,I]=i.useState(""),[C,S]=i.useState(""),[k,W]=i.useState([]),[L,M]=i.useState(""),[E,U]=i.useState([]),[K,N]=i.useState(!1),[A,z]=i.useState(!1),[$,B]=i.useState(""),[G,V]=i.useState(!1),[me,ae]=i.useState(()=>ht()),[xe,de]=i.useState(null),[be,he]=i.useState(!1),[Y,oe]=i.useState(""),[J,ue]=i.useState(!1),[le,Se]=i.useState(""),[ie,pe]=i.useState([]),[ne,Z]=i.useState(!1),[ee,q]=i.useState(""),[X,re]=i.useState(!1),je=i.useRef(null),we=i.useRef(0);i.useEffect(()=>{var T;!d&&((T=m[0])!=null&&T.id)&&h(m[0].id)},[d,m]),i.useEffect(()=>{!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||u(f.id,{minFreshMs:3e4}).catch(()=>{})},[u,f]);const te=i.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(T=>ps(T,"cli")),[f]),D=i.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(T=>ps(T,"acp")),[f]),ve=i.useMemo(()=>((f==null?void 0:f.detectedIdes)||[]).map(T=>({id:T.type,label:T.name||T.type,meta:T.running?"Detected locally":"Available to open"})),[f]),Ce=i.useMemo(()=>w==="cli"?te.map(T=>({id:T.type,label:T.displayName||T.type,meta:"CLI provider"})):w==="acp"?D.map(T=>({id:T.type,label:T.displayName||T.type,meta:"ACP provider"})):ve,[D,w,te,ve]);i.useEffect(()=>{var P;if(!f)return;if(je.current!==f.id){je.current=f.id,y(j||((P=v[0])==null?void 0:P.id)||"__home__"),b(""),R(Wn(f)),I(""),S(""),M(""),U([]),z(!1),B(""),ae(ht()),oe("");return}y(F=>{var Q;return F==="__custom__"||F==="__home__"||v.some(ye=>ye.id===F)?F:j||((Q=v[0])==null?void 0:Q.id)||"__home__"}),R(F=>F==="ide"&&ve.length>0||F==="cli"&&te.length>0||F==="acp"&&D.length>0?F:Wn(f))},[D.length,te.length,j,ve.length,f,v]),i.useEffect(()=>{var T;w&&(Ce.some(P=>P.id===g)||I(((T=Ce[0])==null?void 0:T.id)||""))},[w,Ce,g]);const ke=i.useCallback(async(T,P)=>{const F=we.current+1;return we.current=F,N(!0),B(""),l(T,P).then(Q=>{we.current===F&&U(Q)}).catch(Q=>{we.current===F&&(U([]),B(Q instanceof Error?Q.message:"Could not load saved sessions"))}).finally(()=>{we.current===F&&(N(!1),z(!0))})},[l]),Pe=i.useCallback((T,P)=>{W(Ll(T,P))},[]);i.useEffect(()=>{we.current+=1,M(""),ae(ht()),!f||!g||w==="ide"?W([]):Pe(f.id,g),z(!1),U([]),B(""),N(!1)},[w,Pe,ke,f,g]),i.useEffect(()=>{if(!L)return;const T=E.find(P=>P.providerSessionId===L);T!=null&&T.canResume||M("")},[E,L]);const Le=p==="__custom__"?x.trim():p==="__home__"?"":((_=v.find(T=>T.id===p))==null?void 0:_.path)||"",Oe=i.useMemo(()=>f?t.filter(T=>T.id!==f.id&&T.daemonId===f.id).map(T=>T.workspace):[],[t,f]),ze=i.useMemo(()=>((f==null?void 0:f.recentLaunches)||[]).map(T=>T.workspace),[f]),tt=i.useCallback(T=>{const P=String(T.workspace||"").trim();if(!P)return;const F=v.find(Q=>Tr(Q.path)===Tr(P));if(F){y(F.id),b("");return}y("__custom__"),b(P)},[v]),Xe=i.useCallback(T=>{const P=String(T.workspace||"").trim();if(!P)return{workspaceId:null,workspacePath:null};const F=v.find(Q=>Tr(Q.path)===Tr(P));return F?{workspaceId:F.id,workspacePath:null}:{workspaceId:null,workspacePath:P}},[v]),Ye=i.useMemo(()=>E.find(T=>T.providerSessionId===L)||null,[E,L]),mt=i.useMemo(()=>{var P;if(w!=="cli"||!f||!g)return null;const T=((P=te.find(F=>F.type===g))==null?void 0:P.displayName)||g;return{routeId:f.id,daemonId:f.id,providerSessionId:L||void 0,transport:"pty",mode:"chat",agentName:T,agentType:g,status:"idle",title:T,messages:[],ideType:g,workspaceName:Le,workspacePath:Le,displayPrimary:T,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${f.id}:${g}`,machineName:St(f,{fallbackId:f.id})}},[w,te,Le,f,L,g]),pt=i.useCallback(()=>{var P;if(!f)return;y("__custom__"),ue(!0),q("");const T=un(f.platform,dn(x.trim(),Le,Oe,ze,f.defaultWorkspacePath,(P=v.find(F=>F.id===j))==null?void 0:P.path,v.map(F=>F.path)));Z(!0),n(f.id,T).then(F=>{Se(F.path),b(F.path),pe(F.directories)}).catch(F=>{q(F instanceof Error?F.message:"Could not load folder")}).finally(()=>Z(!1))},[x,j,ze,Oe,n,Le,f,v]),dt=i.useCallback(T=>{f&&(Z(!0),q(""),n(f.id,T).then(P=>{Se(P.path),b(P.path),pe(P.directories)}).catch(P=>{q(P instanceof Error?P.message:"Could not load folder")}).finally(()=>Z(!1)))},[n,f]),Te=i.useCallback(async()=>{if(!f||!Le)return;re(!0),oe("");const T=await a(f.id,Le);if(re(!1),!T.ok){oe(T.error||"Could not save workspace");return}oe("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,Le,f]),Fe=i.useCallback(async()=>{if(!f||!w||!g)return;he(!0),oe("");const T=C.trim()?C.trim().split(/\s+/).filter(Boolean):[],P=w==="ide"?await o(f.id,g,{workspacePath:Le||null}):await c(f.id,w,g,{workspaceId:p!=="__home__"&&p!=="__custom__"?p:null,workspacePath:p==="__custom__"&&Le||null,resumeSessionId:w==="cli"&&L?L:null,cliArgs:T});if(he(!1),!P.ok){oe(P.error||"Could not start session");return}w!=="ide"&&C.trim()&&(Rl(f.id,g,C),Pe(f.id,g)),r()},[w,C,Pe,r,o,c,Le,f,L,g,p]),Ge=w?Kc(w,w==="cli"&&!!L):"Start",ct=w?Oc(w,w==="cli"&&!!L):"Starting…",ft=m.length>5;return f?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(wt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[s.jsx(Br,{title:"Machine",children:ft?s.jsx("select",{"aria-label":"Machine",value:f.id,onChange:T=>h(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:be,children:m.map(T=>s.jsx("option",{value:T.id,children:St(T,{fallbackId:T.id})},T.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:m.map(T=>{const P=St(T,{fallbackId:T.id}),F=f.id===T.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${P}`,"aria-pressed":F,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${F?"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:()=>h(T.id),disabled:be,title:P,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${T.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:P})]},T.id)})})}),s.jsxs(Br,{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:pt,disabled:be,children:"Browse…"}),children:[s.jsxs("select",{value:p,onChange:T=>{const P=T.target.value;y(P),P==="__custom__"?pt():oe("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:be,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),v.map(T=>s.jsxs("option",{value:T.id,children:[T.id===j?"⭐ ":"",an(T.path,T.label)||T.path]},T.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:p==="__home__"?"Launch without a workspace.":Le||"Select a workspace folder."}),p==="__custom__"&&Le&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:pt,disabled:be,children:[s.jsx(Ns,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Te,disabled:be||X,children:X?"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:te.length>0},{id:"ide",label:"IDE",enabled:ve.length>0},{id:"acp",label:"ACP",enabled:D.length>0}].map(T=>s.jsx("button",{type:"button",className:`btn btn-sm ${w===T.id?"btn-primary":"btn-secondary"}`,onClick:()=>R(T.id),disabled:!T.enabled||be,children:T.label},T.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:w==="ide"?"Choose IDE":w==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Ce.map(T=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${g===T.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>I(T.id),disabled:be,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:T.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:T.meta})]},T.id)),Ce.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."})]})]}),w!=="ide"&&s.jsxs(Br,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:C,onChange:T=>S(T.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:be}),k.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:k.map(T=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>S(T),disabled:be,title:T,children:T},T))})]}),w==="cli"&&s.jsx(Pl,{busy:be,savedSessionsLoading:K,savedSessionsError:$,selectedSession:Ye,onRefresh:()=>{!f||!g||ke(f.id,g)},onOpenHistory:()=>{!f||!g||(V(!0),_l({hasLoadedInitialResults:A,isLoading:K})&&ke(f.id,g))},onClearSelection:()=>M("")}),Y&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${Y.includes("saved")||Y.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:Y})]}),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:be,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:Fe,disabled:be||!w||!g||p==="__custom__"&&!Le,children:[s.jsx(Aa,{size:14}),be?ct:Ge]})]})]})}),J&&s.jsx(fn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:le,directories:ie,busy:ne,error:ee,onClose:()=>ue(!1),onNavigate:dt,onConfirm:T=>{b(T),Se(T),y("__custom__"),ue(!1)}}),G&&mt&&s.jsx(Xa,{activeConv:mt,ides:[],isCreatingChat:!1,isRefreshingHistory:K,savedSessions:E,isSavedSessionsLoading:K,isResumingSavedSessionId:xe,savedHistoryFilters:me,missingWorkspaceResumePath:Le||null,onSavedHistoryFiltersChange:ae,onClose:()=>V(!1),onNewChat:()=>{M(""),V(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!f||!g||ke(f.id,g)},onResumeSavedSession:T=>{if(!f||!g||xe||!T.canResume)return;const P=Xe(T);M(T.providerSessionId),tt(T),de(T.providerSessionId),V(!1),he(!0),oe(""),c(f.id,"cli",g,{workspaceId:P.workspaceId,workspacePath:P.workspacePath,resumeSessionId:T.providerSessionId}).then(F=>{if(!F.ok){oe(F.error||"Could not resume session");return}r()}).finally(()=>{he(!1),de(F=>F===T.providerSessionId?null:F)})}})]}):null}function yb({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=i.useState(!1),[o,c]=i.useState(!1),[l,u]=i.useState(!1),[m,d]=i.useState(!1),[h,f]=i.useState(!1),[v,j]=i.useState("quickstart"),[p,y]=i.useState("workspace"),x=i.useMemo(()=>!t&&!e,[t,e]),b=i.useCallback(S=>{a(S),S&&c(!1)},[]),w=i.useCallback(S=>{c(S),S&&a(!1)},[]),R=i.useCallback(()=>{j(r===0?"quickstart":"shortcuts"),y("workspace"),u(!0),a(!1),c(!1)},[r]),g=i.useCallback(()=>{u(!1)},[]),I=i.useCallback(()=>{d(!0)},[]),C=i.useCallback(()=>{d(!1)},[]);return i.useEffect(()=>{if(!x){f(!1);return}f(!0);const S=window.setTimeout(()=>{f(!1)},1e4);return()=>window.clearTimeout(S)},[x]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:l,newSessionOpen:m,guideNudgeVisible:h,guideTab:v,shortcutSection:p,isDesktopDashboard:x,setGuideTab:j,setShortcutSection:y,handleInboxOpenChange:b,handleHiddenOpenChange:w,handleOpenShortcutHelp:R,closeShortcutHelp:g,openNewSession:I,closeNewSession:C}}function vb(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 wb(e){return e instanceof Error?e.message:String(e||"")}function kb(e){const t=wb(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function jb({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetActiveCliViewMode:m,mobileChatConversations:d,hiddenConversations:h,ides:f,actionLogs:v,sendDaemonCommand:j,setActionLogs:p,setCliViewModeOverrides:y,isStandalone:x,initialDataLoaded:b,userName:w,requestedMobileTabKey:R,onRequestedMobileTabConsumed:g,requestedMachineId:I,onRequestedMachineConsumed:C,requestedMobileSection:S,onRequestedMobileSectionConsumed:k,containerRef:W,isSplitMode:L,numGroups:M,groupSizes:E,groupedConvs:U,clearedTabs:K,focusedGroup:N,focusGroup:A,moveTabToGroup:z,splitTabRelative:$,closeGroup:B,handleResizeStart:G,groupActiveTabIds:V,setGroupActiveTab:me,groupTabOrders:ae,setGroupTabOrder:xe,toggleHiddenTab:de,visibleConversations:be,requestedDesktopTabKey:he,onRequestedDesktopTabConsumed:Y,onDesktopActiveTabChange:oe,onRequestScrollToBottom:J,onHideConversation:ue,onShowHiddenConversation:le,onShowAllHiddenConversations:Se,scrollToBottomRequest:ie,machineEntries:pe,layoutProfile:ne,onBrowseMachineDirectory:Z,onSaveMachineWorkspace:ee,onLaunchMachineIde:q,onLaunchMachineProvider:X,onListMachineSavedSessions:re,notifications:je,notificationUnreadCount:we,liveSessionInboxState:te,onMarkNotificationRead:D,onMarkNotificationUnread:ve,onDeleteNotification:Ce}){const ke=kt.useRef(null),{inboxOpen:Pe,hiddenOpen:Le,shortcutHelpOpen:Oe,newSessionOpen:ze,guideNudgeVisible:tt,guideTab:Xe,shortcutSection:Ye,isDesktopDashboard:mt,setGuideTab:pt,setShortcutSection:dt,handleInboxOpenChange:Te,handleHiddenOpenChange:Fe,handleOpenShortcutHelp:Ge,closeShortcutHelp:ct,openNewSession:ft,closeNewSession:H}=yb({isMobile:t,showMobileChatMode:e,visibleConversationCount:be.length}),_=kt.useCallback(fe=>{var _e;Zs.flushSync(()=>{le(fe)}),(_e=ke.current)==null||_e.restoreHiddenTabToSavedLocation(fe.tabKey)},[le]),T=kt.useCallback(fe=>{var rt;const _e=d.find(nt=>la(nt,fe))||h.find(nt=>la(nt,fe));_e&&(h.some(nt=>nt.tabKey===_e.tabKey)&&_(_e),oe(_e.tabKey),(rt=ke.current)==null||rt.activateConversationTab(_e.tabKey),J(_e.tabKey,"notification-open")),D(fe.id),Te(!1)},[_,h,d,oe,D,J]),P=kt.useCallback(()=>{var _e;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((_e=ke.current)==null||_e.resetAllPanelsToMain(),Fe(!1))},[Fe]),F=kt.useCallback(async fe=>{var Mt;if(!r)return;const _e=(Mt=r.modalButtons)==null?void 0:Mt[fe];if(!_e)return;const rt=Ts(r);if(!rt)return;const nt=_e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),He=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(nt);try{await j(rt,"resolve_action",{button:_e,action:He?"approve":"reject",buttonIndex:fe,...es(r)})}catch(O){kb(O)||console.error("[Shortcut approval] Failed:",O)}},[r,j]),{isMac:Q,actionDefinitions:ye,actionShortcuts:ce,shortcutListening:Ne,shortcutListeningDraft:De,setShortcutListening:$e,setShortcutListeningDraft:Me,saveShortcuts:Re}=Zx({enabled:mt&&!Oe,onTrigger:fe=>{var _e,rt,nt,He,Mt,O,se,ge,Be,Ie,Ee,at,yt,ut,Ut,ur;if(fe==="openShortcutHelp"){Ge();return}if(fe==="openNewSession"){ft();return}if(fe==="hideCurrentTab"){r&&ue(r);return}if(fe==="toggleHiddenTabs"){Fe(!Le);return}if(fe==="openHistoryForActiveTab"){r&&!qe(r)&&o(r);return}if(fe==="openRemoteForActiveTab"){r&&!Ze(r)&&!qe(r)&&c(r);return}if(fe==="splitActiveTabRight"){(_e=ke.current)==null||_e.splitActiveTabRight();return}if(fe==="splitActiveTabDown"){(rt=ke.current)==null||rt.splitActiveTabDown();return}if(fe==="floatActiveTab"){(nt=ke.current)==null||nt.floatActiveTab();return}if(fe==="popoutActiveTab"){(He=ke.current)==null||He.popoutActiveTab();return}if(fe==="dockActiveTab"){(Mt=ke.current)==null||Mt.dockActiveTab();return}if(fe==="focusLeftPane"){(O=ke.current)==null||O.focusLeftPane();return}if(fe==="focusRightPane"){(se=ke.current)==null||se.focusRightPane();return}if(fe==="focusUpPane"){(ge=ke.current)==null||ge.focusUpPane();return}if(fe==="focusDownPane"){(Be=ke.current)==null||Be.focusDownPane();return}if(fe==="moveActiveTabToLeftPane"){(Ie=ke.current)==null||Ie.moveActiveTabToLeftPane();return}if(fe==="moveActiveTabToRightPane"){(Ee=ke.current)==null||Ee.moveActiveTabToRightPane();return}if(fe==="moveActiveTabToUpPane"){(at=ke.current)==null||at.moveActiveTabToUpPane();return}if(fe==="moveActiveTabToDownPane"){(yt=ke.current)==null||yt.moveActiveTabToDownPane();return}if(fe==="triggerPrimaryApprovalAction"){F(0);return}if(fe==="triggerSecondaryApprovalAction"){F(1);return}if(fe==="triggerTertiaryApprovalAction"){F(2);return}if(fe==="setActiveTabShortcut"){(ut=ke.current)==null||ut.setShortcutForActiveTab();return}if(fe==="selectPreviousGroupTab"){(Ut=ke.current)==null||Ut.activatePreviousTabInGroup();return}if(fe==="selectNextGroupTab"){(ur=ke.current)==null||ur.activateNextTabInGroup();return}!r||!Ze(r)||qe(r)||fe==="toggleCliView"&&m(u==="chat"?"terminal":"chat")}}),We=kt.useCallback(()=>{ct(),$e(null),Me([])},[ct,$e,Me]),Ae=kt.useMemo(()=>Ye==="all"?ye:ye.filter(fe=>vb(fe)===Ye),[ye,Ye]),Je=kt.useCallback(()=>{const fe=Object.fromEntries(ye.map(_e=>[_e.id,""]));Re(fe)},[ye,Re]),Qe=kt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const fe=Object.fromEntries(ye.map(_e=>[_e.id,_e.defaultShortcut]));Re(fe)},[ye,Re]);return kt.useEffect(()=>{const fe=_e=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?_e.metaKey&&_e.key.toLowerCase()==="w":_e.ctrlKey&&_e.key.toLowerCase()==="w")&&(_e.preventDefault(),r&&ue&&ue(r))};return window.addEventListener("keydown",fe),()=>window.removeEventListener("keydown",fe)},[r,ue]),kt.useEffect(()=>{if(!Oe||Ne)return;const fe=_e=>{_e.key==="Escape"&&(_e.preventDefault(),We())};return window.addEventListener("keydown",fe,!0),()=>window.removeEventListener("keydown",fe,!0)},[We,Oe,Ne]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(pp,{activeConv:r,wsStatus:n,isConnected:a,conversations:be,hiddenConversations:h,onOpenHistory:o,onHideConversation:ue,onShowConversation:_,onShowAllHidden:Se,onResetPanelsToMain:P,notifications:je,notificationUnreadCount:we,onOpenNotification:T,onMarkNotificationRead:D,onMarkNotificationUnread:ve,onDeleteNotification:Ce,inboxOpen:Pe,onInboxOpenChange:Te,hiddenOpen:Le,onHiddenOpenChange:Fe,onOpenNewSession:t?void 0:ft,onOpenDashboardGuide:Ge,guideNudgeVisible:tt,actionShortcuts:ce,onOpenRemote:()=>{!r||Ze(r)||qe(r)||c(r)},onStopCli:l,activeCliViewMode:u,onSetCliViewMode:m}),e?s.jsx(Wx,{conversations:d,hiddenConversations:h,ides:f,actionLogs:v,sendDaemonCommand:j,setActionLogs:p,setCliViewModeOverrides:y,isStandalone:x,userName:w,requestedActiveTabKey:R,onRequestedActiveTabConsumed:g,requestedMachineId:I,onRequestedMachineConsumed:C,requestedMobileSection:S,onRequestedMobileSectionConsumed:k,onOpenHistory:o,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowHiddenConversation:_,onShowAllHiddenConversations:Se,onOpenNewSession:ft,liveSessionInboxState:te}):t?s.jsx(Yx,{containerRef:W,isSplitMode:L,numGroups:M,groupSizes:E,groupedConvs:U,clearedTabs:K,ides:f,actionLogs:v,sendDaemonCommand:j,setActionLogs:p,isStandalone:x,hasRegisteredMachines:pe.length>0,userName:w,focusedGroup:N,focusGroup:A,moveTabToGroup:z,splitTabRelative:$,closeGroup:B,handleResizeStart:G,groupActiveTabIds:V,setGroupActiveTab:me,groupTabOrders:ae,setGroupTabOrder:xe,toggleHiddenTab:de,onOpenNewSession:ft,allowTabShortcuts:!1,liveSessionInboxState:te}):s.jsx(fb,{visibleConversations:be,clearedTabs:K,ides:f,actionLogs:v,sendDaemonCommand:j,setActionLogs:p,isStandalone:x,hasRegisteredMachines:pe.length>0,initialDataLoaded:b,userName:w,toggleHiddenTab:de,actionShortcuts:ce,registerActionHandlers:fe=>{ke.current=fe},onActiveTabChange:oe,requestedActiveTabKey:he,onRequestedActiveTabConsumed:Y,onRequestScrollToBottom:J,scrollToBottomRequest:ie,onOpenNewSession:ft,liveSessionInboxState:te,layoutProfile:ne}),ze&&s.jsx(gb,{machines:pe,ides:f,onClose:H,onBrowseDirectory:Z,onSaveWorkspace:ee,onLaunchIde:q,onLaunchProvider:X,onListSavedSessions:re}),Oe&&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:We,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:fe=>fe.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:We,"aria-label":"Close dashboard guide",children:s.jsx(wt,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(fe=>s.jsx("button",{type:"button",className:`btn btn-sm ${Xe===fe.id?"btn-primary":"btn-secondary"}`,onClick:()=>pt(fe.id),children:fe.label},fe.id))}),Xe==="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 ",Q?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Xe==="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."]})]})]})]}),Xe==="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(fe=>s.jsx("button",{type:"button",className:`btn btn-sm ${Ye===fe.id?"btn-primary":"btn-secondary"}`,onClick:()=>dt(fe.id),children:fe.label},fe.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Je,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:Qe,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Ae.map(fe=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ne===fe.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:fe.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:fe.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:fe.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===fe.id?De.length>0?`${De.join(" ")} ...`:"Listening...":ce[fe.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{$e(fe.id),Me([])},children:Ne===fe.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const _e={...ce};_e[fe.id]="",Re(_e)},children:"Disable"})]})]})},fe.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Q?"⌘⇧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 Hn=[{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 Sb({onClose:e}){const[t,r]=i.useState(0),n=Hn[t],a=t===Hn.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:o=>{o.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(wt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Hn.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:`
63
63
  @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
64
64
  @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
65
- `})]})}function pb({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",u=o.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${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)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"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 hb({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,c]=i.useState(()=>a||"native"),l=i.useMemo(()=>Kc(t),[t]),u=i.useMemo(()=>e?Ja(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),m=i.useMemo(()=>u.find(p=>p.streamSource==="native"),[u]),d=i.useMemo(()=>u.filter(p=>p.streamSource==="agent-stream"),[u]),h=i.useMemo(()=>e?_t(u,e.id):null,[u,e]);i.useEffect(()=>{a&&c(a)},[a]),i.useEffect(()=>{if(a||!h)return;const p=h.streamSource==="native"?"native":h.tabKey;!p||o===p||o==="native"&&c(p)},[o,h,a]),i.useEffect(()=>{var p;o!=="native"&&(d.some(y=>y.tabKey===o)||c(((p=d[0])==null?void 0:p.tabKey)||"native"))},[o,d]),i.useEffect(()=>{o==="native"&&(m||d[0]&&c(d[0].tabKey))},[o,m,d]);const f=i.useMemo(()=>o==="native"&&m?m:d.find(p=>p.tabKey===o)||h||m||d[0],[o,m,h,d]),w=i.useMemo(()=>d.map(p=>({tabKey:p.tabKey,title:Rc(p)||n,status:p.status})),[d,n]),k=i.useCallback(p=>{if(p)return u.find(y=>ca(y,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[u]);return{activeChatTab:o,setActiveChatTab:c,activeConv:f,conversations:u,extensionTabs:w,hasExtensions:w.length>0,resolveConversationByTarget:k}}function xb({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:c,isStandalone:l,userName:u,onOpenHistory:m,onConversationChange:d,onClose:h}){const[f,w]=i.useState("split"),[k,p]=i.useState(()=>Vt(e)?"native":e.tabKey),y=i.useRef(null),x=i.useMemo(()=>t||r.find(A=>A.id===e.routeId),[e.routeId,t,r]),b=i.useMemo(()=>ot((x==null?void 0:x.type)||""),[x==null?void 0:x.type]),{conversations:v,extensionTabs:R,hasExtensions:g}=hb({ideData:x,allIdes:r,connectionStates:n,ideName:b||"IDE",preferredTabKey:Vt(e)?void 0:e.tabKey}),M=i.useMemo(()=>x?_t(v,x.id):null,[x,v]);i.useEffect(()=>{const A=y.current,z={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(y.current=z,!(A&&A.routeId===z.routeId&&A.tabKey===z.tabKey&&A.streamSource===z.streamSource)){if(Vt(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(k==="native"){if(v.some(A=>A.streamSource==="native"))return;(M==null?void 0:M.streamSource)==="agent-stream"&&p(M.tabKey);return}if(!v.some(A=>A.tabKey===k)){if((M==null?void 0:M.streamSource)==="agent-stream"){p(M.tabKey);return}p("native")}},[v,k,M]);const C=i.useMemo(()=>k==="native"?v.find(A=>A.streamSource==="native")||e:v.find(A=>A.tabKey===k)||e,[e,v,k]),S=Zc(C),j=i.useMemo(()=>S.status||S.modalMessage||S.modalButtons?{...C,...S.status?{status:S.status}:{},...S.modalMessage!==void 0?{modalMessage:S.modalMessage}:{},...S.modalButtons!==void 0?{modalButtons:S.modalButtons}:{}}:C,[C,S]),W=Ps(j),L=on({sendDaemonCommand:o,activeConv:j,setActionLogs:c,isStandalone:l}),{connScreenshot:I,screenshotUsage:D,handleRemoteAction:U}=gl({doId:W,targetSessionId:fc(j),connState:j.connectionState||"new",viewMode:f}),K=i.useMemo(()=>a.filter(A=>A.routeId===j.tabKey),[a,j.tabKey]);i.useEffect(()=>{d==null||d(j)},[j,d]),i.useEffect(()=>{const A=z=>{z.key==="Escape"&&h()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[h]);const N=i.useCallback(A=>{A.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:h,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:N,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(Nt,{size:16})}),s.jsx("span",{className:"truncate",children:$a(C)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(A=>{const z=f===A;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${z?"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:()=>w(A),title:A==="split"?"Split view":"Remote only",children:A==="split"?s.jsx(Yd,{size:15}):s.jsx(Nt,{size:15})},A)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>m(C),title:"Chat History",children:[s.jsx(Ia,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${f==="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:[f!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(pb,{hasExtensions:g,ideName:b||"IDE",activeChatTab:k,extensionTabs:R,onSelectTab:p}),s.jsx(Zi,{activeConv:j,onModalButton:L.handleModalButton}),s.jsx(ha,{activeConv:j,ideEntry:x,showMetaChips:!1,handleSendChat:L.handleSendChat,isSendingChat:L.isSendingChat,sendFeedbackMessage:L.sendFeedbackMessage,handleFocusAgent:L.handleFocusAgent,isFocusingAgent:L.isFocusingAgent,actionLogs:K,userName:u})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${f==="split"?"order-1 md:order-2":""}`,children:s.jsx(Ji,{addLog:()=>{},connState:j.connectionState||"new",connScreenshot:I,screenshotUsage:D,transportType:j.transport,onAction:U})})]})]})})}function bb({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=Vf(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 gb({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(Jf,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(Xa,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,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&&(Ze(r.targetConv)||qe(r.targetConv))&&s.jsx(bb,{activeConv:r.targetConv,canSaveAndStop:Ze(r.targetConv)&&!qe(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(Bc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&s.jsx(fb,{onClose:o.onClose})]})}function yb({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(or,{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=St(c,{fallbackId:c.id}),u=n[c.id],m=c.version||c.daemonVersion||"unknown",d=c.versionUpdateRequired===!0;return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:l}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),d&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:d?"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(wt,{size:16})})]})}function vb(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function wb(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 jb(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>wb(t)).map(t=>t.id)}}function kb(){var po,ho,xo,bo;const{sendCommand:e}=vt(),t=lr(),r=Qc(),n=Na(),a=Ls(),[o,c]=xd(),l=o.get("activeTab"),u=((po=n.state)==null?void 0:po.openRemoteForTabKey)||null,m=((ho=n.state)==null?void 0:ho.openMachineId)||null,d=((xo=n.state)==null?void 0:xo.mobileSection)||null,h=Ic(),f=h.ides||[],w=h.initialLoaded??!0,{updateRouteChats:k,setToasts:p}=h,[y,x]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),b=h.toasts||[],v=h.wsStatus||"connected",R=h.isConnected??!0,g=h.connectionStates||{},M=h.showReconnected||!1,{layoutProfile:C,groupAssignments:S,updateGroupAssignments:j,focusedGroup:W,updateFocusedGroup:L,focusGroup:I,groupActiveTabIds:D,updateGroupActiveTabIds:U,setGroupActiveTab:K,groupTabOrders:N,updateGroupTabOrders:A,setGroupTabOrder:z,groupSizes:$,updateGroupSizes:B,isMobile:V,hasHydratedStoredLayout:G,hydrateStoredLayout:me,focusConversationTab:ne}=Lh(),[xe,de]=i.useState(()=>to());i.useEffect(()=>Yp(de),[]);const be=i.useMemo(()=>vb({isMobile:V,mobileViewMode:xe}),[V,xe]),[he,Y]=i.useState([]),[oe,J]=i.useState({}),[ue,le]=i.useState({});ir("Dashboard",{ideCount:f.length,toastCount:b.length,focusedGroup:W,groupCount:Object.keys(S).length,actionLogCount:he.length});const Se=i.useMemo(()=>f.filter(Ue=>Ue.type==="adhdev-daemon").sort(Pa),[f]),ie=Se[0],pe=!!ie;i.useEffect(()=>{const{metadataDaemonIds:Ue,runtimeDaemonIds:Mt}=jb(Se);for(const Ds of Ue)t(Ds,{minFreshMs:3e4}).catch(()=>{});for(const Ds of Mt)r(Ds,{minFreshMs:3e4}).catch(()=>{})},[t,r,Se]);const re=(ie==null?void 0:ie.terminalBackend)||null,Z=ie?St(ie,{fallbackId:ie.id}):null,ee=(ie==null?void 0:ie.id)||null,q=i.useMemo(()=>oh(f,oe),[f,oe]),{hiddenTabs:X,hideTarget:ae,toggleTarget:je,showTarget:ke,showAllTabs:te}=ah(),{conversations:E,visibleConversations:ve,visibleTabKeys:Ce,resolveConversationBySessionId:we,resolveConversationByTarget:Pe}=xh({ides:q,connectionStates:g,clearedTabs:ue,hiddenTabs:X}),Le=i.useMemo(()=>new Map(E.map(Ue=>[Ue.tabKey,Ue])),[E]),Oe=Tf(ve,be),ze=i.useMemo(()=>Ho(E,Oe),[E,Oe]),tt=i.useMemo(()=>Ho(ve,Oe),[ve,Oe]);i.useEffect(()=>{Object.keys(oe).length!==0&&J(Ue=>ih(Ue,f))},[f,oe]);const Xe=i.useMemo(()=>Eu(f),[f]),{notifications:Ye,unreadCount:mt}=Vh({conversations:ze,liveSessionInboxState:Xe}),{handleMarkDashboardNotificationRead:pt,handleMarkDashboardNotificationUnread:dt,handleDeleteDashboardNotification:Te}=Gh({notifications:Ye,sendDaemonCommand:e}),{containerRef:Fe,normalizedGroupAssignments:Ge,numGroups:ct,isSplitMode:ft,groupedConvs:H,moveTabToGroup:_,closeGroup:T,handleResizeStart:P,splitTabRelative:F}=Bh({groupAssignments:S,updateGroupAssignments:j,updateFocusedGroup:L,updateGroupActiveTabIds:U,updateGroupTabOrders:A,groupSizes:$,updateGroupSizes:B,isMobile:V,visibleConversations:tt,visibleTabKeys:Ce}),{activeConv:Q,openDesktopConversation:ye,requestScrollToBottom:ce,scrollToBottomRequest:Ne,setDesktopActiveTab:De}=rx({isMobile:V,conversations:ze,visibleConversations:tt,groupActiveTabIds:D,focusedGroup:W,groupedConvs:H,setSearchParams:c});ox({activeConv:Q,isMobile:V,liveSessionInboxState:Xe,sendDaemonCommand:e});const{requestedDesktopTabKey:$e,requestedMobileTabKey:Ie,consumeRequestedActiveTab:Re}=bh({isMobile:V,urlActiveTab:l,resolveConversationBySessionId:we,setSearchParams:c}),{remoteDialogConv:We,remoteDialogIdeEntry:Ae,remoteDialogActiveConv:Je,setRemoteDialogActiveConv:Qe,openRemoteDialog:fe,closeRemoteDialog:_e,cliStopDialogOpen:rt,cliStopTargetConv:nt,requestCliStop:He,cancelCliStop:It,confirmCliStop:O}=lx({isMobile:V,location:n,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:$e,conversations:E,ides:f,resolveConversationByTarget:Pe,activeConv:Q,sendDaemonCommand:e}),{historyModalOpen:se,openHistoryModal:ge,closeHistoryModal:Be,historyTargetConv:Me,isSavedSessionHistoryTarget:Ee,isHistoryCreatingChat:at,isHistoryRefreshingHistory:yt,handleHistorySwitchSession:ut,handleHistoryNewChat:Ut,handleHistoryRefresh:ur,savedHistorySessions:El,savedHistoryFilters:$l,setSavedHistoryFilters:Bl,isSavedHistoryLoading:Kl,resumingSavedHistorySessionId:Ol,handleRefreshSavedHistory:Wl,handleResumeSavedHistorySession:Hl}=ix({activeConv:Q,remoteDialogConv:We,remoteDialogActiveConv:Je,ides:f,sendDaemonCommand:e,updateRouteChats:k,setToasts:p,setClearedTabs:le,setSearchParams:c}),Fl=i.useMemo(()=>tt,[tt]),mr=V&&xe==="chat",Ul=i.useMemo(()=>ze.filter(Ue=>so(X,Ue)),[ze,X]),uo=i.useCallback(Ue=>{const Mt=new URLSearchParams(o);Mt.set("activeTab",Ue),c(Mt,{replace:!0})},[o,c]),{trackPendingLaunch:zl}=Zh({ides:f,conversations:E,onOpenSession:uo}),{handleBrowseMachineDirectory:Vl,handleSaveMachineWorkspace:Gl,handleLaunchMachineIde:ql,handleLaunchMachineProvider:Yl,handleListMachineSavedSessions:Xl,setActiveCliViewMode:Jl}=ex({sendDaemonCommand:e,trackPendingLaunch:zl,onOpenSession:uo,activeConv:Q,ides:f,setCliViewModeOverrides:J});ch({visibleConversations:ve,clearedTabs:ue,setClearedTabs:le,setActionLogs:Y}),gh({ides:f,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Pe});const{isRefreshingHistory:Ql,handleRefreshHistory:Zl}=ll({sendDaemonCommand:e,activeConv:Q,chats:(bo=f.find(Ue=>Ue.id===(Q==null?void 0:Q.routeId)))==null?void 0:bo.chats,updateRouteChats:k,setToasts:p,setClearedTabs:le});_h({urlActiveTab:V&&!mr?l:null,conversations:E,resolveConversationBySessionId:we,normalizedGroupAssignments:Ge,hasHydratedStoredLayout:V&&!mr?G:!0,hydrateStoredLayout:V&&!mr?me:()=>{},focusConversationTab:ne,setSearchParams:c,historyModalOpen:se,activeConv:Q,isRefreshingHistory:Ql,ides:f,handleRefreshHistory:Zl});const ed=i.useMemo(()=>!Q||!Ze(Q)||qe(Q)?null:_s(Q),[Q]),{versionMismatchDaemons:td,hasRequiredVersionDaemons:mo,appVersion:sd,versionBannerDismissed:rd,setVersionBannerDismissed:nd,upgradingDaemons:ad,handleBannerUpgrade:od}=Kh({ides:f,sendDaemonCommand:e}),fo=i.useCallback(Ue=>{ke(Ue),ye(Ue)},[ye,ke]),id=i.useCallback(Ue=>{ae(Ue)},[ae]);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(Qf,{terminalBackend:re,isStandalone:pe,machineLabel:Z,machineKey:ee}),(!rd||mo)&&s.jsx(yb,{daemons:td,targetVersion:sd,required:mo,upgradingDaemons:ad,onUpgrade:od,onDismiss:()=>nd(!0)}),s.jsx(mb,{showMobileChatMode:mr,isMobile:V,activeConv:Q,wsStatus:v,isConnected:R,onOpenHistory:Ue=>{Ue&&Qe(Ue),ge()},onOpenRemote:fe,onStopCli:He,activeCliViewMode:ed,onSetActiveCliViewMode:Jl,mobileChatConversations:Fl,ides:f,actionLogs:he,sendDaemonCommand:e,setActionLogs:Y,setCliViewModeOverrides:J,isStandalone:pe,initialDataLoaded:w,userName:h.userName,requestedMobileTabKey:Ie,onRequestedMobileTabConsumed:Re,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Fe,isSplitMode:ft,numGroups:ct,groupSizes:$,groupedConvs:H,clearedTabs:ue,focusedGroup:W,focusGroup:I,moveTabToGroup:_,splitTabRelative:F,closeGroup:T,handleResizeStart:P,groupActiveTabIds:D,setGroupActiveTab:K,groupTabOrders:N,setGroupTabOrder:z,toggleHiddenTab:Ue=>je(Le.get(Ue)||{tabKey:Ue}),visibleConversations:tt,hiddenConversations:Ul,requestedDesktopTabKey:$e,onRequestedDesktopTabConsumed:Re,onDesktopActiveTabChange:De,onRequestScrollToBottom:ce,onHideConversation:id,onShowHiddenConversation:fo,onShowAllHiddenConversations:te,scrollToBottomRequest:Ne,machineEntries:Se,layoutProfile:C,onBrowseMachineDirectory:Vl,onSaveMachineWorkspace:Gl,onLaunchMachineIde:ql,onLaunchMachineProvider:Yl,onListMachineSavedSessions:Xl,notifications:Ye,notificationUnreadCount:mt,liveSessionInboxState:Xe,onMarkNotificationRead:pt,onMarkNotificationUnread:dt,onDeleteNotification:Te}),s.jsx("style",{children:`
65
+ `})]})}function Nb({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",u=o.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${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)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"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 Cb({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,c]=i.useState(()=>a||"native"),l=i.useMemo(()=>Hc(t),[t]),u=i.useMemo(()=>e?Ja(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),m=i.useMemo(()=>u.find(p=>p.streamSource==="native"),[u]),d=i.useMemo(()=>u.filter(p=>p.streamSource==="agent-stream"),[u]),h=i.useMemo(()=>e?_t(u,e.id):null,[u,e]);i.useEffect(()=>{a&&c(a)},[a]),i.useEffect(()=>{if(a||!h)return;const p=h.streamSource==="native"?"native":h.tabKey;!p||o===p||o==="native"&&c(p)},[o,h,a]),i.useEffect(()=>{var p;o!=="native"&&(d.some(y=>y.tabKey===o)||c(((p=d[0])==null?void 0:p.tabKey)||"native"))},[o,d]),i.useEffect(()=>{o==="native"&&(m||d[0]&&c(d[0].tabKey))},[o,m,d]);const f=i.useMemo(()=>o==="native"&&m?m:d.find(p=>p.tabKey===o)||h||m||d[0],[o,m,h,d]),v=i.useMemo(()=>d.map(p=>({tabKey:p.tabKey,title:Dc(p)||n,status:p.status})),[d,n]),j=i.useCallback(p=>{if(p)return u.find(y=>la(y,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[u]);return{activeChatTab:o,setActiveChatTab:c,activeConv:f,conversations:u,extensionTabs:v,hasExtensions:v.length>0,resolveConversationByTarget:j}}function Tb({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:c,isStandalone:l,userName:u,onOpenHistory:m,onConversationChange:d,onClose:h}){const[f,v]=i.useState("split"),[j,p]=i.useState(()=>Vt(e)?"native":e.tabKey),y=i.useRef(null),x=i.useMemo(()=>t||r.find(A=>A.id===e.routeId),[e.routeId,t,r]),b=i.useMemo(()=>ot((x==null?void 0:x.type)||""),[x==null?void 0:x.type]),{conversations:w,extensionTabs:R,hasExtensions:g}=Cb({ideData:x,allIdes:r,connectionStates:n,ideName:b||"IDE",preferredTabKey:Vt(e)?void 0:e.tabKey}),I=i.useMemo(()=>x?_t(w,x.id):null,[x,w]);i.useEffect(()=>{const A=y.current,z={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(y.current=z,!(A&&A.routeId===z.routeId&&A.tabKey===z.tabKey&&A.streamSource===z.streamSource)){if(Vt(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(j==="native"){if(w.some(A=>A.streamSource==="native"))return;(I==null?void 0:I.streamSource)==="agent-stream"&&p(I.tabKey);return}if(!w.some(A=>A.tabKey===j)){if((I==null?void 0:I.streamSource)==="agent-stream"){p(I.tabKey);return}p("native")}},[w,j,I]);const C=i.useMemo(()=>j==="native"?w.find(A=>A.streamSource==="native")||e:w.find(A=>A.tabKey===j)||e,[e,w,j]),S=sl(C),k=i.useMemo(()=>S.status||S.modalMessage||S.modalButtons?{...C,...S.status?{status:S.status}:{},...S.modalMessage!==void 0?{modalMessage:S.modalMessage}:{},...S.modalButtons!==void 0?{modalButtons:S.modalButtons}:{}}:C,[C,S]),W=Ps(k),L=cn({sendDaemonCommand:o,activeConv:k,setActionLogs:c,isStandalone:l}),{connScreenshot:M,screenshotUsage:E,handleRemoteAction:U}=wl({doId:W,targetSessionId:pc(k),connState:k.connectionState||"new",viewMode:f}),K=i.useMemo(()=>a.filter(A=>A.routeId===k.tabKey),[a,k.tabKey]);i.useEffect(()=>{d==null||d(k)},[k,d]),i.useEffect(()=>{const A=z=>{z.key==="Escape"&&h()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[h]);const N=i.useCallback(A=>{A.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:h,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:N,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(Nt,{size:16})}),s.jsx("span",{className:"truncate",children:$a(C)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(A=>{const z=f===A;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${z?"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:()=>v(A),title:A==="split"?"Split view":"Remote only",children:A==="split"?s.jsx(Qd,{size:15}):s.jsx(Nt,{size:15})},A)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>m(C),title:"Chat History",children:[s.jsx(Ma,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${f==="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:[f!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(Nb,{hasExtensions:g,ideName:b||"IDE",activeChatTab:j,extensionTabs:R,onSelectTab:p}),s.jsx(ec,{activeConv:k,onModalButton:L.handleModalButton}),s.jsx(ha,{activeConv:k,ideEntry:x,showMetaChips:!1,handleSendChat:L.handleSendChat,isSendingChat:L.isSendingChat,sendFeedbackMessage:L.sendFeedbackMessage,handleFocusAgent:L.handleFocusAgent,isFocusingAgent:L.isFocusingAgent,actionLogs:K,userName:u})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${f==="split"?"order-1 md:order-2":""}`,children:s.jsx(Qi,{addLog:()=>{},connState:k.connectionState||"new",connScreenshot:M,screenshotUsage:E,transportType:k.transport,onAction:U})})]})]})})}function Mb({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=rp(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 Ib({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(cp,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(Xa,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),t.conversation&&s.jsx(Tb,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),r.open&&r.targetConv&&(Ze(r.targetConv)||qe(r.targetConv))&&s.jsx(Mb,{activeConv:r.targetConv,canSaveAndStop:Ze(r.targetConv)&&!qe(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(Wc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&s.jsx(Sb,{onClose:o.onClose})]})}function Ab({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(or,{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=St(c,{fallbackId:c.id}),u=n[c.id],m=c.version||c.daemonVersion||"unknown",d=c.versionUpdateRequired===!0;return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:l}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),d&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:d?"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(wt,{size:16})})]})}function Lb(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Rb(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 _b(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>Rb(t)).map(t=>t.id)}}function Pb(){var po,ho,xo,bo;const{sendCommand:e}=vt(),t=lr(),r=tl(),n=Na(),a=Ls(),[o,c]=yd(),l=o.get("activeTab"),u=((po=n.state)==null?void 0:po.openRemoteForTabKey)||null,m=((ho=n.state)==null?void 0:ho.openMachineId)||null,d=((xo=n.state)==null?void 0:xo.mobileSection)||null,h=Lc(),f=h.ides||[],v=h.initialLoaded??!0,{updateRouteChats:j,setToasts:p}=h,[y,x]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),b=h.toasts||[],w=h.wsStatus||"connected",R=h.isConnected??!0,g=h.connectionStates||{},I=h.showReconnected||!1,{layoutProfile:C,groupAssignments:S,updateGroupAssignments:k,focusedGroup:W,updateFocusedGroup:L,focusGroup:M,groupActiveTabIds:E,updateGroupActiveTabIds:U,setGroupActiveTab:K,groupTabOrders:N,updateGroupTabOrders:A,setGroupTabOrder:z,groupSizes:$,updateGroupSizes:B,isMobile:G,hasHydratedStoredLayout:V,hydrateStoredLayout:me,focusConversationTab:ae}=Hh(),[xe,de]=i.useState(()=>to());i.useEffect(()=>oh(de),[]);const be=i.useMemo(()=>Lb({isMobile:G,mobileViewMode:xe}),[G,xe]),[he,Y]=i.useState([]),[oe,J]=i.useState({}),[ue,le]=i.useState({});ir("Dashboard",{ideCount:f.length,toastCount:b.length,focusedGroup:W,groupCount:Object.keys(S).length,actionLogCount:he.length});const Se=i.useMemo(()=>f.filter(Ue=>Ue.type==="adhdev-daemon").sort(Pa),[f]),ie=Se[0],pe=!!ie;i.useEffect(()=>{const{metadataDaemonIds:Ue,runtimeDaemonIds:It}=_b(Se);for(const Ds of Ue)t(Ds,{minFreshMs:3e4}).catch(()=>{});for(const Ds of It)r(Ds,{minFreshMs:3e4}).catch(()=>{})},[t,r,Se]);const ne=(ie==null?void 0:ie.terminalBackend)||null,Z=ie?St(ie,{fallbackId:ie.id}):null,ee=(ie==null?void 0:ie.id)||null,q=i.useMemo(()=>bh(f,oe),[f,oe]),{hiddenTabs:X,hideTarget:re,toggleTarget:je,showTarget:we,showAllTabs:te}=xh(),{conversations:D,visibleConversations:ve,visibleTabKeys:Ce,resolveConversationBySessionId:ke,resolveConversationByTarget:Pe}=Th({ides:q,connectionStates:g,clearedTabs:ue,hiddenTabs:X}),Le=i.useMemo(()=>new Map(D.map(Ue=>[Ue.tabKey,Ue])),[D]),Oe=Af(ve,be),ze=i.useMemo(()=>Ho(D,Oe),[D,Oe]),tt=i.useMemo(()=>Ho(ve,Oe),[ve,Oe]);i.useEffect(()=>{Object.keys(oe).length!==0&&J(Ue=>gh(Ue,f))},[f,oe]);const Xe=i.useMemo(()=>Ku(f),[f]),{notifications:Ye,unreadCount:mt}=rx({conversations:ze,liveSessionInboxState:Xe}),{handleMarkDashboardNotificationRead:pt,handleMarkDashboardNotificationUnread:dt,handleDeleteDashboardNotification:Te}=nx({notifications:Ye,sendDaemonCommand:e}),{containerRef:Fe,normalizedGroupAssignments:Ge,numGroups:ct,isSplitMode:ft,groupedConvs:H,moveTabToGroup:_,closeGroup:T,handleResizeStart:P,splitTabRelative:F}=Yh({groupAssignments:S,updateGroupAssignments:k,updateFocusedGroup:L,updateGroupActiveTabIds:U,updateGroupTabOrders:A,groupSizes:$,updateGroupSizes:B,isMobile:G,visibleConversations:tt,visibleTabKeys:Ce}),{activeConv:Q,openDesktopConversation:ye,requestScrollToBottom:ce,scrollToBottomRequest:Ne,setDesktopActiveTab:De}=px({isMobile:G,conversations:ze,visibleConversations:tt,groupActiveTabIds:E,focusedGroup:W,groupedConvs:H,setSearchParams:c});bx({activeConv:Q,isMobile:G,liveSessionInboxState:Xe,sendDaemonCommand:e});const{requestedDesktopTabKey:$e,requestedMobileTabKey:Me,consumeRequestedActiveTab:Re}=Mh({isMobile:G,urlActiveTab:l,resolveConversationBySessionId:ke,setSearchParams:c}),{remoteDialogConv:We,remoteDialogIdeEntry:Ae,remoteDialogActiveConv:Je,setRemoteDialogActiveConv:Qe,openRemoteDialog:fe,closeRemoteDialog:_e,cliStopDialogOpen:rt,cliStopTargetConv:nt,requestCliStop:He,cancelCliStop:Mt,confirmCliStop:O}=vx({isMobile:G,location:n,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:$e,conversations:D,ides:f,resolveConversationByTarget:Pe,activeConv:Q,sendDaemonCommand:e}),{historyModalOpen:se,openHistoryModal:ge,closeHistoryModal:Be,historyTargetConv:Ie,isSavedSessionHistoryTarget:Ee,isHistoryCreatingChat:at,isHistoryRefreshingHistory:yt,handleHistorySwitchSession:ut,handleHistoryNewChat:Ut,handleHistoryRefresh:ur,savedHistorySessions:Kl,savedHistoryFilters:Ol,setSavedHistoryFilters:Wl,isSavedHistoryLoading:Hl,resumingSavedHistorySessionId:Fl,handleRefreshSavedHistory:Ul,handleResumeSavedHistorySession:zl}=gx({activeConv:Q,remoteDialogConv:We,remoteDialogActiveConv:Je,ides:f,sendDaemonCommand:e,updateRouteChats:j,setToasts:p,setClearedTabs:le,setSearchParams:c}),Vl=i.useMemo(()=>tt,[tt]),mr=G&&xe==="chat",Gl=i.useMemo(()=>ze.filter(Ue=>so(X,Ue)),[ze,X]),uo=i.useCallback(Ue=>{const It=new URLSearchParams(o);It.set("activeTab",Ue),c(It,{replace:!0})},[o,c]),{trackPendingLaunch:ql}=dx({ides:f,conversations:D,onOpenSession:uo}),{handleBrowseMachineDirectory:Yl,handleSaveMachineWorkspace:Xl,handleLaunchMachineIde:Jl,handleLaunchMachineProvider:Ql,handleListMachineSavedSessions:Zl,setActiveCliViewMode:ed}=ux({sendDaemonCommand:e,trackPendingLaunch:ql,onOpenSession:uo,activeConv:Q,ides:f,setCliViewModeOverrides:J});yh({visibleConversations:ve,clearedTabs:ue,setClearedTabs:le,setActionLogs:Y}),Ih({ides:f,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Pe});const{isRefreshingHistory:td,handleRefreshHistory:sd}=ml({sendDaemonCommand:e,activeConv:Q,chats:(bo=f.find(Ue=>Ue.id===(Q==null?void 0:Q.routeId)))==null?void 0:bo.chats,updateRouteChats:j,setToasts:p,setClearedTabs:le});Uh({urlActiveTab:G&&!mr?l:null,conversations:D,resolveConversationBySessionId:ke,normalizedGroupAssignments:Ge,hasHydratedStoredLayout:G&&!mr?V:!0,hydrateStoredLayout:G&&!mr?me:()=>{},focusConversationTab:ae,setSearchParams:c,historyModalOpen:se,activeConv:Q,isRefreshingHistory:td,ides:f,handleRefreshHistory:sd});const rd=i.useMemo(()=>!Q||!Ze(Q)||qe(Q)?null:_s(Q),[Q]),{versionMismatchDaemons:nd,hasRequiredVersionDaemons:mo,appVersion:ad,versionBannerDismissed:od,setVersionBannerDismissed:id,upgradingDaemons:cd,handleBannerUpgrade:ld}=Xh({ides:f,sendDaemonCommand:e}),fo=i.useCallback(Ue=>{we(Ue),ye(Ue)},[ye,we]),dd=i.useCallback(Ue=>{re(Ue)},[re]);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(lp,{terminalBackend:ne,isStandalone:pe,machineLabel:Z,machineKey:ee}),(!od||mo)&&s.jsx(Ab,{daemons:nd,targetVersion:ad,required:mo,upgradingDaemons:cd,onUpgrade:ld,onDismiss:()=>id(!0)}),s.jsx(jb,{showMobileChatMode:mr,isMobile:G,activeConv:Q,wsStatus:w,isConnected:R,onOpenHistory:Ue=>{Ue&&Qe(Ue),ge()},onOpenRemote:fe,onStopCli:He,activeCliViewMode:rd,onSetActiveCliViewMode:ed,mobileChatConversations:Vl,ides:f,actionLogs:he,sendDaemonCommand:e,setActionLogs:Y,setCliViewModeOverrides:J,isStandalone:pe,initialDataLoaded:v,userName:h.userName,requestedMobileTabKey:Me,onRequestedMobileTabConsumed:Re,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Fe,isSplitMode:ft,numGroups:ct,groupSizes:$,groupedConvs:H,clearedTabs:ue,focusedGroup:W,focusGroup:M,moveTabToGroup:_,splitTabRelative:F,closeGroup:T,handleResizeStart:P,groupActiveTabIds:E,setGroupActiveTab:K,groupTabOrders:N,setGroupTabOrder:z,toggleHiddenTab:Ue=>je(Le.get(Ue)||{tabKey:Ue}),visibleConversations:tt,hiddenConversations:Gl,requestedDesktopTabKey:$e,onRequestedDesktopTabConsumed:Re,onDesktopActiveTabChange:De,onRequestScrollToBottom:ce,onHideConversation:dd,onShowHiddenConversation:fo,onShowAllHiddenConversations:te,scrollToBottomRequest:Ne,machineEntries:Se,layoutProfile:C,onBrowseMachineDirectory:Yl,onSaveMachineWorkspace:Xl,onLaunchMachineIde:Jl,onLaunchMachineProvider:Ql,onListMachineSavedSessions:Zl,notifications:Ye,notificationUnreadCount:mt,liveSessionInboxState:Xe,onMarkNotificationRead:pt,onMarkNotificationUnread:dt,onDeleteNotification:Te}),s.jsx("style",{children:`
66
66
  body { overflow: hidden; overscroll-behavior: none; }
67
- `}),s.jsx(gb,{historyModal:{open:se,targetConv:Me,ides:f,isCreatingChat:at,isRefreshingHistory:Ee?!1:yt,savedSessions:El,savedHistoryFilters:$l,onSavedHistoryFiltersChange:Bl,isSavedSessionsLoading:Kl,isResumingSavedSessionId:Ol,onClose:Be,onNewChat:Ut,onSwitchSession:ut,onRefreshHistory:Ee?Wl:ur,onResumeSavedSession:Hl},remoteDialog:{conversation:We,ideEntry:Ae,ides:f,connectionStates:g,actionLogs:he,sendDaemonCommand:e,setActionLogs:Y,isStandalone:pe,userName:h.userName,onOpenHistory:Ue=>{Ue&&Qe(Ue),ge()},onConversationChange:Qe,onClose:_e},cliStopDialog:{open:rt,targetConv:nt,onCancel:It,onStopNow:async()=>{await O("hard")},onSaveAndStop:async()=>{await O("save")}},connectionBanner:{wsStatus:v,showReconnected:M,loginUrl:h.connectionLoginUrl,onReconnect:h.retryServerConnection},toastOverlay:{toasts:b,onDismiss:Ue=>p(Mt=>Mt.filter(Ds=>Ds.id!==Ue)),onClick:Ue=>{if(Ue.targetKey){const Mt=Pe(Ue.targetKey);Mt&&(ne(Mt.tabKey,Ge),fo(Mt),ce(Mt.tabKey,"toast-open"))}}},onboarding:{open:y,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}x(!1)}}})]})}function Sb({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[o,c]=i.useState([]),[l,u]=i.useState(null),[m,d]=i.useState(null),[h,f]=i.useState(!1),[w,k]=i.useState(null),[p,y]=i.useState(!1),[x,b]=i.useState(""),v=i.useRef(null),R=i.useCallback($=>{v.current=$},[]),g=i.useCallback(($,B,V=!1)=>{c(G=>[...G.slice(-100),{timestamp:Date.now(),level:$,message:B}]),setTimeout(()=>{var G;return(G=a.current)==null?void 0:G.scrollIntoView({behavior:"smooth"})},100),V&&et.showToast(B,$==="error"||$==="warn"?"warning":"success")},[a]),M=i.useCallback($=>{const B=$ instanceof Error?$.message:String($||"");return B.includes("P2P command timeout")||B.includes("P2P not connected")||B.includes("P2P not available")},[]),C=i.useCallback(async($,B)=>{var V;if(!e||l)return!1;u($),g("info",`Launching ${ot($)}${B!=null&&B.workspace?` in ${B.workspace}`:""}...`);try{const G={ideType:$,enableCdp:!0};(V=B==null?void 0:B.workspace)!=null&&V.trim()?G.workspace=B.workspace.trim():B!=null&&B.useDefaultWorkspace&&(G.useDefaultWorkspace=!0);const me=await r(e,"launch_ide",G);return g(me!=null&&me.success?"info":"error",me!=null&&me.success?`${ot($)} launched`:`Failed: ${me==null?void 0:me.error}`,!0),!!(me!=null&&me.success)}catch(G){return g("error",`Launch error: ${G.message}`,!0),!1}finally{u(null)}},[e,l,g,r]),S=i.useCallback(async $=>{if(!e)return{success:!1};const{cliType:B,dir:V,workspaceId:G,useDefaultWorkspace:me,useHome:ne,argsStr:xe,model:de,resumeSessionId:be}=$;if(!B)return g("warn","Select a CLI or ACP provider first",!0),{success:!1};const he=xe?xe.split(/\s+/).filter(Boolean):void 0,Y=(V==null?void 0:V.trim())||(G?"(saved id)":me?"(default workspace)":ne?"(home)":"");g("info",`Launching ${B}${Y?` in ${Y}`:""}${de?` (model: ${de})`:""}...`),d(B);try{const oe={cliType:B,cliArgs:he,initialModel:de||void 0};V!=null&&V.trim()?oe.dir=V.trim():G?oe.workspaceId=G:me?oe.useDefaultWorkspace=!0:ne&&(oe.useHome=!0),be&&(oe.resumeSessionId=be);const J=await r(e,"launch_cli",oe),ue=(J==null?void 0:J.result)||J;return J!=null&&J.success?(g("info",`${B} launched`,!0),(ue==null?void 0:ue.launchSource)==="home"?g("info","📂 Running in home directory (explicit choice)"):(ue==null?void 0:ue.launchSource)==="defaultWorkspace"&&g("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ue==null?void 0:ue.sessionId}):(g("error",`Failed: ${(J==null?void 0:J.error)||(ue==null?void 0:ue.error)}`,!0),(J==null?void 0:J.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&k({cliType:B,argsStr:xe,model:de}),{success:!1,sessionId:ue==null?void 0:ue.sessionId})}catch(oe){return M(oe)?(g("warn",`${B} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(g("error",`Launch error: ${oe.message}`,!0),{success:!1})}finally{d(null)}},[e,g,M,r]),j=i.useCallback(async($,B,V,G)=>e?$?B.trim()?S({cliType:$,dir:B,argsStr:V,model:G}):(k({cliType:$,argsStr:V,model:G}),{success:!1}):(g("warn","Select a provider",!0),{success:!1}):{success:!1},[e,g,S]),W=i.useCallback(async($,B,V)=>{if(e&&window.confirm(`Stop ${$}?
68
- This will terminate the process.`))try{const G=await r(e,"stop_cli",{cliType:$,dir:B,targetSessionId:V});G!=null&&G.success?g("info",`${$} stopped`,!0):g("error",`Stop failed: ${(G==null?void 0:G.error)||"Unknown error"}`,!0)}catch(G){g("error",`Stop failed: ${G.message}`,!0)}},[e,g,r]),L=i.useCallback(async $=>{try{await r($.daemonId,"restart_ide",{ideType:$.type}),g("info",`${ot($.type)} restart initiated`,!0)}catch(B){g("error",`Restart failed: ${B.message}`,!0)}},[g,r]),I=i.useCallback(async $=>{if(window.confirm(`Stop ${ot($.type)}?
69
- This will disconnect CDP and optionally kill the process.`))try{const B=await r($.daemonId,"stop_ide",{ideType:$.type,killProcess:!0});B!=null&&B.success?g("info",`${ot($.type)} stopped`,!0):g("error",`Stop failed: ${(B==null?void 0:B.error)||"Unknown error"}`,!0)}catch(B){g("error",`Stop failed: ${B.message}`,!0)}},[g,r]),D=i.useCallback(async()=>{if(e)try{const $=await r(e,"detect_ides",{});g("info",`Found ${(($==null?void 0:$.result)||[]).length} IDE(s)`,!0)}catch($){g("error",`Detection failed: ${$.message}`,!0)}},[e,g,r]),U=i.useCallback(async $=>{if(!e||!$.trim())return!1;f(!0);try{const B=await r(e,"workspace_add",{path:$.trim()});return B!=null&&B.success?(g("info",`Workspace added: ${$.trim()}`),!0):(g("error",(B==null?void 0:B.error)||"workspace_add failed"),!1)}catch(B){return g("error",B.message),!1}finally{f(!1)}},[e,g,r]),K=i.useCallback(async $=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){f(!0);try{const B=await r(e,"workspace_remove",{id:$});B!=null&&B.success?g("info","Workspace removed",!0):g("error",(B==null?void 0:B.error)||"workspace_remove failed",!0)}catch(B){g("error",B.message,!0)}finally{f(!1)}}},[e,g,r]),N=i.useCallback(async $=>{var B;if(e){f(!0);try{const V=await r(e,"workspace_set_default",$===null?{clear:!0}:{id:$});if(V!=null&&V.success){g("info",$?"Default workspace updated":"Default workspace cleared",!0);const G=typeof V.defaultWorkspacePath=="string"?V.defaultWorkspacePath:"";G&&((B=v.current)==null||B.call(v,G))}else g("error",(V==null?void 0:V.error)||"workspace_set_default failed",!0)}catch(V){g("error",V.message,!0)}finally{f(!1)}}},[e,g,r]),A=i.useCallback(async $=>{var V;if(!e||!$.trim())return;const B=$.trim();f(!0);try{const G=await r(e,"workspace_set_default",{path:B});G!=null&&G.success?(g("info","Default workspace set from history"),(V=v.current)==null||V.call(v,B)):g("error",(G==null?void 0:G.error)||"Could not set default (path missing on disk?)")}catch(G){g("error",G.message)}finally{f(!1)}},[e,g,r]),z=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($){g("warn",`Live nickname updated, but account sync failed: ${$.message}`)}g("info",`Nickname set to "${x||"(cleared)"}"`),y(!1)}catch($){g("error",`Failed: ${$.message}`)}},[e,x,t,g,n,r]);return{logs:o,launchingIde:l,launchingAgentType:m,workspaceBusy:h,launchPick:w,setLaunchPick:k,editingNickname:p,setEditingNickname:y,nicknameInput:x,setNicknameInput:b,addLog:g,handleLaunchIde:C,runLaunchCliCore:S,handleLaunchCli:j,handleStopCli:W,handleRestartIde:L,handleStopIde:I,handleDetectIdes:D,handleWorkspaceAdd:U,handleWorkspaceRemove:K,handleWorkspaceSetDefault:N,handleWorkspaceResumePath:A,handleSaveNickname:z,setOnDefaultWorkspaceChanged:R}}function Nb({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:c}){var L;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:m,handleWorkspaceSetDefault:d}=o,[h,f]=i.useState(!1),[w,k]=i.useState(""),[p,y]=i.useState([]),[x,b]=i.useState(!1),[v,R]=i.useState(""),g=i.useCallback(async I=>{b(!0),R("");try{const D=await un(c,e,I);k(D.path),y(D.directories)}catch(D){R(D instanceof Error?D.message:"Could not load folder")}finally{b(!1)}},[e,c]),M=i.useCallback(()=>{f(!0);const I=[...r.map(U=>U.workspace),...n.map(U=>U.workspace),...a.map(U=>U.workspace)],D=dn(t.platform,ln(I,t.defaultWorkspacePath,(t.workspaces||[]).map(U=>U.path)));g(D)},[a,n,r,g,t.defaultWorkspacePath,t.platform,t.workspaces]),C=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,S=t.availableMem??t.freeMem??t.totalMem,j=C&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-S)/t.totalMem*100))):0,W=((L=t.loadavg)==null?void 0:L[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(hr,{icon:s.jsx(Ui,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?Hu(t.uptime):"Waiting…"}),s.jsx(hr,{icon:s.jsx(Nt,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(hr,{icon:s.jsx(Ma,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(hr,{icon:s.jsx(Jd,{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(Co,{value:C?Math.min(Math.round(W/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:C?`${W.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Co,{value:j,max:100,label:"Memory",color:"#3b82f6",detail:C?`${vn(t.totalMem-S)} / ${vn(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${vn(t.totalMem)} total`})]})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[s.jsx(Ns,{size:14})," Workspaces"]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),s.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:l,value:t.defaultWorkspaceId||"",onChange:I=>void d(I.target.value===""?null:I.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(I=>s.jsx("option",{value:I.id,children:I.label||I.path},I.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(I=>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:[I.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:nn(I.path,I.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:I.path,children:I.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void m(I.id),children:"Remove"})]},I.id))})]}),h&&s.jsx(mn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:w,directories:p,busy:x,error:v,confirmLabel:"Add workspace",onClose:()=>f(!1),onNavigate:I=>{g(I)},onConfirm:I=>{(async()=>{if(!I)return;await u(I)&&f(!1)})()}})]})}function Cb(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 Tb(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(u=>u.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 Hn(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 hi(e){if(!e||typeof e!="object")return null;if(Hn(e))return e;const t=e,r=t.result;return Hn(r)?r:Hn(t.sourceConfig)?t.sourceConfig:null}function Ib(e){const t=e.trim();return t||null}const xi=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Mb=[{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 Ab({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,o]=i.useState("config"),[c,l]=i.useState("codex-cli"),[u,m]=i.useState([]),[d,h]=i.useState(""),[f,w]=i.useState([]),[k,p]=i.useState(""),y=i.useRef(null),x=i.useRef(null),b=S=>{m(j=>j.includes(S)?j.filter(W=>W!==S):[...j,S])},v=()=>m([...xi]),R=()=>m([]);i.useEffect(()=>{var S;(S=y.current)==null||S.scrollIntoView({behavior:"smooth"})},[f]),i.useEffect(()=>()=>{x.current&&clearInterval(x.current)},[]);const g=i.useCallback(()=>{x.current&&clearInterval(x.current),x.current=setInterval(async()=>{try{const S=await r(e,"provider_auto_fix_status",{providerType:t.type});(S==null?void 0:S.running)===!1&&a==="running"&&(o("done"),w(j=>[...j,`
70
- ✅ Auto-fix completed!`]),x.current&&clearInterval(x.current))}catch{}},3e3)},[e,t.type,r,a]),M=async()=>{if(u.length!==0){o("running"),w(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,d?`💬 Comment: ${d}`:"",""]),p("");try{const S=await r(e,"provider_auto_fix",{providerType:t.type,functions:u,agent:c,...d?{comment:d}:{}});S!=null&&S.success&&(S!=null&&S.started||S!=null&&S.running)?(w(j=>[...j,"✅ Agent started. Monitoring progress..."]),g()):(o("error"),p((S==null?void 0:S.error)||"Failed to start auto-fix"))}catch(S){o("error"),p((S==null?void 0:S.message)||"Connection failed")}}},C=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),w(S=>[...S,`
71
- ⚠️ 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:S=>S.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:Mb.map(S=>s.jsxs("button",{onClick:()=>l(S.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===S.value?S.color+"66":"var(--border-subtle)",background:c===S.value?S.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===S.value?S.color:"var(--text-primary)"},children:S.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:S.desc})]},S.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:R,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:xi.map(S=>s.jsxs("button",{onClick:()=>b(S),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(S)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(S)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(S)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(S)?"☑ ":"☐ ",S]},S))})]}),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:d,onChange:S=>h(S.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:[f.map((S,j)=>s.jsx("div",{className:S.startsWith("✅")?"text-green-400":"",style:S.startsWith("❌")||S.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:S},j)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:y})]}),k&&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:k})]})]}),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"&&u.length>0&&`${u.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:u.length===0,className:"machine-btn",style:{background:u.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:u.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:u.length>0?"#a78bfa":void 0,opacity:u.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&s.jsx("button",{onClick:C,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"),w([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Lb({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)||""),[u,m]=i.useState(""),[d,h]=i.useState(""),[f,w]=i.useState(!1),[k,p]=i.useState(""),[y,x]=i.useState(!1),b=M=>{const C=M.toLowerCase().replace(/[^a-z0-9-]/g,"");m(C),(!d||d===v(u))&&h(v(C))},v=M=>M.split("-").map(C=>C.charAt(0).toUpperCase()+C.slice(1)).join(" "),R=async()=>{if(!(!u||!d||!c)){w(!0),p("");try{const M=await r(e,"provider_clone",{type:u,name:d,category:"ide",location:"user",cloneFrom:c});M!=null&&M.success||M!=null&&M.created?(x(!0),a==null||a(u)):p((M==null?void 0:M.error)||"Failed to create provider")}catch(M){p((M==null?void 0:M.message)||"Connection failed")}w(!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:y?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:u})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",u,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",u]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:o.map(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:u,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/",u||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:d,onChange:M=>h(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"})]}),k&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:k})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:y?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:R,disabled:!u||!d||f,className:"machine-btn",style:{background:u&&d?"rgba(34,197,94,0.12)":void 0,borderColor:u&&d?"rgba(34,197,94,0.3)":void 0,color:u&&d?"#86efac":void 0,opacity:!u||!d||f?.4:1},children:f?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function bi(e){return e==="cli"||e==="acp"}function Rb(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 _b(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 gi(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 Pb({machineId:e,providers:t,sendDaemonCommand:r}){var U;const[n,a]=i.useState([]),[o,c]=i.useState(!1),[l,u]=i.useState(null),[m,d]=i.useState("all"),[h,f]=i.useState(null),[w,k]=i.useState(!1),[p,y]=i.useState(null),[x,b]=i.useState("normal"),[v,R]=i.useState(""),[g,M]=i.useState(!1),C=i.useCallback(async()=>{if(e)try{const K=await r(e,"get_provider_source_config",{}),N=hi(K);N&&(y(N),b(N.sourceMode),R(N.explicitProviderDir||""))}catch{}},[e,r]),S=i.useCallback(async()=>{if(e){c(!0);try{const K=await r(e,"get_provider_settings",{}),N=Cb(K);if(N){const A=Tb(N,t,{filterSchema:z=>z.filter($=>$.key!=="enabled")});A.sort((z,$)=>z.category.localeCompare($.category)||z.displayName.localeCompare($.displayName)),a(A)}}catch{}c(!1)}},[e,t,r]);i.useEffect(()=>{n.length===0&&S(),p||C()},[]);const j=async(K,N,A)=>{u(`${K}.${N}`),a(z=>z.map($=>$.type===K?{...$,values:{...$.values,[N]:A}}:$));try{const z=await r(e,"set_provider_setting",{providerType:K,key:N,value:A});z!=null&&z.success||S()}catch{S()}u(null)},W=async(K,N)=>{await j(K,"enabled",N),await S()},L=async K=>{u(`${K}.detect`);try{await r(e,"detect_provider",{providerType:K})}finally{await S(),u(null)}},I=async K=>{await j(K,"executablePath",""),await j(K,"executableArgs",""),await S()},D=async()=>{M(!0);try{const K=await r(e,"set_provider_source_config",{providerSourceMode:x,providerDir:Ib(v)}),N=hi(K);N?(y(N),b(N.sourceMode),R(N.explicitProviderDir||"")):await C(),await S()}catch{await C()}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(K=>s.jsx("button",{onClick:()=>d(K),className:`machine-btn text-[10px] px-2 py-0.5 ${m===K?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:K.toUpperCase()},K))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>k(!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:S,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:C,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:K=>b(K.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),s.jsx("input",{type:"text",value:v,onChange:K=>R(K.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void D(),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:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((U=p==null?void 0:p.providerRoots)==null?void 0:U.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(K=>K.category===m).length>1&&(()=>{const K=n.filter($=>$.category===m),N=new Map;for(const $ of K)for(const B of $.schema){if(B.type!=="boolean")continue;const V=N.get(B.key),G=!!($.values[B.key]??B.default);V?(V.onCount+=G?1:0,V.total+=1):N.set(B.key,{label:B.label||B.key,onCount:G?1:0,total:1})}const A=[...N.entries()].filter(([,$])=>$.total===K.length);if(A.length===0)return null;const z=async($,B)=>{for(const V of K)await j(V.type,$,B)};return s.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[s.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",K.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:A.map(([$,B])=>{const V=B.onCount===B.total,G=B.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:B.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",B.onCount,"/",B.total,")"]}),s.jsx("button",{onClick:()=>void z($,!0),disabled:V,className:`machine-btn text-[9px] px-1.5 py-px ${V?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void z($,!1),disabled:G,className:`machine-btn text-[9px] px-1.5 py-px ${G?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},$)})})]})})(),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(K=>m==="all"||K.category===m).map(K=>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:K.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:K.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:K.category==="acp"?"rgba(139,92,246,0.08)":K.category==="cli"?"rgba(59,130,246,0.08)":K.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:K.category==="acp"?"#a78bfa":K.category==="cli"?"#60a5fa":K.category==="ide"?"#86efac":"var(--status-warning)"},children:K.category}),bi(K.category)&&(()=>{const N=t.find($=>$.type===K.type),A=(N==null?void 0:N.enabled)===!0||K.values.enabled===!0,z=(N==null?void 0:N.machineStatus)||(A?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${_b(z)}`,children:Rb(z)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void W(K.type,!A),disabled:l===`${K.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${A?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:A?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void L(K.type),disabled:!A||l===`${K.type}.detect`,title:A?"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 ${A?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void I(K.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),K.category==="ide"&&s.jsx("button",{onClick:()=>f(t.find(N=>N.type===K.type)||{type:K.type,name:K.displayName,displayName:K.displayName,icon:K.icon,category:K.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"})]}),bi(K.category)&&(()=>{const N=t.find(A=>A.type===K.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:"})," ",gi(N==null?void 0:N.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",gi(N==null?void 0:N.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:K.schema.map(N=>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:[N.label||N.key,l===`${K.type}.${N.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),N.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:N.description})]}),s.jsx("div",{className:"shrink-0",children:N.type==="boolean"?s.jsx("button",{onClick:()=>j(K.type,N.key,!(K.values[N.key]??N.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:K.values[N.key]??N.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:K.values[N.key]??N.default?21:3}})}):N.type==="number"?s.jsx("input",{type:"number",value:Number(K.values[N.key]??N.default??0)||0,min:N.min,max:N.max,onChange:A=>{const z=parseInt(A.target.value)||0;N.min!==void 0&&z<N.min||N.max!==void 0&&z>N.max||j(K.type,N.key,z)},className:"machine-input w-20 text-center text-[11px]"}):N.type==="select"&&N.options?s.jsx("select",{value:String(K.values[N.key]??N.default??""),onChange:A=>j(K.type,N.key,A.target.value),className:"machine-input text-[11px]",children:N.options.map(A=>s.jsx("option",{value:A,children:A},A))}):s.jsx("input",{type:"text",value:String(K.values[N.key]??N.default??""),onBlur:A=>j(K.type,N.key,A.target.value),className:"machine-input w-[120px] text-[11px]"})})]},N.key))})]},K.type))}),h&&s.jsx(Ab,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>f(null)}),w&&s.jsx(Lb,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>k(!1),onCreated:()=>{k(!1),S()}})]})}const Db=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Eb({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function $b(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function Bb(e){return e.trim().toLowerCase()}function pn(e,t){const r=Bb(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function io(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function As(e,t=220){const r=io(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function Kb(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 Ob(e,t){return e.filter(r=>pn([r.level,r.message],t))}function yi(e){return`${e.timestamp}:${e.level}:${e.message}`}function Wb(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const c of e.entries)n.set(yi(c),c);for(const c of t.entries)n.set(yi(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 Hb(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 Fb(e,t){return e.split(`
72
- `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>pn([r],t))}function Ub(e,t){return e.filter(r=>pn([r.level,r.category,r.stage,r.interactionId,io(r.payload)],t))}function zb(e,t){return e.filter(r=>pn([r.kind,r.topic,r.interactionId,io(r.payload)],t))}function vi(e){return e==="warn"||e==="error"}function Vb({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=>vi(a.level)).length+r.filter(a=>vi(a.level)).length}}function Gb({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(`
67
+ `}),s.jsx(Ib,{historyModal:{open:se,targetConv:Ie,ides:f,isCreatingChat:at,isRefreshingHistory:Ee?!1:yt,savedSessions:Kl,savedHistoryFilters:Ol,onSavedHistoryFiltersChange:Wl,isSavedSessionsLoading:Hl,isResumingSavedSessionId:Fl,onClose:Be,onNewChat:Ut,onSwitchSession:ut,onRefreshHistory:Ee?Ul:ur,onResumeSavedSession:zl},remoteDialog:{conversation:We,ideEntry:Ae,ides:f,connectionStates:g,actionLogs:he,sendDaemonCommand:e,setActionLogs:Y,isStandalone:pe,userName:h.userName,onOpenHistory:Ue=>{Ue&&Qe(Ue),ge()},onConversationChange:Qe,onClose:_e},cliStopDialog:{open:rt,targetConv:nt,onCancel:Mt,onStopNow:async()=>{await O("hard")},onSaveAndStop:async()=>{await O("save")}},connectionBanner:{wsStatus:w,showReconnected:I,loginUrl:h.connectionLoginUrl,onReconnect:h.retryServerConnection},toastOverlay:{toasts:b,onDismiss:Ue=>p(It=>It.filter(Ds=>Ds.id!==Ue)),onClick:Ue=>{if(Ue.targetKey){const It=Pe(Ue.targetKey);It&&(ae(It.tabKey,Ge),fo(It),ce(It.tabKey,"toast-open"))}}},onboarding:{open:y,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}x(!1)}}})]})}function Db({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[o,c]=i.useState([]),[l,u]=i.useState(null),[m,d]=i.useState(null),[h,f]=i.useState(!1),[v,j]=i.useState(null),[p,y]=i.useState(!1),[x,b]=i.useState(""),w=i.useRef(null),R=i.useCallback($=>{w.current=$},[]),g=i.useCallback(($,B,G=!1)=>{c(V=>[...V.slice(-100),{timestamp:Date.now(),level:$,message:B}]),setTimeout(()=>{var V;return(V=a.current)==null?void 0:V.scrollIntoView({behavior:"smooth"})},100),G&&et.showToast(B,$==="error"||$==="warn"?"warning":"success")},[a]),I=i.useCallback($=>{const B=$ instanceof Error?$.message:String($||"");return B.includes("P2P command timeout")||B.includes("P2P not connected")||B.includes("P2P not available")},[]),C=i.useCallback(async($,B)=>{var G;if(!e||l)return!1;u($),g("info",`Launching ${ot($)}${B!=null&&B.workspace?` in ${B.workspace}`:""}...`);try{const V={ideType:$,enableCdp:!0};(G=B==null?void 0:B.workspace)!=null&&G.trim()?V.workspace=B.workspace.trim():B!=null&&B.useDefaultWorkspace&&(V.useDefaultWorkspace=!0);const me=await r(e,"launch_ide",V);return g(me!=null&&me.success?"info":"error",me!=null&&me.success?`${ot($)} launched`:`Failed: ${me==null?void 0:me.error}`,!0),!!(me!=null&&me.success)}catch(V){return g("error",`Launch error: ${V.message}`,!0),!1}finally{u(null)}},[e,l,g,r]),S=i.useCallback(async $=>{if(!e)return{success:!1};const{cliType:B,dir:G,workspaceId:V,useDefaultWorkspace:me,useHome:ae,argsStr:xe,model:de,resumeSessionId:be}=$;if(!B)return g("warn","Select a CLI or ACP provider first",!0),{success:!1};const he=xe?xe.split(/\s+/).filter(Boolean):void 0,Y=(G==null?void 0:G.trim())||(V?"(saved id)":me?"(default workspace)":ae?"(home)":"");g("info",`Launching ${B}${Y?` in ${Y}`:""}${de?` (model: ${de})`:""}...`),d(B);try{const oe={cliType:B,cliArgs:he,initialModel:de||void 0};G!=null&&G.trim()?oe.dir=G.trim():V?oe.workspaceId=V:me?oe.useDefaultWorkspace=!0:ae&&(oe.useHome=!0),be&&(oe.resumeSessionId=be);const J=await r(e,"launch_cli",oe),ue=(J==null?void 0:J.result)||J;return J!=null&&J.success?(g("info",`${B} launched`,!0),(ue==null?void 0:ue.launchSource)==="home"?g("info","📂 Running in home directory (explicit choice)"):(ue==null?void 0:ue.launchSource)==="defaultWorkspace"&&g("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ue==null?void 0:ue.sessionId}):(g("error",`Failed: ${(J==null?void 0:J.error)||(ue==null?void 0:ue.error)}`,!0),(J==null?void 0:J.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&j({cliType:B,argsStr:xe,model:de}),{success:!1,sessionId:ue==null?void 0:ue.sessionId})}catch(oe){return I(oe)?(g("warn",`${B} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(g("error",`Launch error: ${oe.message}`,!0),{success:!1})}finally{d(null)}},[e,g,I,r]),k=i.useCallback(async($,B,G,V)=>e?$?B.trim()?S({cliType:$,dir:B,argsStr:G,model:V}):(j({cliType:$,argsStr:G,model:V}),{success:!1}):(g("warn","Select a provider",!0),{success:!1}):{success:!1},[e,g,S]),W=i.useCallback(async($,B,G)=>{if(e&&window.confirm(`Stop ${$}?
68
+ This will terminate the process.`))try{const V=await r(e,"stop_cli",{cliType:$,dir:B,targetSessionId:G});V!=null&&V.success?g("info",`${$} stopped`,!0):g("error",`Stop failed: ${(V==null?void 0:V.error)||"Unknown error"}`,!0)}catch(V){g("error",`Stop failed: ${V.message}`,!0)}},[e,g,r]),L=i.useCallback(async $=>{try{await r($.daemonId,"restart_ide",{ideType:$.type}),g("info",`${ot($.type)} restart initiated`,!0)}catch(B){g("error",`Restart failed: ${B.message}`,!0)}},[g,r]),M=i.useCallback(async $=>{if(window.confirm(`Stop ${ot($.type)}?
69
+ This will disconnect CDP and optionally kill the process.`))try{const B=await r($.daemonId,"stop_ide",{ideType:$.type,killProcess:!0});B!=null&&B.success?g("info",`${ot($.type)} stopped`,!0):g("error",`Stop failed: ${(B==null?void 0:B.error)||"Unknown error"}`,!0)}catch(B){g("error",`Stop failed: ${B.message}`,!0)}},[g,r]),E=i.useCallback(async()=>{if(e)try{const $=await r(e,"detect_ides",{});g("info",`Found ${(($==null?void 0:$.result)||[]).length} IDE(s)`,!0)}catch($){g("error",`Detection failed: ${$.message}`,!0)}},[e,g,r]),U=i.useCallback(async $=>{if(!e||!$.trim())return!1;f(!0);try{const B=await r(e,"workspace_add",{path:$.trim()});return B!=null&&B.success?(g("info",`Workspace added: ${$.trim()}`),!0):(g("error",(B==null?void 0:B.error)||"workspace_add failed"),!1)}catch(B){return g("error",B.message),!1}finally{f(!1)}},[e,g,r]),K=i.useCallback(async $=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){f(!0);try{const B=await r(e,"workspace_remove",{id:$});B!=null&&B.success?g("info","Workspace removed",!0):g("error",(B==null?void 0:B.error)||"workspace_remove failed",!0)}catch(B){g("error",B.message,!0)}finally{f(!1)}}},[e,g,r]),N=i.useCallback(async $=>{var B;if(e){f(!0);try{const G=await r(e,"workspace_set_default",$===null?{clear:!0}:{id:$});if(G!=null&&G.success){g("info",$?"Default workspace updated":"Default workspace cleared",!0);const V=typeof G.defaultWorkspacePath=="string"?G.defaultWorkspacePath:"";V&&((B=w.current)==null||B.call(w,V))}else g("error",(G==null?void 0:G.error)||"workspace_set_default failed",!0)}catch(G){g("error",G.message,!0)}finally{f(!1)}}},[e,g,r]),A=i.useCallback(async $=>{var G;if(!e||!$.trim())return;const B=$.trim();f(!0);try{const V=await r(e,"workspace_set_default",{path:B});V!=null&&V.success?(g("info","Default workspace set from history"),(G=w.current)==null||G.call(w,B)):g("error",(V==null?void 0:V.error)||"Could not set default (path missing on disk?)")}catch(V){g("error",V.message)}finally{f(!1)}},[e,g,r]),z=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($){g("warn",`Live nickname updated, but account sync failed: ${$.message}`)}g("info",`Nickname set to "${x||"(cleared)"}"`),y(!1)}catch($){g("error",`Failed: ${$.message}`)}},[e,x,t,g,n,r]);return{logs:o,launchingIde:l,launchingAgentType:m,workspaceBusy:h,launchPick:v,setLaunchPick:j,editingNickname:p,setEditingNickname:y,nicknameInput:x,setNicknameInput:b,addLog:g,handleLaunchIde:C,runLaunchCliCore:S,handleLaunchCli:k,handleStopCli:W,handleRestartIde:L,handleStopIde:M,handleDetectIdes:E,handleWorkspaceAdd:U,handleWorkspaceRemove:K,handleWorkspaceSetDefault:N,handleWorkspaceResumePath:A,handleSaveNickname:z,setOnDefaultWorkspaceChanged:R}}function Eb({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:c}){var L;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:m,handleWorkspaceSetDefault:d}=o,[h,f]=i.useState(!1),[v,j]=i.useState(""),[p,y]=i.useState([]),[x,b]=i.useState(!1),[w,R]=i.useState(""),g=i.useCallback(async M=>{b(!0),R("");try{const E=await mn(c,e,M);j(E.path),y(E.directories)}catch(E){R(E instanceof Error?E.message:"Could not load folder")}finally{b(!1)}},[e,c]),I=i.useCallback(()=>{f(!0);const M=[...r.map(U=>U.workspace),...n.map(U=>U.workspace),...a.map(U=>U.workspace)],E=un(t.platform,dn(M,t.defaultWorkspacePath,(t.workspaces||[]).map(U=>U.path)));g(E)},[a,n,r,g,t.defaultWorkspacePath,t.platform,t.workspaces]),C=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,S=t.availableMem??t.freeMem??t.totalMem,k=C&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-S)/t.totalMem*100))):0,W=((L=t.loadavg)==null?void 0:L[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(hr,{icon:s.jsx(zi,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?zu(t.uptime):"Waiting…"}),s.jsx(hr,{icon:s.jsx(Nt,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(hr,{icon:s.jsx(Ia,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(hr,{icon:s.jsx(eu,{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(Co,{value:C?Math.min(Math.round(W/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:C?`${W.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Co,{value:k,max:100,label:"Memory",color:"#3b82f6",detail:C?`${wn(t.totalMem-S)} / ${wn(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${wn(t.totalMem)} total`})]})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[s.jsx(Ns,{size:14})," Workspaces"]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),s.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:l,value:t.defaultWorkspaceId||"",onChange:M=>void d(M.target.value===""?null:M.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(M=>s.jsx("option",{value:M.id,children:M.label||M.path},M.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:I,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(M=>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:[M.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:an(M.path,M.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:M.path,children:M.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void m(M.id),children:"Remove"})]},M.id))})]}),h&&s.jsx(fn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:v,directories:p,busy:x,error:w,confirmLabel:"Add workspace",onClose:()=>f(!1),onNavigate:M=>{g(M)},onConfirm:M=>{(async()=>{if(!M)return;await u(M)&&f(!1)})()}})]})}function $b(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 Bb(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(u=>u.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 Fn(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 xi(e){if(!e||typeof e!="object")return null;if(Fn(e))return e;const t=e,r=t.result;return Fn(r)?r:Fn(t.sourceConfig)?t.sourceConfig:null}function Kb(e){const t=e.trim();return t||null}const bi=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Ob=[{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 Wb({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,o]=i.useState("config"),[c,l]=i.useState("codex-cli"),[u,m]=i.useState([]),[d,h]=i.useState(""),[f,v]=i.useState([]),[j,p]=i.useState(""),y=i.useRef(null),x=i.useRef(null),b=S=>{m(k=>k.includes(S)?k.filter(W=>W!==S):[...k,S])},w=()=>m([...bi]),R=()=>m([]);i.useEffect(()=>{var S;(S=y.current)==null||S.scrollIntoView({behavior:"smooth"})},[f]),i.useEffect(()=>()=>{x.current&&clearInterval(x.current)},[]);const g=i.useCallback(()=>{x.current&&clearInterval(x.current),x.current=setInterval(async()=>{try{const S=await r(e,"provider_auto_fix_status",{providerType:t.type});(S==null?void 0:S.running)===!1&&a==="running"&&(o("done"),v(k=>[...k,`
70
+ ✅ Auto-fix completed!`]),x.current&&clearInterval(x.current))}catch{}},3e3)},[e,t.type,r,a]),I=async()=>{if(u.length!==0){o("running"),v(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,d?`💬 Comment: ${d}`:"",""]),p("");try{const S=await r(e,"provider_auto_fix",{providerType:t.type,functions:u,agent:c,...d?{comment:d}:{}});S!=null&&S.success&&(S!=null&&S.started||S!=null&&S.running)?(v(k=>[...k,"✅ Agent started. Monitoring progress..."]),g()):(o("error"),p((S==null?void 0:S.error)||"Failed to start auto-fix"))}catch(S){o("error"),p((S==null?void 0:S.message)||"Connection failed")}}},C=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),v(S=>[...S,`
71
+ ⚠️ 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:S=>S.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:Ob.map(S=>s.jsxs("button",{onClick:()=>l(S.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===S.value?S.color+"66":"var(--border-subtle)",background:c===S.value?S.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===S.value?S.color:"var(--text-primary)"},children:S.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:S.desc})]},S.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:w,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:R,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:bi.map(S=>s.jsxs("button",{onClick:()=>b(S),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(S)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(S)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(S)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(S)?"☑ ":"☐ ",S]},S))})]}),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:d,onChange:S=>h(S.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:[f.map((S,k)=>s.jsx("div",{className:S.startsWith("✅")?"text-green-400":"",style:S.startsWith("❌")||S.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:S},k)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:y})]}),j&&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:j})]})]}),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"&&u.length>0&&`${u.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:I,disabled:u.length===0,className:"machine-btn",style:{background:u.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:u.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:u.length>0?"#a78bfa":void 0,opacity:u.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&s.jsx("button",{onClick:C,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"),v([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Hb({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var g;const o=t.filter(I=>I.category==="ide"),[c,l]=i.useState(((g=o[0])==null?void 0:g.type)||""),[u,m]=i.useState(""),[d,h]=i.useState(""),[f,v]=i.useState(!1),[j,p]=i.useState(""),[y,x]=i.useState(!1),b=I=>{const C=I.toLowerCase().replace(/[^a-z0-9-]/g,"");m(C),(!d||d===w(u))&&h(w(C))},w=I=>I.split("-").map(C=>C.charAt(0).toUpperCase()+C.slice(1)).join(" "),R=async()=>{if(!(!u||!d||!c)){v(!0),p("");try{const I=await r(e,"provider_clone",{type:u,name:d,category:"ide",location:"user",cloneFrom:c});I!=null&&I.success||I!=null&&I.created?(x(!0),a==null||a(u)):p((I==null?void 0:I.error)||"Failed to create provider")}catch(I){p((I==null?void 0:I.message)||"Connection failed")}v(!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:I=>I.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:y?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:u})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",u,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",u]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:o.map(I=>s.jsxs("button",{onClick:()=>l(I.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===I.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===I.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:I.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===I.type?"#a78bfa":"var(--text-secondary)"},children:I.displayName})]},I.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:u,onChange:I=>b(I.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",u||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:d,onChange:I=>h(I.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"})]}),j&&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:j})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:y?s.jsx("button",{onClick: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:R,disabled:!u||!d||f,className:"machine-btn",style:{background:u&&d?"rgba(34,197,94,0.12)":void 0,borderColor:u&&d?"rgba(34,197,94,0.3)":void 0,color:u&&d?"#86efac":void 0,opacity:!u||!d||f?.4:1},children:f?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function gi(e){return e==="cli"||e==="acp"}function Fb(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 Ub(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 yi(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 zb({machineId:e,providers:t,sendDaemonCommand:r}){var U;const[n,a]=i.useState([]),[o,c]=i.useState(!1),[l,u]=i.useState(null),[m,d]=i.useState("all"),[h,f]=i.useState(null),[v,j]=i.useState(!1),[p,y]=i.useState(null),[x,b]=i.useState("normal"),[w,R]=i.useState(""),[g,I]=i.useState(!1),C=i.useCallback(async()=>{if(e)try{const K=await r(e,"get_provider_source_config",{}),N=xi(K);N&&(y(N),b(N.sourceMode),R(N.explicitProviderDir||""))}catch{}},[e,r]),S=i.useCallback(async()=>{if(e){c(!0);try{const K=await r(e,"get_provider_settings",{}),N=$b(K);if(N){const A=Bb(N,t,{filterSchema:z=>z.filter($=>$.key!=="enabled")});A.sort((z,$)=>z.category.localeCompare($.category)||z.displayName.localeCompare($.displayName)),a(A)}}catch{}c(!1)}},[e,t,r]);i.useEffect(()=>{n.length===0&&S(),p||C()},[]);const k=async(K,N,A)=>{u(`${K}.${N}`),a(z=>z.map($=>$.type===K?{...$,values:{...$.values,[N]:A}}:$));try{const z=await r(e,"set_provider_setting",{providerType:K,key:N,value:A});z!=null&&z.success||S()}catch{S()}u(null)},W=async(K,N)=>{await k(K,"enabled",N),await S()},L=async K=>{u(`${K}.detect`);try{await r(e,"detect_provider",{providerType:K})}finally{await S(),u(null)}},M=async K=>{await k(K,"executablePath",""),await k(K,"executableArgs",""),await S()},E=async()=>{I(!0);try{const K=await r(e,"set_provider_source_config",{providerSourceMode:x,providerDir:Kb(w)}),N=xi(K);N?(y(N),b(N.sourceMode),R(N.explicitProviderDir||"")):await C(),await S()}catch{await C()}I(!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(K=>s.jsx("button",{onClick:()=>d(K),className:`machine-btn text-[10px] px-2 py-0.5 ${m===K?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:K.toUpperCase()},K))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>j(!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:S,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:C,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:K=>b(K.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),s.jsx("input",{type:"text",value:w,onChange:K=>R(K.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void E(),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:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((U=p==null?void 0:p.providerRoots)==null?void 0:U.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(K=>K.category===m).length>1&&(()=>{const K=n.filter($=>$.category===m),N=new Map;for(const $ of K)for(const B of $.schema){if(B.type!=="boolean")continue;const G=N.get(B.key),V=!!($.values[B.key]??B.default);G?(G.onCount+=V?1:0,G.total+=1):N.set(B.key,{label:B.label||B.key,onCount:V?1:0,total:1})}const A=[...N.entries()].filter(([,$])=>$.total===K.length);if(A.length===0)return null;const z=async($,B)=>{for(const G of K)await k(G.type,$,B)};return s.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[s.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",K.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:A.map(([$,B])=>{const G=B.onCount===B.total,V=B.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:B.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",B.onCount,"/",B.total,")"]}),s.jsx("button",{onClick:()=>void z($,!0),disabled:G,className:`machine-btn text-[9px] px-1.5 py-px ${G?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void z($,!1),disabled:V,className:`machine-btn text-[9px] px-1.5 py-px ${V?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},$)})})]})})(),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(K=>m==="all"||K.category===m).map(K=>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:K.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:K.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:K.category==="acp"?"rgba(139,92,246,0.08)":K.category==="cli"?"rgba(59,130,246,0.08)":K.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:K.category==="acp"?"#a78bfa":K.category==="cli"?"#60a5fa":K.category==="ide"?"#86efac":"var(--status-warning)"},children:K.category}),gi(K.category)&&(()=>{const N=t.find($=>$.type===K.type),A=(N==null?void 0:N.enabled)===!0||K.values.enabled===!0,z=(N==null?void 0:N.machineStatus)||(A?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${Ub(z)}`,children:Fb(z)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void W(K.type,!A),disabled:l===`${K.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${A?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:A?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void L(K.type),disabled:!A||l===`${K.type}.detect`,title:A?"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 ${A?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void M(K.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),K.category==="ide"&&s.jsx("button",{onClick:()=>f(t.find(N=>N.type===K.type)||{type:K.type,name:K.displayName,displayName:K.displayName,icon:K.icon,category:K.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"})]}),gi(K.category)&&(()=>{const N=t.find(A=>A.type===K.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:"})," ",yi(N==null?void 0:N.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",yi(N==null?void 0:N.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:K.schema.map(N=>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:[N.label||N.key,l===`${K.type}.${N.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),N.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:N.description})]}),s.jsx("div",{className:"shrink-0",children:N.type==="boolean"?s.jsx("button",{onClick:()=>k(K.type,N.key,!(K.values[N.key]??N.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:K.values[N.key]??N.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:K.values[N.key]??N.default?21:3}})}):N.type==="number"?s.jsx("input",{type:"number",value:Number(K.values[N.key]??N.default??0)||0,min:N.min,max:N.max,onChange:A=>{const z=parseInt(A.target.value)||0;N.min!==void 0&&z<N.min||N.max!==void 0&&z>N.max||k(K.type,N.key,z)},className:"machine-input w-20 text-center text-[11px]"}):N.type==="select"&&N.options?s.jsx("select",{value:String(K.values[N.key]??N.default??""),onChange:A=>k(K.type,N.key,A.target.value),className:"machine-input text-[11px]",children:N.options.map(A=>s.jsx("option",{value:A,children:A},A))}):s.jsx("input",{type:"text",value:String(K.values[N.key]??N.default??""),onBlur:A=>k(K.type,N.key,A.target.value),className:"machine-input w-[120px] text-[11px]"})})]},N.key))})]},K.type))}),h&&s.jsx(Wb,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>f(null)}),v&&s.jsx(Hb,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>j(!1),onCreated:()=>{j(!1),S()}})]})}const Vb=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Gb({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function qb(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function Yb(e){return e.trim().toLowerCase()}function hn(e,t){const r=Yb(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function io(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function As(e,t=220){const r=io(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function Xb(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 Jb(e,t){return e.filter(r=>hn([r.level,r.message],t))}function vi(e){return`${e.timestamp}:${e.level}:${e.message}`}function Qb(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const c of e.entries)n.set(vi(c),c);for(const c of t.entries)n.set(vi(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 Zb(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 eg(e,t){return e.split(`
72
+ `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>hn([r],t))}function tg(e,t){return e.filter(r=>hn([r.level,r.category,r.stage,r.interactionId,io(r.payload)],t))}function sg(e,t){return e.filter(r=>hn([r.kind,r.topic,r.interactionId,io(r.payload)],t))}function wi(e){return e==="warn"||e==="error"}function rg({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=>wi(a.level)).length+r.filter(a=>wi(a.level)).length}}function ng({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
73
  `)):t.length>0&&a.push(["[daemon logs]",...t].join(`
74
74
  `)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${As(o.payload,500)}`.trim())].join(`
75
75
  `)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${As(o.payload,500)}`.trim())].join(`
76
76
  `)),a.join(`
77
77
 
78
- `)}function qb({machineId:e,sendDaemonCommand:t}){const[r,n]=i.useState([]),[a,o]=i.useState("empty"),[c,l]=i.useState(""),[u,m]=i.useState([]),[d,h]=i.useState([]),[f,w]=i.useState(null),[k,p]=i.useState(!0),[y,x]=i.useState("info"),[b,v]=i.useState("all"),[R,g]=i.useState(!0),[M,C]=i.useState(!0),[S,j]=i.useState(""),[W,L]=i.useState(""),[I,D]=i.useState(0),U=i.useRef(0),K=i.useRef(0),N=i.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),A=i.useRef([]),z=i.useCallback(()=>{const xe={entries:[],kind:"empty",rawText:"",lastTs:0};N.current=xe,U.current=0,n([]),l(""),o("empty"),g(!0)},[]),$=i.useCallback(()=>{A.current=[],K.current=0,m([]),C(!0)},[]),B=i.useCallback(xe=>{xe!==y&&(z(),x(xe))},[y,z]),V=i.useCallback(xe=>{v(de=>de===xe?de:xe)},[]),G=i.useCallback(()=>{z(),$(),h([]),w(null),j(""),L(""),Ss.clear()},[z,$]),me=i.useCallback(()=>{D(xe=>xe+1)},[]),ne=i.useCallback(async()=>{if(!e)return;const xe=U.current,de=K.current,[be,he]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:y,since:xe}),t(e,"get_debug_trace",Eb({count:120,since:de,category:b}))]);if(be.status==="fulfilled"){const Y=be.value,oe=(Y==null?void 0:Y.result)||Y,J=Kb(oe),ue=Wb(N.current,J,300);N.current=ue,U.current=ue.lastTs,g(!1),j((Y==null?void 0:Y.success)===!1?String((Y==null?void 0:Y.error)||"Could not load daemon logs"):""),o(ue.kind),l(ue.rawText),n(ue.entries)}else g(!1),j(be.reason instanceof Error?be.reason.message:"Could not load daemon logs");if(he.status==="fulfilled"){const Y=he.value,oe=(Y==null?void 0:Y.result)||Y;if((Y==null?void 0:Y.success)===!1)L(String((Y==null?void 0:Y.error)||"Could not load daemon trace"));else if(Array.isArray(oe==null?void 0:oe.trace)){const J=oe.trace,ue=Hb(A.current,J,120),le=J.reduce((Se,ie)=>Math.max(Se,Number(ie.ts||0)),de);A.current=ue,le>de&&(K.current=le),L(""),m(ue)}else L("");C(!1)}else C(!1),L(he.reason instanceof Error?he.reason.message:"Could not load daemon trace");h(Ss.list({limit:120})),w(Date.now())},[y,e,t,b]);return i.useEffect(()=>{$()},[$,b]),i.useEffect(()=>{if(!e||(ne(),!k))return;const xe=setInterval(()=>{ne()},3e3);return()=>clearInterval(xe)},[k,ne,e,I]),{daemonLogs:r,daemonLogKind:a,daemonRawText:c,debugTrace:u,webEvents:d,lastUpdatedAt:f,autoRefresh:k,logLevel:y,traceCategory:b,daemonLoading:R,traceLoading:M,daemonFetchError:S,traceFetchError:W,setAutoRefresh:p,setLogLevel:B,setTraceCategory:V,refresh:me,clear:G}}function Yb({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:c,traceCount:l,webEventCount:u}){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:u>0?"ok":"empty",detail:u>0?`${u} local browser event(s)`:"No browser events captured"}]}function wi(e){return e==="warn"||e==="error"}function Xb(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 Jb(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 ji(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function Qb(e){const t=As(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function Zb(e){const t=As(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function eg({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:Zb(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:Qb(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:Jb(o,c),severity:Xb(o),message:o,raw:o})}),a.sort((o,c)=>o.ts!==c.ts?o.ts-c.ts:ji(o.source)-ji(c.source))}function tg(e){return`${e.source}:${e.severity}:${e.message}`}function sg(e){const t=e.filter(n=>wi(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!wi(n.severity))continue;const a=tg(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 rg(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function ki(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${rg(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function ng({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
78
+ `)}function ag({machineId:e,sendDaemonCommand:t}){const[r,n]=i.useState([]),[a,o]=i.useState("empty"),[c,l]=i.useState(""),[u,m]=i.useState([]),[d,h]=i.useState([]),[f,v]=i.useState(null),[j,p]=i.useState(!0),[y,x]=i.useState("info"),[b,w]=i.useState("all"),[R,g]=i.useState(!0),[I,C]=i.useState(!0),[S,k]=i.useState(""),[W,L]=i.useState(""),[M,E]=i.useState(0),U=i.useRef(0),K=i.useRef(0),N=i.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),A=i.useRef([]),z=i.useCallback(()=>{const xe={entries:[],kind:"empty",rawText:"",lastTs:0};N.current=xe,U.current=0,n([]),l(""),o("empty"),g(!0)},[]),$=i.useCallback(()=>{A.current=[],K.current=0,m([]),C(!0)},[]),B=i.useCallback(xe=>{xe!==y&&(z(),x(xe))},[y,z]),G=i.useCallback(xe=>{w(de=>de===xe?de:xe)},[]),V=i.useCallback(()=>{z(),$(),h([]),v(null),k(""),L(""),Ss.clear()},[z,$]),me=i.useCallback(()=>{E(xe=>xe+1)},[]),ae=i.useCallback(async()=>{if(!e)return;const xe=U.current,de=K.current,[be,he]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:y,since:xe}),t(e,"get_debug_trace",Gb({count:120,since:de,category:b}))]);if(be.status==="fulfilled"){const Y=be.value,oe=(Y==null?void 0:Y.result)||Y,J=Xb(oe),ue=Qb(N.current,J,300);N.current=ue,U.current=ue.lastTs,g(!1),k((Y==null?void 0:Y.success)===!1?String((Y==null?void 0:Y.error)||"Could not load daemon logs"):""),o(ue.kind),l(ue.rawText),n(ue.entries)}else g(!1),k(be.reason instanceof Error?be.reason.message:"Could not load daemon logs");if(he.status==="fulfilled"){const Y=he.value,oe=(Y==null?void 0:Y.result)||Y;if((Y==null?void 0:Y.success)===!1)L(String((Y==null?void 0:Y.error)||"Could not load daemon trace"));else if(Array.isArray(oe==null?void 0:oe.trace)){const J=oe.trace,ue=Zb(A.current,J,120),le=J.reduce((Se,ie)=>Math.max(Se,Number(ie.ts||0)),de);A.current=ue,le>de&&(K.current=le),L(""),m(ue)}else L("");C(!1)}else C(!1),L(he.reason instanceof Error?he.reason.message:"Could not load daemon trace");h(Ss.list({limit:120})),v(Date.now())},[y,e,t,b]);return i.useEffect(()=>{$()},[$,b]),i.useEffect(()=>{if(!e||(ae(),!j))return;const xe=setInterval(()=>{ae()},3e3);return()=>clearInterval(xe)},[j,ae,e,M]),{daemonLogs:r,daemonLogKind:a,daemonRawText:c,debugTrace:u,webEvents:d,lastUpdatedAt:f,autoRefresh:j,logLevel:y,traceCategory:b,daemonLoading:R,traceLoading:I,daemonFetchError:S,traceFetchError:W,setAutoRefresh:p,setLogLevel:B,setTraceCategory:G,refresh:me,clear:V}}function og({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:c,traceCount:l,webEventCount:u}){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:u>0?"ok":"empty",detail:u>0?`${u} local browser event(s)`:"No browser events captured"}]}function ki(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 cg(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 ji(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function lg(e){const t=As(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function dg(e){const t=As(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function ug({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:dg(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:lg(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:cg(o,c),severity:ig(o),message:o,raw:o})}),a.sort((o,c)=>o.ts!==c.ts?o.ts-c.ts:ji(o.source)-ji(c.source))}function mg(e){return`${e.source}:${e.severity}:${e.message}`}function fg(e){const t=e.filter(n=>ki(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!ki(n.severity))continue;const a=mg(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 pg(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Si(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${pg(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function hg({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
79
79
  `)),a.push(["[source status]",...r.map(c=>`${c.label}: ${c.status} - ${c.detail}`)].join(`
80
- `)),t.latestIssue&&a.push(["[latest issue]",ki(t.latestIssue)].join(`
80
+ `)),t.latestIssue&&a.push(["[latest issue]",Si(t.latestIssue)].join(`
81
81
  `)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(c=>`${c.count}x ${c.severity.toUpperCase()} ${c.source} ${c.message}`)].join(`
82
- `));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(ki):["No diagnostic events captured."]].join(`
82
+ `));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(Si):["No diagnostic events captured."]].join(`
83
83
  `)),a.join(`
84
84
 
85
- `)}function ag(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 ig({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:c,searchQuery:l,daemonLoading:u,traceLoading:m,daemonFetchError:d,traceFetchError:h}){const f=$b(n,o),w=Ob(e,l),k=Fb(t,l),p=Ub(f,l),y=zb(a,l),x=ag(w,c),b=c==="all"?k:[],v=og(p,c),R=c==="issues"?[]:y,g=Vb({daemonLogs:w,daemonRawLines:k,trace:p,webEvents:y}),M=eg({daemonLogs:x,daemonRawLines:b,trace:v,webEvents:R}),C=sg(M),S=Yb({daemonLoading:u,traceLoading:m,daemonFetchError:d,traceFetchError:h,daemonLogKind:r,daemonLogsCount:w.length,daemonRawLineCount:k.length,traceCount:p.length,webEventCount:y.length});return{filteredDaemonLogs:w,filteredDaemonRawLines:k,filteredTraceEntries:p,filteredWebEvents:y,visibleDaemonLogs:x,visibleDaemonRawLines:b,visibleTraceEntries:v,visibleWebEvents:R,quickFilterCounts:g,diagnosticEvents:M,diagnosticsSummary:C,sourceStates:S}}function cg(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Rl(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function wa(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 Fn(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 co(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function lg({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${wa(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Rl(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:co(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 dg({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:c,onCopyVisible:l,onToggleAutoRefresh:u,onRefresh:m,onClear:d}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(h=>s.jsx("button",{type:"button",onClick:()=>a(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),s.jsx("input",{value:r,onChange:h=>o(h.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:l,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:u,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:d,className:"machine-btn",children:"Clear"})]})]})}function ug({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:Db.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 mg({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:c,traceFetchError:l}){var d,h;const u=((d=e.latestIssue)==null?void 0:d.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",m=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 ${Fn(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 ${Fn(u)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[co(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:Rl(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 ${Fn(m)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:c||l?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",cg(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(f=>s.jsxs("div",{children:[f.label,": ",f.status]},f.id))})]})]})}function fg({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()," · ",co(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function pg({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:c,visibleWebEvents:l,quickFilter:u,searchQuery:m}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,timeline:!d.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(d=>s.jsx(lg,{event:d},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,daemon:!d.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:u==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((d,h)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:d},`raw-${h}`)),e.daemonLogKind!=="text"&&a.map((d,h)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${wa(d.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(d.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:d.level==="error"?"ERR":d.level==="warn"?"WRN":d.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:d.message})]},`log-${h}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,trace:!d.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[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:m.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),c.map(d=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${wa(d.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.level.toUpperCase()}),s.jsxs("span",{children:[d.category,".",d.stage]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:As(d.payload,360)||"No payload"})]},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,web:!d.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[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:m.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),l.map(d=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.kind}),d.topic&&s.jsxs("span",{children:["topic=",d.topic]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:As(d.payload,360)||"No payload"})]},d.id))]})]})]})}function hg({machineId:e,sendDaemonCommand:t}){const r=qb({machineId:e,sendDaemonCommand:t}),[n,a]=i.useState("info"),[o,c]=i.useState(""),[l,u]=i.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=i.useRef(null),d=i.useRef(!1),h=i.useMemo(()=>ig({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:o,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,o,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);i.useEffect(()=>{if(r.autoRefresh&&h.diagnosticEvents.length>0){const k=d.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:k}),d.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const f=i.useCallback(async()=>{var p;const k=Gb({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!k.trim()){et.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(k)),et.showToast("Copied visible logs to clipboard.","success")}catch(y){et.showToast(y instanceof Error?y.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),w=i.useCallback(async()=>{var p;const k=ng({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(k)),et.showToast("Copied diagnostic bundle to clipboard.","success")}catch(y){et.showToast(y instanceof Error?y.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(dg,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{w()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>r.setAutoRefresh(k=>!k),onRefresh:r.refresh,onClear:r.clear}),s.jsx(ug,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(mg,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(fg,{patterns:h.diagnosticsSummary.repeatedPatterns}),s.jsx(pg,{streams:r,sectionsOpen:l,setSectionsOpen:u,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function 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 _l(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 bg(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const c=String((o==null?void 0:o.lifecycle)||"").trim(),l=_l((o==null?void 0:o.meta)||void 0),u=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?t.push(o):(c==="stopped"||c==="failed")&&(u||l)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function gg(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Un(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 zn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Vn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Si(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 yg(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function vg(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 wg(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 jg({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,c]=i.useState(null),[l,u]=i.useState(!1),m=sh(e,{enabled:!!e,includeSessions:!0,limit:Eo,intervalMs:af}),d=m.diagnostics,h=m.loading,f=m.applyDiagnostics,w=i.useMemo(()=>xg({diagnostics:d,loading:h,refreshing:l,error:n}),[d,h,l,n]),k=i.useMemo(()=>new Map(t.map(L=>[L.sessionId||L.id,L])),[t]),p=i.useCallback(async()=>{if(e){u(!0);try{const L=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Eo}),I=zn(L);if(!(I!=null&&I.success))throw new Error((I==null?void 0:I.error)||"Could not load hosted runtime diagnostics");f(I.diagnostics||I.result||null),a("")}catch(L){const I=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";a(I)}finally{u(!1)}}},[f,e,r]);i.useEffect(()=>{!e||d||h||l||p()},[d,h,e,p,l]);const y=i.useCallback(async(L,I)=>{const D=`${L}:${I.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${I.displayName}?
86
- This will terminate the hosted runtime.`))){c(D);try{const U=await r(e,L,{sessionId:I.sessionId}),K=zn(U);if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Session host action failed");const N=L==="session_host_resume_session"?"resumed":L==="session_host_restart_session"?"restarted":"stopped";et.showToast(`Session host ${N}: ${I.displayName}`,"success"),await p()}catch(U){const K=U instanceof Error?U.message:"Session host action failed";et.showToast(K,"warning"),a(K)}finally{c(U=>U===D?null:U)}}},[e,p,r]),x=i.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
87
- 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 I=await r(e,"session_host_prune_duplicate_sessions",{}),D=zn(I);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Duplicate prune failed");const U=D.result||{},K=Array.isArray(U.prunedSessionIds)?U.prunedSessionIds.length:0,N=typeof U.duplicateGroupCount=="number"?U.duplicateGroupCount:0;et.showToast(`Pruned ${K} duplicate runtime(s) across ${N} group(s)`,"success"),await p()}catch(I){const D=I instanceof Error?I.message:"Duplicate prune failed";et.showToast(D,"warning"),a(D)}finally{c(I=>I==="session_host_prune_duplicate_sessions"?null:I)}}},[e,p,r]),b=i.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((L,I)=>(I.lastActivityAt||0)-(L.lastActivityAt||0)),[d==null?void 0:d.sessions]),v=i.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:bg(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),R=v.liveRuntimes,g=v.recoverySnapshots,M=v.inactiveRecords,C=i.useMemo(()=>wg(R),[R]),S=i.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),j=i.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[d==null?void 0:d.recentLogs]),W=(L,I)=>{var V;const D=o===`session_host_resume_session:${L.sessionId}`,U=o===`session_host_restart_session:${L.sessionId}`,K=o===`session_host_stop_session:${L.sessionId}`,N=_l(L.meta),A=k.get(L.sessionId),z=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,$=I==="recovery"?"Recover":"Resume",B=gg(I);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:L.displayName||(A==null?void 0:A.cliName)||L.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${vg(L.lifecycle)}`,children:L.lifecycle}),N&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:N})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:L.workspaceLabel||(A==null?void 0:A.runtimeWorkspaceLabel)||L.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:L.runtimeKey}),L.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",L.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((V=L.writeOwner)==null?void 0:V.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:yg(L.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(Ki,{size:11})," ",z]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Si(L.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",B]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[I==="recovery"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{y("session_host_resume_session",L)},children:D?`${$}ing…`:$}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{y("session_host_restart_session",L)},children:U?"Restarting…":"Restart"}),I==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{y("session_host_stop_session",L)},children:K?"Stopping…":"Stop"})]})]})},L.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(ds,{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:[C>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 (${C})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${w.toneClass}`,children:w.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||l,children:[s.jsx(or,{size:13}),h||l?"Refreshing…":"Refresh"]})]})]}),n&&!d&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(tr,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children: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:d.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Si(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Vn(d.hostStartedAt)})]})]}),j&&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(tr,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:j.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Vn(j.timestamp),j.sessionId?` · ${j.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(Ma,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Un("live")}),R.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:R.map(L=>W(L,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(ds,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Un("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(L=>W(L,"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:Un("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:M.map(L=>W(L,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),S.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:S.map(L=>{var D;const I=b.find(U=>U.sessionId===L.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(I==null?void 0:I.displayName)||((D=k.get(L.sessionId))==null?void 0:D.cliName)||L.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[L.action,L.lifecycle?` · ${L.lifecycle}`:"",L.detail?` · ${L.detail}`:"",L.error?` · ${L.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${L.success===!1?"text-red-300":"text-text-secondary"}`,children:Vn(L.timestamp)})]},`${L.sessionId}:${L.timestamp}:${L.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function kg({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 Gn({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 qn({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 Sg({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),d=Xs(e,"0.9.54");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(Gn,{icon:s.jsx(Ht,{size:13}),children:"Current Chats"}),s.jsx(qn,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const f=la(h);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(h),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(h)}),f>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:sn(f)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ms(h)})]},h.tabKey)})})})]}),u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Gn,{icon:s.jsx(Ui,{size:13}),children:"Recent Launches"}),s.jsx(qn,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:f,updatedLabel:w}=pl(h);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(h),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:h.label}),w&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:w})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:f})]},h.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Gn,{icon:s.jsx(tr,{size:13}),children:"Daemon Update"}),s.jsx(qn,{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:d?"Daemon update required":"Version mismatch detected"}),s.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:d?"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(or,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Ng(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function Cg({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:u=>{const m=u.target.value;if(o(m),m==="__custom__"&&a){l();return}m!=="__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(u=>s.jsxs("option",{value:u.id,children:[u.id===e.defaultWorkspaceId?"⭐ ":"",nn(u.path,u.label)]},u.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:u=>c(u.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 Tg={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 Ir(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Yn({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:m}){const d=Ls(),{handleLaunchIde:h,handleStopCli:f,handleRestartIde:w,handleStopIde:k,handleDetectIdes:p,launchingIde:y,launchingAgentType:x,addLog:b}=c,[v,R]=i.useState(null),g=i.useCallback(O=>{O&&d(Gt(O))},[d]),M=Tg[e],C=e==="ide",S=e==="acp",j=i.useMemo(()=>n.filter(O=>ps(O,e)),[e,n]),W=i.useMemo(()=>new Map(j.map(O=>[O.type,O.displayName||O.type])),[j]),[L,I]=i.useState(""),[D,U]=i.useState(""),[K,N]=i.useState([]),[A,z]=i.useState(""),[$,B]=i.useState(""),[V,G]=i.useState([]),[me,ne]=i.useState(!1),[xe,de]=i.useState(!1),[be,he]=i.useState(""),[Y,oe]=i.useState(!1),[J,ue]=i.useState(()=>ht()),[le,Se]=i.useState(null),[ie,pe]=i.useState(m?"__custom__":u||t.defaultWorkspaceId||""),[re,Z]=i.useState(m||""),[ee,q]=i.useState([]),[X,ae]=i.useState(!1),[je,ke]=i.useState(""),[te,E]=i.useState([]),[ve,Ce]=i.useState(!1),[we,Pe]=i.useState(""),Le=i.useRef(null),[Oe,ze]=i.useState(null),tt=i.useRef("__home__"),[Xe,Ye]=i.useState("__home__"),[mt,pt]=i.useState(!1),dt=i.useRef(0),Te=ee.filter(O=>!a.some(se=>se.type===O&&bt(se.status)!=="stopped")),Fe=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!ie&&pe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(m){pe("__custom__"),Z(m);return}u&&(pe(u),Z(""))},[u,m]),i.useEffect(()=>{C||L&&(j.some(O=>O.type===L)||(I(""),B("")))},[j,C,L]);const Ge=(()=>{if(ie==="__custom__")return re.trim();if(!ie)return"";const O=(t.workspaces||[]).find(se=>se.id===ie);return(O==null?void 0:O.path)||""})(),ct=i.useCallback(O=>{const se=Fe.current[O];se&&(clearTimeout(se),delete Fe.current[O]),q(ge=>ge.includes(O)?ge.filter(Be=>Be!==O):ge)},[]),ft=i.useRef(new Set),H=i.useCallback(async O=>{if(l){Ce(!0),Pe("");try{const se=await un(l,r,O);ke(se.path),Z(se.path),E(se.directories)}catch(se){Pe(se instanceof Error?se.message:"Could not load folder")}finally{Ce(!1)}}},[r,l]),_=i.useCallback(()=>{if(!l)return;pe("__custom__"),ae(!0);const O=a.map(ge=>ge.workspace),se=dn(t.platform,ln(re.trim(),Ge,m,O,t.defaultWorkspacePath,(t.workspaces||[]).map(ge=>ge.path)));H(se)},[re,m,H,t.defaultWorkspacePath,t.platform,t.workspaces,a,Ge,l]),T=i.useCallback(O=>{const se=String(O.workspace||"").trim();if(!se)return;const ge=(t.workspaces||[]).find(Be=>Ir(Be.path)===Ir(se));if(ge){pe(ge.id),Z("");return}pe("__custom__"),Z(se)},[t.workspaces]),P=i.useCallback(O=>{const se=String(O.workspace||"").trim();if(!se)return{workspaceId:null,workspacePath:"",useHome:!0};const ge=(t.workspaces||[]).find(Be=>Ir(Be.path)===Ir(se));return ge?{workspaceId:ge.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:se,useHome:!1}},[t.workspaces]),F=i.useCallback(async O=>{if(!l||!O||e!=="cli"){G([]),ne(!1),de(!1),he("");return}const se=dt.current+1;dt.current=se,ne(!0),he("");try{const ge=await l(r,"list_saved_sessions",{providerType:O,kind:"cli",limit:30});if(dt.current!==se)return;const Be=(ge==null?void 0:ge.result)??ge;G(Array.isArray(Be==null?void 0:Be.sessions)?Be.sessions:[])}catch(ge){if(dt.current!==se)return;G([]),he(ge instanceof Error?ge.message:"Could not load saved sessions")}finally{dt.current===se&&(ne(!1),de(!0))}},[e,r,l]),Q=i.useMemo(()=>{if(e!=="cli"||!L)return null;const O=W.get(L)||L;return{routeId:r,daemonId:r,providerSessionId:$||void 0,transport:"pty",mode:"chat",agentName:O,agentType:L,status:"idle",title:O,messages:[],ideType:L,workspaceName:Ge,workspacePath:Ge,displayPrimary:O,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${L}`}},[e,r,W,Ge,$,L]),ye=i.useCallback(O=>{if(e==="ide"||!O){N([]);return}N(Il(r,O))},[e,r]);i.useEffect(()=>{dt.current+=1,B(""),ye(L),de(!1),G([]),he(""),ne(!1)},[e,ye,F,L]);const ce=i.useMemo(()=>V.find(O=>O.providerSessionId===$)||null,[V,$]);i.useEffect(()=>{if(!$)return;const O=V.find(se=>se.providerSessionId===$);O!=null&&O.canResume||B("")},[V,$]);const Ne=i.useCallback((O,se)=>{Le.current=se,tt.current=O.selectedWorkspaceKey||"__home__",Ye(O.selectedWorkspaceKey||"__home__"),ze(O)},[]),De=i.useCallback(()=>{Le.current&&(pt(!0),Le.current().finally(()=>{Le.current=null,pt(!1),ze(null)}))},[]),$e=i.useCallback(O=>{if(!O)return;q(ge=>ge.includes(O)?ge:[...ge,O]);const se=Fe.current[O];se&&clearTimeout(se),Fe.current[O]=setTimeout(()=>{q(ge=>ge.includes(O)?ge.filter(Be=>Be!==O):ge),delete Fe.current[O]},2e4)},[]);i.useEffect(()=>{for(const se of a)bt(se.status)!=="stopped"&&(ee.includes(se.type)&&!ft.current.has(se.type)&&(ft.current.add(se.type),b("info",`${W.get(se.type)||se.type} launched`,!0)),ct(se.type));const O=new Set(a.filter(se=>bt(se.status)!=="stopped").map(se=>se.type));ft.current.forEach(se=>{!ee.includes(se)&&!O.has(se)&&ft.current.delete(se)})},[b,ct,a,ee,W]),i.useEffect(()=>()=>{Object.values(Fe.current).forEach(clearTimeout),Fe.current={}},[]);const[Ie,Re]=i.useState({}),[We,Ae]=i.useState(null);i.useEffect(()=>{if(!C||!r||!l)return;(async()=>{try{const se=await l(r,"get_ide_extensions",{}),ge=(se==null?void 0:se.result)||se;ge!=null&&ge.success&&(ge!=null&&ge.ideExtensions)&&Re(ge.ideExtensions)}catch{}})()},[C,r,l]);const Je=O=>C?ot(O.type):e==="cli"?O.cliName:O.acpName,Qe=C?t.detectedIdes||[]:[],fe=i.useCallback(async O=>{const se=(O==null?void 0:O.type)||L,ge=(O==null?void 0:O.workspacePath)??Ge;if(C){await h(se,ge?{workspace:ge}:void 0)&&$e(se);return}const Be=await c.runLaunchCliCore({cliType:se,dir:O!=null&&O.workspaceId?void 0:ge||void 0,workspaceId:(O==null?void 0:O.workspaceId)||void 0,useHome:(O==null?void 0:O.useHome)||!(O!=null&&O.workspaceId)&&!ge,argsStr:(O==null?void 0:O.argsStr)??(D||void 0),model:(O==null?void 0:O.model)??(S&&A||void 0),resumeSessionId:(O==null?void 0:O.resumeSessionId)||!S&&e==="cli"&&se===L&&$||void 0});if(Be.success||Be.pending){const Me=(O==null?void 0:O.argsStr)??D;!C&&(Me!=null&&Me.trim())&&(Ml(r,se,Me),ye(se)),$e(se),Be.success&&Be.sessionId&&g(Be.sessionId)}},[c,h,S,C,D,A,ye,$e,r,g,Ge,$,L]),_e=Ec(C?"ide":S?"acp":"cli",!C&&!S&&!!$),rt=$c(C?"ide":S?"acp":"cli",!C&&!S&&!!$),nt=()=>{var Me;const O=C?ot(L):W.get(L)||L,se=!C&&!S&&!!$,{options:ge,selectedKey:Be}=is({machine:t,currentWorkspaceId:ie&&ie!=="__custom__"?ie:null,currentWorkspacePath:Ge});Ne({title:se?qa(O):rs("start-fresh",O),description:se?Ya():ns("start-fresh"),confirmLabel:_e,busyLabel:rt,workspaceOptions:ge,selectedWorkspaceKey:Be,details:[{label:"Mode",value:M.label},{label:"Provider",value:O},...!C&&e==="cli"&&$?[{label:"Resume",value:((Me=V.find(Ee=>Ee.providerSessionId===$))==null?void 0:Me.title)||$}]:[],...!C&&D.trim()?[{label:"Arguments",value:D.trim()}]:[],...S&&A.trim()?[{label:"Model",value:A.trim()}]:[]]},async()=>{const Ee=ge.find(at=>at.key===tt.current);Ee!=null&&Ee.workspaceId?(pe(Ee.workspaceId),Z("")):Ee!=null&&Ee.workspacePath?(pe("__custom__"),Z(Ee.workspacePath)):(pe(""),Z("")),await fe({workspaceId:(Ee==null?void 0:Ee.workspaceId)??null,workspacePath:(Ee==null?void 0:Ee.workspacePath)??"",useHome:!(Ee!=null&&Ee.workspaceId)&&!(Ee!=null&&Ee.workspacePath)})})},He=O=>{C?k(O):f(O.type,O.workspace,O.id)},It=i.useCallback(async(O,se,ge=!1)=>{if(O.mode===se){ge&&O.sessionId&&g(O.sessionId);return}if(!l||!O.sessionId){ge&&O.sessionId&&g(O.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:O.sessionId,cliType:O.type,mode:se}),ge&&g(O.sessionId)}catch(Be){const Me=rl(Be);sl(Be)?console.warn(Me?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Be instanceof Error?Be.message:String(Be)):console.error("Failed to switch CLI view mode:",Be)}},[r,g,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${M.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 ",M.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:C?Qe.length>0?Qe.map(O=>{const se=a.find(at=>(at.type||"").toLowerCase()===(O.type||"").toLowerCase()&&bt(at.status)!=="stopped"),ge=O.running||!!se,Be=!!se&&se.cdpConnected,Me=ee.includes(O.type||O.id||""),Ee=L===(O.type||"");return s.jsxs("button",{onClick:()=>{if(Be&&se){const at=se.sessionId;at?d(Gt(at),{state:{openRemoteForTabKey:at}}):d("/dashboard",{state:{openRemoteForTabKey:se.id}});return}Me||I(at=>at===(O.type||"")?"":O.type||"")},disabled:!!y||Me,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Be?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ee?"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:y&&y!==O.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(O.type)}),ge&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Be?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:O.name||ot(O.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Be?"text-green-400":Me?"text-orange-400":Ee?"text-accent-primary":"text-text-muted"}`,children:Be?"Open Session":Me?"Starting...":Ee?"Configure":"Select"})]})]},O.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:p,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(Gd,{size:14})," Scan System"]})]}):j.length>0?j.map(O=>{const se=L===O.type,ge=ee.includes(O.type),Me=!!a.find(Ee=>Ee.type===O.type&&bt(Ee.status)!=="stopped");return s.jsxs("button",{onClick:()=>I(Ee=>Ee===O.type?"":O.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${se?"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:O.icon}),Me&&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:O.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ge?"text-orange-400":se?"text-accent-primary":"text-text-muted"}`,children:ge?"Starting...":se?"Configure":"Select"})]})]},O.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."})]})}),L&&(C?Qe.find(O=>O.type===L):j.find(O=>O.type===L))&&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:C?ot(L):W.get(L)||L})]}),s.jsx(Cg,{machine:t,selectedWorkspace:ie,resolvedWorkspacePath:Ge,customPath:re,canBrowse:!!l,onWorkspaceChange:pe,onCustomPathChange:Z,onOpenBrowseDialog:_}),!C&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!S&&e==="cli"&&s.jsx(Ll,{busy:!!x||!!y||ee.includes(L),savedSessionsLoading:me,savedSessionsError:be,savedSessionsLoaded:xe,savedSessionsCount:V.length,selectedSession:ce,onRefresh:()=>void F(L),onOpenHistory:()=>{L&&(oe(!0),Al({hasLoadedInitialResults:xe,isLoading:me})&&F(L))},onClearSelection:()=>B("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[S&&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:A,onChange:O=>z(O.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:D,onChange:O=>U(O.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"}),K.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:K.map(O=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>U(O),title:O,children:O},O))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:nt,disabled:!!x||!!y||ee.includes(L),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:x===L||y===L?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ee.filter(O=>!a.some(se=>se.type===O&&bt(se.status)!=="stopped")).length,")"]}),a.length===0&&Te.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 ",M.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Te.map(O=>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(O)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:C?ot(O):W.get(O)||O}),s.jsx("div",{className:"text-[11px] text-text-muted",children:x===O?"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:${O}`)),a.map(O=>{const se=C?O:null,ge=!C&&!S?O:null,Be=bt(O.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(O.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Je(O),(se==null?void 0:se.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",se.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:O.workspace||"—"}),s.jsx(cn,{git:O.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(ge==null?void 0:ge.mode)&&s.jsx("span",{className:ge.mode==="chat"?"text-violet-400":"text-text-secondary",children:ge.mode==="chat"?"Chat view":"Terminal view"})]}),ge&&(ge.runtimeKey||ge.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ge.runtimeKey&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),s.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ge.runtimeKey]}),s.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Me;(Me=navigator.clipboard)==null||Me.writeText(`adhdev attach ${ge.runtimeKey}`),R(ge.runtimeKey||null),window.setTimeout(()=>{R(Ee=>Ee===ge.runtimeKey?null:Ee)},1200)},children:v===ge.runtimeKey?"Copied":"Copy"})]}),ge.runtimeWriteOwner&&s.jsx("span",{style:{color:ge.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ge.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Ng(ge.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Be==="stopped"?"bg-red-500/[0.08] text-red-500":Be==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Be}),C&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Me=O.sessionId;if(Me){d(Gt(Me),{state:{openRemoteForTabKey:Me}});return}d("/dashboard",{state:{openRemoteForTabKey:O.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(Nt,{size:13})}),s.jsx("button",{onClick:()=>{const Me=O.workspace||"",{options:Ee,selectedKey:at}=is({machine:t,currentWorkspacePath:Me});Ne({title:rs("restart-ide",ot(O.type)),description:ns("restart-ide"),confirmLabel:Is("restart-ide"),busyLabel:Ms("restart-ide"),workspaceOptions:Ee,selectedWorkspaceKey:at,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ot(O.type)}]},async()=>{const yt=Ee.find(Ut=>Ut.key===tt.current),ut=(yt==null?void 0:yt.workspacePath)??"";if(ut&&ut!==Me){await fe({type:O.type,workspacePath:ut});return}await w(O)})},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(or,{size:14})})]}),S&&s.jsx("button",{onClick:()=>{const Me=O.sessionId;Me&&g(Me)},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:!O.sessionId,children:s.jsx(Ht,{size:14})}),ge&&Be!=="stopped"&&s.jsxs(s.Fragment,{children:[ge.mode&&s.jsx(za,{mode:ge.mode,onChange:Me=>void It(ge,Me,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Me=O.sessionId;Me&&g(Me)},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:!O.sessionId,children:ge.mode==="chat"?s.jsx(Ht,{size:14}):s.jsx(Nt,{size:13})})]}),Be==="stopped"?s.jsx("button",{onClick:()=>{const Me=O.workspace||"",Ee=C?ot(O.type):Je(O),{options:at,selectedKey:yt}=is({machine:t,currentWorkspacePath:Me});Ne({title:rs("restart-stopped",Ee),description:ns("restart-stopped"),confirmLabel:Is("restart-stopped"),busyLabel:Ms("restart-stopped"),workspaceOptions:at,selectedWorkspaceKey:yt,details:[{label:"Mode",value:M.label},{label:"Provider",value:Ee}]},async()=>{const ut=at.find(Ut=>Ut.key===tt.current);await fe({type:O.type,workspaceId:(ut==null?void 0:ut.workspaceId)??null,workspacePath:(ut==null?void 0:ut.workspacePath)??"",useHome:!(ut!=null&&ut.workspaceId)&&!(ut!=null&&ut.workspacePath)})})},disabled:ee.includes(O.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:ee.includes(O.type)?"⏳":s.jsx(Aa,{size:14})}):s.jsx("button",{onClick:()=>He(O),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:s.jsx(wt,{size:14})})]})]}),se&&se.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:se.aiAgents.map(Me=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${ec(Me.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Me.name," · ",bt(Me.status)]},Me.id))}),se&&(Ie[se.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:(Ie[se.type]||[]).map(Me=>s.jsxs("button",{disabled:We===`${se.type}.${Me.type}`,onClick:async()=>{const Ee=`${se.type}.${Me.type}`;Ae(Ee);try{await l(r,"set_ide_extension",{ideType:se.type,extensionType:Me.type,enabled:!Me.enabled}),Re(at=>({...at,[se.type]:(at[se.type]||[]).map(yt=>yt.type===Me.type?{...yt,enabled:!yt.enabled}:yt)}))}catch(at){console.error("Extension toggle failed:",at)}finally{Ae(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 ${Me.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 ${Me.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Me.name,s.jsx("span",{className:"text-[9px] font-normal",children:Me.enabled?"ON":"OFF"})]},Me.type))})]})]},O.id)})]}),X&&l&&s.jsx(mn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:je,directories:te,busy:ve,error:we,confirmLabel:"Use this folder",onClose:()=>ae(!1),onNavigate:O=>{H(O)},onConfirm:O=>{Z(O),pe("__custom__"),ae(!1)}}),Oe&&s.jsx(ao,{title:Oe.title,description:Oe.description,details:Oe.details,workspaceOptions:Oe.workspaceOptions,selectedWorkspaceKey:Xe,onWorkspaceChange:O=>{tt.current=O,Ye(O)},confirmLabel:Oe.confirmLabel,busyLabel:Oe.busyLabel,busy:mt,onConfirm:De,onCancel:()=>{Le.current=null,ze(null)}}),Y&&Q&&s.jsx(Xa,{activeConv:Q,ides:[],isCreatingChat:!1,isRefreshingHistory:me,savedSessions:V,isSavedSessionsLoading:me,isResumingSavedSessionId:le,savedHistoryFilters:J,missingWorkspaceResumePath:Ge||null,onSavedHistoryFiltersChange:ue,onClose:()=>oe(!1),onNewChat:()=>{B(""),oe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{F(L)},onResumeSavedSession:O=>{if(!O.canResume||le)return;const se=P(O);B(O.providerSessionId),T(O),Se(O.providerSessionId),oe(!1),fe({type:O.providerType,workspaceId:se.workspaceId,workspacePath:se.workspacePath,useHome:se.useHome,resumeSessionId:O.providerSessionId}).finally(()=>{Se(ge=>ge===O.providerSessionId?null:ge)})}})]})}const Ni=[{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 Ig({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:m,initialWorkspacePath:d,sendDaemonCommand:h}){var p;const[f,w]=i.useState(u);i.useEffect(()=>{w(u)},[u]);const k=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:Ni.map(y=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${f===y.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>w(y.id),children:[s.jsx("span",{children:y.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${f===y.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:k[y.id]})]},y.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(p=Ni.find(y=>y.id===f))==null?void 0:p.helper})]}),f==="ide"&&s.jsx(Yn,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d}),f==="cli"&&s.jsx(Yn,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d}),f==="acp"&&s.jsx(Yn,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d})]})}function Mg({onNicknameSynced:e}={}){var pe,re,Z,ee,q,X,ae,je,ke,te;const{id:t}=bd(),r=Ls(),n=Na(),{sendCommand:a}=vt(),o=lr(),c=Qc(),l=Ic(),u=l.ides||[],m=l.initialLoaded??!0,d=u.find(E=>E.id===t&&E.type==="adhdev-daemon"),h=u.some(E=>E.type==="adhdev-daemon"),f=t?(pe=l.connectionRetryStatuses)==null?void 0:pe[t]:void 0,w=!!(f!=null&&f.blocked),[k,p]=i.useState("workspace"),[y,x]=i.useState("ide"),b=i.useRef(null),[v,R]=i.useState(null),g=i.useRef("__home__"),[M,C]=i.useState("__home__"),[S,j]=i.useState(!1),W=i.useRef(null);i.useEffect(()=>{!t||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,d,t]),i.useEffect(()=>{if(!t||!d||k!=="overview")return;const E=d.machine;(typeof(E==null?void 0:E.cpus)!="number"||typeof(E==null?void 0:E.totalMem)!="number"||typeof(E==null?void 0:E.arch)!="string"||typeof(E==null?void 0:E.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[k,c,d,t]),th(t&&k==="overview"?[t]:[],{enabled:k==="overview",intervalMs:tf});const L=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},I=Sb({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:W});i.useEffect(()=>et.onToast(ve=>{l.setToasts(we=>{if(we.some(Oe=>Oe.message===ve.message&&ve.timestamp-Oe.timestamp<3e3))return we;const Le={id:ve.id,message:ve.message,type:ve.type,timestamp:ve.timestamp,targetKey:ve.targetKey,actions:ve.actions};return[...we.slice(-4),Le]});const Ce=ve.duration||5e3;setTimeout(()=>l.setToasts(we=>we.filter(Pe=>Pe.id!==ve.id)),Ce)}),[l]);const D=(d==null?void 0:d.availableProviders)||[],U={};for(const E of D)U[E.type]=E.icon;const K=E=>U[E]||"",N=d?{id:d.id,hostname:tc(d,{fallbackId:d.id}),platform:((re=d.machine)==null?void 0:re.platform)||"unknown",arch:((Z=d.machine)==null?void 0:Z.arch)||"",cpus:((ee=d.machine)==null?void 0:ee.cpus)||0,totalMem:((q=d.machine)==null?void 0:q.totalMem)||0,freeMem:(X=d.machine)==null?void 0:X.freeMem,availableMem:(ae=d.machine)==null?void 0:ae.availableMem,loadavg:(je=d.machine)==null?void 0:je.loadavg,uptime:(ke=d.machine)==null?void 0:ke.uptime,release:((te=d.machine)==null?void 0:te.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,A=u.filter(E=>E.daemonId===t&&E.type!=="adhdev-daemon").filter(E=>!rr(E)&&!ws(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,version:E.version||"",instanceId:E.instanceId||"",status:E.status,workspace:E.workspace||null,terminals:E.terminals||0,aiAgents:Yu(E.aiAgents||(E.agents||[]).map(ve=>({id:ve.name,name:ve.name,status:ve.status,version:ve.version}))),activeChat:E.activeChat||null,chats:E.chats||[],childSessions:E.childSessions||[],cdpConnected:E.cdpConnected||!1,daemonId:t})),z=u.filter(E=>E.daemonId===t&&rr(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,cliName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,mode:E.mode,runtimeKey:E.runtimeKey,runtimeDisplayName:E.runtimeDisplayName,runtimeWorkspaceLabel:E.runtimeWorkspaceLabel,runtimeWriteOwner:E.runtimeWriteOwner||null,runtimeAttachedClients:E.runtimeAttachedClients||[],daemonId:t})),$=u.filter(E=>E.daemonId===t&&ws(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,acpName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,daemonId:t})),B=d?St(d,{fallbackId:t}):"",V="workspace",G=n.state,me=G==null?void 0:G.initialMachineTab,ne=G==null?void 0:G.initialWorkspaceCategory,xe=G==null?void 0:G.initialWorkspaceId,de=G==null?void 0:G.initialWorkspacePath,be=me==="ides"||me==="clis"||me==="acps"?"workspace":me||V,he=me==="ides"?"ide":me==="clis"?"cli":me==="acps"?"acp":ne,Y=[...A.map(E=>{var ve,Ce,we,Pe,Le;return{id:`ide:${E.type}:${E.workspace||""}`,label:((ve=E.activeChat)==null?void 0:ve.title)||E.type,kind:"ide",providerType:E.type,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Le=(Pe=(we=(Ce=E.activeChat)==null?void 0:Ce.messages)==null?void 0:we.at)==null?void 0:Pe.call(we,-1))==null?void 0:Le.timestamp)||0}}),...z.map(E=>{var ve,Ce,we,Pe,Le;return{id:`cli:${E.type}:${E.workspace||""}`,label:((ve=E.activeChat)==null?void 0:ve.title)||E.cliName,kind:"cli",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Le=(Pe=(we=(Ce=E.activeChat)==null?void 0:Ce.messages)==null?void 0:we.at)==null?void 0:Pe.call(we,-1))==null?void 0:Le.timestamp)||0}}),...$.map(E=>{var ve,Ce,we,Pe,Le;return{id:`acp:${E.type}:${E.workspace||""}`,label:((ve=E.activeChat)==null?void 0:ve.title)||E.acpName,kind:"acp",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:us(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Le=(Pe=(we=(Ce=E.activeChat)==null?void 0:Ce.messages)==null?void 0:we.at)==null?void 0:Pe.call(we,-1))==null?void 0:Le.timestamp)||0}})].sort((E,ve)=>(ve.lastLaunchedAt||0)-(E.lastLaunchedAt||0)),oe=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(E=>({id:E.id,label:E.title||E.providerName||E.providerType,kind:E.kind,providerType:E.providerType,providerSessionId:E.providerSessionId,subtitle:us(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace,summaryMetadata:E.summaryMetadata,lastLaunchedAt:E.lastLaunchedAt})):Y,J=i.useMemo(()=>{var ve;const E=((ve=l.connectionStates)==null?void 0:ve[t||""])||void 0;return u.filter(Ce=>Ce.daemonId===t&&Ce.type!=="adhdev-daemon").flatMap(Ce=>Ja(Ce,{connectionStates:t&&E?{[t]:E}:void 0,defaultConnectionState:E})).filter(Ce=>!(Ce.transport==="pty"&&Ce.mode==="terminal")).sort((Ce,we)=>la(we)-la(Ce))},[u,l.connectionStates,t]),ue=i.useCallback(E=>{const ve=Ha(E);ve&&r(Gt(ve))},[r]),le=i.useCallback(()=>{b.current&&(j(!0),b.current().finally(()=>{b.current=null,j(!1),R(null)}))},[]),Se=i.useCallback(E=>{if(!N)return;const{options:ve,selectedKey:Ce}=is({machine:N,currentWorkspacePath:E.workspace}),we=async()=>{x(E.kind),p("workspace")};b.current=async()=>{const Pe=ve.find(ze=>ze.key===g.current),Le=(Pe==null?void 0:Pe.workspacePath)??null,Oe=(Pe==null?void 0:Pe.workspaceId)??null;if(E.kind==="ide"&&E.providerType){await I.handleLaunchIde(E.providerType,Le?{workspace:Le}:void 0);return}if((E.kind==="cli"||E.kind==="acp")&&E.providerType){await I.runLaunchCliCore({cliType:E.providerType,dir:Oe?void 0:Le||"",workspaceId:Oe||void 0,model:E.kind==="acp"&&rc(E.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:E.providerSessionId});return}await we()},g.current=Ce,C(Ce),R({title:E.kind==="ide"?rs("restart-ide",E.label):E.providerSessionId?qa(E.label):rs("start-fresh",E.label),description:E.kind==="ide"?ns("restart-ide"):E.providerSessionId?Ya():ns("start-fresh"),confirmLabel:E.kind==="ide"?Is("restart-ide"):E.providerSessionId?Yr(!0):Is("start-fresh"),busyLabel:E.kind==="ide"?Ms("restart-ide"):E.providerSessionId?Va(!0):Ms("start-fresh"),workspaceOptions:ve,details:[{label:"Mode",value:E.kind.toUpperCase()},...E.providerType?[{label:"Provider",value:E.providerType}]:[]]})},[I,N]);if(i.useEffect(()=>{p(be)},[V,be,t]),i.useEffect(()=>{he&&x(he)},[he,t]),!N)return m?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:L,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const ie=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nt,{size:14})," Workspace"]}),count:A.length+z.length+$.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ds,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(en,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(qd,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zd,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:L,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[I.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:I.nicknameInput,onChange:E=>I.setNicknameInput(E.target.value),onKeyDown:E=>{E.key==="Enter"&&I.handleSaveNickname(),E.key==="Escape"&&I.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:I.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:()=>I.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:()=>{I.setEditingNickname(!0),I.setNicknameInput(N.machineNickname||"")},title:"Click to set nickname",children:B}),w?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:[N.platform," · ",N.arch]}),s.jsxs("span",{children:[N.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),N.p2p.available&&s.jsxs("span",{children:["P2P ",N.p2p.state==="connected"?"connected":N.p2p.state]}),N.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:N.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(E=>s.jsxs("button",{onClick:()=>p(E.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${k===E.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[E.label,E.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${k===E.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:E.count})]},E.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[k==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(Sg,{machineEntry:d,providers:D,recentLaunches:oe,currentConversations:J,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:Se,onOpenConversation:ue}),s.jsx(Ig,{machine:N,machineId:t,providers:D,ideSessions:A,cliSessions:z,acpSessions:$,actions:I,getIcon:K,initialCategory:y,initialWorkspaceId:xe,initialWorkspacePath:de,sendDaemonCommand:a})]}),k==="providers"&&s.jsx(Pb,{machineId:t,providers:D,sendDaemonCommand:a}),k==="overview"&&s.jsx(Nb,{machineId:t,machine:N,ideSessions:A,cliSessions:z,acpSessions:$,actions:I,sendDaemonCommand:a}),k==="session-host"&&s.jsx(jg,{machineId:t,cliSessions:z,sendDaemonCommand:a}),k==="logs"&&s.jsx(hg,{machineId:t,sendDaemonCommand:a})]})})}),I.launchPick&&N&&s.jsx(kg,{machine:N,launchPick:I.launchPick,actions:I}),v&&s.jsx(ao,{title:v.title,description:v.description,details:v.details,workspaceOptions:v.workspaceOptions,selectedWorkspaceKey:M,onWorkspaceChange:E=>{g.current=E,C(E)},confirmLabel:v.confirmLabel,busyLabel:v.busyLabel,busy:S,onConfirm:le,onCancel:()=>{b.current=null,R(null)}}),s.jsx(Bc,{toasts:l.toasts||[],onDismiss:E=>l.setToasts(ve=>ve.filter(Ce=>Ce.id!==E)),onClickToast:E=>{E.targetKey&&r(Gt(E.targetKey))}}),s.jsx("style",{children:`
85
+ `)}function xg(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function bg(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function gg({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:c,searchQuery:l,daemonLoading:u,traceLoading:m,daemonFetchError:d,traceFetchError:h}){const f=qb(n,o),v=Jb(e,l),j=eg(t,l),p=tg(f,l),y=sg(a,l),x=xg(v,c),b=c==="all"?j:[],w=bg(p,c),R=c==="issues"?[]:y,g=rg({daemonLogs:v,daemonRawLines:j,trace:p,webEvents:y}),I=ug({daemonLogs:x,daemonRawLines:b,trace:w,webEvents:R}),C=fg(I),S=og({daemonLoading:u,traceLoading:m,daemonFetchError:d,traceFetchError:h,daemonLogKind:r,daemonLogsCount:v.length,daemonRawLineCount:j.length,traceCount:p.length,webEventCount:y.length});return{filteredDaemonLogs:v,filteredDaemonRawLines:j,filteredTraceEntries:p,filteredWebEvents:y,visibleDaemonLogs:x,visibleDaemonRawLines:b,visibleTraceEntries:w,visibleWebEvents:R,quickFilterCounts:g,diagnosticEvents:I,diagnosticsSummary:C,sourceStates:S}}function yg(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Dl(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function wa(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 Un(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 co(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function vg({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${wa(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Dl(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:co(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 wg({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:c,onCopyVisible:l,onToggleAutoRefresh:u,onRefresh:m,onClear:d}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(h=>s.jsx("button",{type:"button",onClick:()=>a(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),s.jsx("input",{value:r,onChange:h=>o(h.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:l,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:u,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:d,className:"machine-btn",children:"Clear"})]})]})}function kg({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:Vb.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 jg({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:c,traceFetchError:l}){var d,h;const u=((d=e.latestIssue)==null?void 0:d.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",m=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 ${Un(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 ${Un(u)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[co(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:Dl(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 ${Un(m)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:c||l?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",yg(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(f=>s.jsxs("div",{children:[f.label,": ",f.status]},f.id))})]})]})}function Sg({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()," · ",co(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function Ng({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:c,visibleWebEvents:l,quickFilter:u,searchQuery:m}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,timeline:!d.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(d=>s.jsx(vg,{event:d},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,daemon:!d.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:u==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((d,h)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:d},`raw-${h}`)),e.daemonLogKind!=="text"&&a.map((d,h)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${wa(d.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(d.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:d.level==="error"?"ERR":d.level==="warn"?"WRN":d.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:d.message})]},`log-${h}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,trace:!d.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[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:m.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),c.map(d=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${wa(d.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.level.toUpperCase()}),s.jsxs("span",{children:[d.category,".",d.stage]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:As(d.payload,360)||"No payload"})]},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,web:!d.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[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:m.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),l.map(d=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.kind}),d.topic&&s.jsxs("span",{children:["topic=",d.topic]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:As(d.payload,360)||"No payload"})]},d.id))]})]})]})}function Cg({machineId:e,sendDaemonCommand:t}){const r=ag({machineId:e,sendDaemonCommand:t}),[n,a]=i.useState("info"),[o,c]=i.useState(""),[l,u]=i.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=i.useRef(null),d=i.useRef(!1),h=i.useMemo(()=>gg({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:o,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,o,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);i.useEffect(()=>{if(r.autoRefresh&&h.diagnosticEvents.length>0){const j=d.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:j}),d.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const f=i.useCallback(async()=>{var p;const j=ng({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!j.trim()){et.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(j)),et.showToast("Copied visible logs to clipboard.","success")}catch(y){et.showToast(y instanceof Error?y.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),v=i.useCallback(async()=>{var p;const j=hg({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(j)),et.showToast("Copied diagnostic bundle to clipboard.","success")}catch(y){et.showToast(y instanceof Error?y.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(wg,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{v()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>r.setAutoRefresh(j=>!j),onRefresh:r.refresh,onClear:r.clear}),s.jsx(kg,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(jg,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(Sg,{patterns:h.diagnosticsSummary.repeatedPatterns}),s.jsx(Ng,{streams:r,sectionsOpen:l,setSectionsOpen:u,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function Tg(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 El(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 Mg(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const c=String((o==null?void 0:o.lifecycle)||"").trim(),l=El((o==null?void 0:o.meta)||void 0),u=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?t.push(o):(c==="stopped"||c==="failed")&&(u||l)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function Ig(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function zn(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 Vn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Gn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Ni(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 Ag(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Lg(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 Rg(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 _g({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,c]=i.useState(null),[l,u]=i.useState(!1),m=fh(e,{enabled:!!e,includeSessions:!0,limit:Eo,intervalMs:lf}),d=m.diagnostics,h=m.loading,f=m.applyDiagnostics,v=i.useMemo(()=>Tg({diagnostics:d,loading:h,refreshing:l,error:n}),[d,h,l,n]),j=i.useMemo(()=>new Map(t.map(L=>[L.sessionId||L.id,L])),[t]),p=i.useCallback(async()=>{if(e){u(!0);try{const L=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Eo}),M=Vn(L);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Could not load hosted runtime diagnostics");f(M.diagnostics||M.result||null),a("")}catch(L){const M=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";a(M)}finally{u(!1)}}},[f,e,r]);i.useEffect(()=>{!e||d||h||l||p()},[d,h,e,p,l]);const y=i.useCallback(async(L,M)=>{const E=`${L}:${M.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${M.displayName}?
86
+ This will terminate the hosted runtime.`))){c(E);try{const U=await r(e,L,{sessionId:M.sessionId}),K=Vn(U);if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Session host action failed");const N=L==="session_host_resume_session"?"resumed":L==="session_host_restart_session"?"restarted":"stopped";et.showToast(`Session host ${N}: ${M.displayName}`,"success"),await p()}catch(U){const K=U instanceof Error?U.message:"Session host action failed";et.showToast(K,"warning"),a(K)}finally{c(U=>U===E?null:U)}}},[e,p,r]),x=i.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
87
+ 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 M=await r(e,"session_host_prune_duplicate_sessions",{}),E=Vn(M);if(!(E!=null&&E.success))throw new Error((E==null?void 0:E.error)||"Duplicate prune failed");const U=E.result||{},K=Array.isArray(U.prunedSessionIds)?U.prunedSessionIds.length:0,N=typeof U.duplicateGroupCount=="number"?U.duplicateGroupCount:0;et.showToast(`Pruned ${K} duplicate runtime(s) across ${N} group(s)`,"success"),await p()}catch(M){const E=M instanceof Error?M.message:"Duplicate prune failed";et.showToast(E,"warning"),a(E)}finally{c(M=>M==="session_host_prune_duplicate_sessions"?null:M)}}},[e,p,r]),b=i.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((L,M)=>(M.lastActivityAt||0)-(L.lastActivityAt||0)),[d==null?void 0:d.sessions]),w=i.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:Mg(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),R=w.liveRuntimes,g=w.recoverySnapshots,I=w.inactiveRecords,C=i.useMemo(()=>Rg(R),[R]),S=i.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),k=i.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[d==null?void 0:d.recentLogs]),W=(L,M)=>{var G;const E=o===`session_host_resume_session:${L.sessionId}`,U=o===`session_host_restart_session:${L.sessionId}`,K=o===`session_host_stop_session:${L.sessionId}`,N=El(L.meta),A=j.get(L.sessionId),z=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,$=M==="recovery"?"Recover":"Resume",B=Ig(M);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:L.displayName||(A==null?void 0:A.cliName)||L.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Lg(L.lifecycle)}`,children:L.lifecycle}),N&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:N})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:L.workspaceLabel||(A==null?void 0:A.runtimeWorkspaceLabel)||L.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:L.runtimeKey}),L.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",L.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((G=L.writeOwner)==null?void 0:G.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Ag(L.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(Oi,{size:11})," ",z]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Ni(L.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",B]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[M==="recovery"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{y("session_host_resume_session",L)},children:E?`${$}ing…`:$}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{y("session_host_restart_session",L)},children:U?"Restarting…":"Restart"}),M==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{y("session_host_stop_session",L)},children:K?"Stopping…":"Stop"})]})]})},L.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(ds,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:yp()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[C>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 (${C})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${v.toneClass}`,children:v.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||l,children:[s.jsx(or,{size:13}),h||l?"Refreshing…":"Refresh"]})]})]}),n&&!d&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(tr,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children: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:d.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Ni(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Gn(d.hostStartedAt)})]})]}),k&&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(tr,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:k.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Gn(k.timestamp),k.sessionId?` · ${k.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(Ia,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:zn("live")}),R.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:R.map(L=>W(L,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(ds,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:zn("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(L=>W(L,"recovery"))})]}),I.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:zn("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:I.map(L=>W(L,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),S.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:S.map(L=>{var E;const M=b.find(U=>U.sessionId===L.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(M==null?void 0:M.displayName)||((E=j.get(L.sessionId))==null?void 0:E.cliName)||L.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[L.action,L.lifecycle?` · ${L.lifecycle}`:"",L.detail?` · ${L.detail}`:"",L.error?` · ${L.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${L.success===!1?"text-red-300":"text-text-secondary"}`,children:Gn(L.timestamp)})]},`${L.sessionId}:${L.timestamp}:${L.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Pg({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 qn({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 Yn({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 Dg({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),d=Xs(e,"0.9.56");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(qn,{icon:s.jsx(Ht,{size:13}),children:"Current Chats"}),s.jsx(Yn,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const f=da(h);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(h),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(h)}),f>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:rn(f)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ms(h)})]},h.tabKey)})})})]}),u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qn,{icon:s.jsx(zi,{size:13}),children:"Recent Launches"}),s.jsx(Yn,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:f,updatedLabel:v}=bl(h);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(h),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:h.label}),v&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:v})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:f})]},h.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qn,{icon:s.jsx(tr,{size:13}),children:"Daemon Update"}),s.jsx(Yn,{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:d?"Daemon update required":"Version mismatch detected"}),s.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:d?"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(or,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Eg(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function $g({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:u=>{const m=u.target.value;if(o(m),m==="__custom__"&&a){l();return}m!=="__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(u=>s.jsxs("option",{value:u.id,children:[u.id===e.defaultWorkspaceId?"⭐ ":"",an(u.path,u.label)]},u.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:u=>c(u.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 Bg={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 Mr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Xn({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:m}){const d=Ls(),{handleLaunchIde:h,handleStopCli:f,handleRestartIde:v,handleStopIde:j,handleDetectIdes:p,launchingIde:y,launchingAgentType:x,addLog:b}=c,[w,R]=i.useState(null),g=i.useCallback(O=>{O&&d(Gt(O))},[d]),I=Bg[e],C=e==="ide",S=e==="acp",k=i.useMemo(()=>n.filter(O=>ps(O,e)),[e,n]),W=i.useMemo(()=>new Map(k.map(O=>[O.type,O.displayName||O.type])),[k]),[L,M]=i.useState(""),[E,U]=i.useState(""),[K,N]=i.useState([]),[A,z]=i.useState(""),[$,B]=i.useState(""),[G,V]=i.useState([]),[me,ae]=i.useState(!1),[xe,de]=i.useState(!1),[be,he]=i.useState(""),[Y,oe]=i.useState(!1),[J,ue]=i.useState(()=>ht()),[le,Se]=i.useState(null),[ie,pe]=i.useState(m?"__custom__":u||t.defaultWorkspaceId||""),[ne,Z]=i.useState(m||""),[ee,q]=i.useState([]),[X,re]=i.useState(!1),[je,we]=i.useState(""),[te,D]=i.useState([]),[ve,Ce]=i.useState(!1),[ke,Pe]=i.useState(""),Le=i.useRef(null),[Oe,ze]=i.useState(null),tt=i.useRef("__home__"),[Xe,Ye]=i.useState("__home__"),[mt,pt]=i.useState(!1),dt=i.useRef(0),Te=ee.filter(O=>!a.some(se=>se.type===O&&bt(se.status)!=="stopped")),Fe=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!ie&&pe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(m){pe("__custom__"),Z(m);return}u&&(pe(u),Z(""))},[u,m]),i.useEffect(()=>{C||L&&(k.some(O=>O.type===L)||(M(""),B("")))},[k,C,L]);const Ge=(()=>{if(ie==="__custom__")return ne.trim();if(!ie)return"";const O=(t.workspaces||[]).find(se=>se.id===ie);return(O==null?void 0:O.path)||""})(),ct=i.useCallback(O=>{const se=Fe.current[O];se&&(clearTimeout(se),delete Fe.current[O]),q(ge=>ge.includes(O)?ge.filter(Be=>Be!==O):ge)},[]),ft=i.useRef(new Set),H=i.useCallback(async O=>{if(l){Ce(!0),Pe("");try{const se=await mn(l,r,O);we(se.path),Z(se.path),D(se.directories)}catch(se){Pe(se instanceof Error?se.message:"Could not load folder")}finally{Ce(!1)}}},[r,l]),_=i.useCallback(()=>{if(!l)return;pe("__custom__"),re(!0);const O=a.map(ge=>ge.workspace),se=un(t.platform,dn(ne.trim(),Ge,m,O,t.defaultWorkspacePath,(t.workspaces||[]).map(ge=>ge.path)));H(se)},[ne,m,H,t.defaultWorkspacePath,t.platform,t.workspaces,a,Ge,l]),T=i.useCallback(O=>{const se=String(O.workspace||"").trim();if(!se)return;const ge=(t.workspaces||[]).find(Be=>Mr(Be.path)===Mr(se));if(ge){pe(ge.id),Z("");return}pe("__custom__"),Z(se)},[t.workspaces]),P=i.useCallback(O=>{const se=String(O.workspace||"").trim();if(!se)return{workspaceId:null,workspacePath:"",useHome:!0};const ge=(t.workspaces||[]).find(Be=>Mr(Be.path)===Mr(se));return ge?{workspaceId:ge.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:se,useHome:!1}},[t.workspaces]),F=i.useCallback(async O=>{if(!l||!O||e!=="cli"){V([]),ae(!1),de(!1),he("");return}const se=dt.current+1;dt.current=se,ae(!0),he("");try{const ge=await l(r,"list_saved_sessions",{providerType:O,kind:"cli",limit:30});if(dt.current!==se)return;const Be=(ge==null?void 0:ge.result)??ge;V(Array.isArray(Be==null?void 0:Be.sessions)?Be.sessions:[])}catch(ge){if(dt.current!==se)return;V([]),he(ge instanceof Error?ge.message:"Could not load saved sessions")}finally{dt.current===se&&(ae(!1),de(!0))}},[e,r,l]),Q=i.useMemo(()=>{if(e!=="cli"||!L)return null;const O=W.get(L)||L;return{routeId:r,daemonId:r,providerSessionId:$||void 0,transport:"pty",mode:"chat",agentName:O,agentType:L,status:"idle",title:O,messages:[],ideType:L,workspaceName:Ge,workspacePath:Ge,displayPrimary:O,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${L}`}},[e,r,W,Ge,$,L]),ye=i.useCallback(O=>{if(e==="ide"||!O){N([]);return}N(Ll(r,O))},[e,r]);i.useEffect(()=>{dt.current+=1,B(""),ye(L),de(!1),V([]),he(""),ae(!1)},[e,ye,F,L]);const ce=i.useMemo(()=>G.find(O=>O.providerSessionId===$)||null,[G,$]);i.useEffect(()=>{if(!$)return;const O=G.find(se=>se.providerSessionId===$);O!=null&&O.canResume||B("")},[G,$]);const Ne=i.useCallback((O,se)=>{Le.current=se,tt.current=O.selectedWorkspaceKey||"__home__",Ye(O.selectedWorkspaceKey||"__home__"),ze(O)},[]),De=i.useCallback(()=>{Le.current&&(pt(!0),Le.current().finally(()=>{Le.current=null,pt(!1),ze(null)}))},[]),$e=i.useCallback(O=>{if(!O)return;q(ge=>ge.includes(O)?ge:[...ge,O]);const se=Fe.current[O];se&&clearTimeout(se),Fe.current[O]=setTimeout(()=>{q(ge=>ge.includes(O)?ge.filter(Be=>Be!==O):ge),delete Fe.current[O]},2e4)},[]);i.useEffect(()=>{for(const se of a)bt(se.status)!=="stopped"&&(ee.includes(se.type)&&!ft.current.has(se.type)&&(ft.current.add(se.type),b("info",`${W.get(se.type)||se.type} launched`,!0)),ct(se.type));const O=new Set(a.filter(se=>bt(se.status)!=="stopped").map(se=>se.type));ft.current.forEach(se=>{!ee.includes(se)&&!O.has(se)&&ft.current.delete(se)})},[b,ct,a,ee,W]),i.useEffect(()=>()=>{Object.values(Fe.current).forEach(clearTimeout),Fe.current={}},[]);const[Me,Re]=i.useState({}),[We,Ae]=i.useState(null);i.useEffect(()=>{if(!C||!r||!l)return;(async()=>{try{const se=await l(r,"get_ide_extensions",{}),ge=(se==null?void 0:se.result)||se;ge!=null&&ge.success&&(ge!=null&&ge.ideExtensions)&&Re(ge.ideExtensions)}catch{}})()},[C,r,l]);const Je=O=>C?ot(O.type):e==="cli"?O.cliName:O.acpName,Qe=C?t.detectedIdes||[]:[],fe=i.useCallback(async O=>{const se=(O==null?void 0:O.type)||L,ge=(O==null?void 0:O.workspacePath)??Ge;if(C){await h(se,ge?{workspace:ge}:void 0)&&$e(se);return}const Be=await c.runLaunchCliCore({cliType:se,dir:O!=null&&O.workspaceId?void 0:ge||void 0,workspaceId:(O==null?void 0:O.workspaceId)||void 0,useHome:(O==null?void 0:O.useHome)||!(O!=null&&O.workspaceId)&&!ge,argsStr:(O==null?void 0:O.argsStr)??(E||void 0),model:(O==null?void 0:O.model)??(S&&A||void 0),resumeSessionId:(O==null?void 0:O.resumeSessionId)||!S&&e==="cli"&&se===L&&$||void 0});if(Be.success||Be.pending){const Ie=(O==null?void 0:O.argsStr)??E;!C&&(Ie!=null&&Ie.trim())&&(Rl(r,se,Ie),ye(se)),$e(se),Be.success&&Be.sessionId&&g(Be.sessionId)}},[c,h,S,C,E,A,ye,$e,r,g,Ge,$,L]),_e=Kc(C?"ide":S?"acp":"cli",!C&&!S&&!!$),rt=Oc(C?"ide":S?"acp":"cli",!C&&!S&&!!$),nt=()=>{var Ie;const O=C?ot(L):W.get(L)||L,se=!C&&!S&&!!$,{options:ge,selectedKey:Be}=is({machine:t,currentWorkspaceId:ie&&ie!=="__custom__"?ie:null,currentWorkspacePath:Ge});Ne({title:se?qa(O):rs("start-fresh",O),description:se?Ya():ns("start-fresh"),confirmLabel:_e,busyLabel:rt,workspaceOptions:ge,selectedWorkspaceKey:Be,details:[{label:"Mode",value:I.label},{label:"Provider",value:O},...!C&&e==="cli"&&$?[{label:"Resume",value:((Ie=G.find(Ee=>Ee.providerSessionId===$))==null?void 0:Ie.title)||$}]:[],...!C&&E.trim()?[{label:"Arguments",value:E.trim()}]:[],...S&&A.trim()?[{label:"Model",value:A.trim()}]:[]]},async()=>{const Ee=ge.find(at=>at.key===tt.current);Ee!=null&&Ee.workspaceId?(pe(Ee.workspaceId),Z("")):Ee!=null&&Ee.workspacePath?(pe("__custom__"),Z(Ee.workspacePath)):(pe(""),Z("")),await fe({workspaceId:(Ee==null?void 0:Ee.workspaceId)??null,workspacePath:(Ee==null?void 0:Ee.workspacePath)??"",useHome:!(Ee!=null&&Ee.workspaceId)&&!(Ee!=null&&Ee.workspacePath)})})},He=O=>{C?j(O):f(O.type,O.workspace,O.id)},Mt=i.useCallback(async(O,se,ge=!1)=>{if(O.mode===se){ge&&O.sessionId&&g(O.sessionId);return}if(!l||!O.sessionId){ge&&O.sessionId&&g(O.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:O.sessionId,cliType:O.type,mode:se}),ge&&g(O.sessionId)}catch(Be){const Ie=ol(Be);al(Be)?console.warn(Ie?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Be instanceof Error?Be.message:String(Be)):console.error("Failed to switch CLI view mode:",Be)}},[r,g,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${I.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 ",I.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:C?Qe.length>0?Qe.map(O=>{const se=a.find(at=>(at.type||"").toLowerCase()===(O.type||"").toLowerCase()&&bt(at.status)!=="stopped"),ge=O.running||!!se,Be=!!se&&se.cdpConnected,Ie=ee.includes(O.type||O.id||""),Ee=L===(O.type||"");return s.jsxs("button",{onClick:()=>{if(Be&&se){const at=se.sessionId;at?d(Gt(at),{state:{openRemoteForTabKey:at}}):d("/dashboard",{state:{openRemoteForTabKey:se.id}});return}Ie||M(at=>at===(O.type||"")?"":O.type||"")},disabled:!!y||Ie,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Be?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ee?"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:y&&y!==O.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(O.type)}),ge&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Be?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:O.name||ot(O.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Be?"text-green-400":Ie?"text-orange-400":Ee?"text-accent-primary":"text-text-muted"}`,children:Be?"Open Session":Ie?"Starting...":Ee?"Configure":"Select"})]})]},O.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:p,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(Xd,{size:14})," Scan System"]})]}):k.length>0?k.map(O=>{const se=L===O.type,ge=ee.includes(O.type),Ie=!!a.find(Ee=>Ee.type===O.type&&bt(Ee.status)!=="stopped");return s.jsxs("button",{onClick:()=>M(Ee=>Ee===O.type?"":O.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${se?"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:O.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:O.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ge?"text-orange-400":se?"text-accent-primary":"text-text-muted"}`,children:ge?"Starting...":se?"Configure":"Select"})]})]},O.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."})]})}),L&&(C?Qe.find(O=>O.type===L):k.find(O=>O.type===L))&&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:C?ot(L):W.get(L)||L})]}),s.jsx($g,{machine:t,selectedWorkspace:ie,resolvedWorkspacePath:Ge,customPath:ne,canBrowse:!!l,onWorkspaceChange:pe,onCustomPathChange:Z,onOpenBrowseDialog:_}),!C&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!S&&e==="cli"&&s.jsx(Pl,{busy:!!x||!!y||ee.includes(L),savedSessionsLoading:me,savedSessionsError:be,savedSessionsLoaded:xe,savedSessionsCount:G.length,selectedSession:ce,onRefresh:()=>void F(L),onOpenHistory:()=>{L&&(oe(!0),_l({hasLoadedInitialResults:xe,isLoading:me})&&F(L))},onClearSelection:()=>B("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[S&&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:A,onChange:O=>z(O.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:E,onChange:O=>U(O.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"}),K.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:K.map(O=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>U(O),title:O,children:O},O))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:nt,disabled:!!x||!!y||ee.includes(L),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:x===L||y===L?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ee.filter(O=>!a.some(se=>se.type===O&&bt(se.status)!=="stopped")).length,")"]}),a.length===0&&Te.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 ",I.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Te.map(O=>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(O)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:C?ot(O):W.get(O)||O}),s.jsx("div",{className:"text-[11px] text-text-muted",children:x===O?"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:${O}`)),a.map(O=>{const se=C?O:null,ge=!C&&!S?O:null,Be=bt(O.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(O.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Je(O),(se==null?void 0:se.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",se.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:O.workspace||"—"}),s.jsx(ln,{git:O.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(ge==null?void 0:ge.mode)&&s.jsx("span",{className:ge.mode==="chat"?"text-violet-400":"text-text-secondary",children:ge.mode==="chat"?"Chat view":"Terminal view"})]}),ge&&(ge.runtimeKey||ge.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ge.runtimeKey&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),s.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ge.runtimeKey]}),s.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Ie;(Ie=navigator.clipboard)==null||Ie.writeText(`adhdev attach ${ge.runtimeKey}`),R(ge.runtimeKey||null),window.setTimeout(()=>{R(Ee=>Ee===ge.runtimeKey?null:Ee)},1200)},children:w===ge.runtimeKey?"Copied":"Copy"})]}),ge.runtimeWriteOwner&&s.jsx("span",{style:{color:ge.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ge.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Eg(ge.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Be==="stopped"?"bg-red-500/[0.08] text-red-500":Be==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Be}),C&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Ie=O.sessionId;if(Ie){d(Gt(Ie),{state:{openRemoteForTabKey:Ie}});return}d("/dashboard",{state:{openRemoteForTabKey:O.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(Nt,{size:13})}),s.jsx("button",{onClick:()=>{const Ie=O.workspace||"",{options:Ee,selectedKey:at}=is({machine:t,currentWorkspacePath:Ie});Ne({title:rs("restart-ide",ot(O.type)),description:ns("restart-ide"),confirmLabel:Ms("restart-ide"),busyLabel:Is("restart-ide"),workspaceOptions:Ee,selectedWorkspaceKey:at,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ot(O.type)}]},async()=>{const yt=Ee.find(Ut=>Ut.key===tt.current),ut=(yt==null?void 0:yt.workspacePath)??"";if(ut&&ut!==Ie){await fe({type:O.type,workspacePath:ut});return}await v(O)})},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(or,{size:14})})]}),S&&s.jsx("button",{onClick:()=>{const Ie=O.sessionId;Ie&&g(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:!O.sessionId,children:s.jsx(Ht,{size:14})}),ge&&Be!=="stopped"&&s.jsxs(s.Fragment,{children:[ge.mode&&s.jsx(za,{mode:ge.mode,onChange:Ie=>void Mt(ge,Ie,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Ie=O.sessionId;Ie&&g(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:!O.sessionId,children:ge.mode==="chat"?s.jsx(Ht,{size:14}):s.jsx(Nt,{size:13})})]}),Be==="stopped"?s.jsx("button",{onClick:()=>{const Ie=O.workspace||"",Ee=C?ot(O.type):Je(O),{options:at,selectedKey:yt}=is({machine:t,currentWorkspacePath:Ie});Ne({title:rs("restart-stopped",Ee),description:ns("restart-stopped"),confirmLabel:Ms("restart-stopped"),busyLabel:Is("restart-stopped"),workspaceOptions:at,selectedWorkspaceKey:yt,details:[{label:"Mode",value:I.label},{label:"Provider",value:Ee}]},async()=>{const ut=at.find(Ut=>Ut.key===tt.current);await fe({type:O.type,workspaceId:(ut==null?void 0:ut.workspaceId)??null,workspacePath:(ut==null?void 0:ut.workspacePath)??"",useHome:!(ut!=null&&ut.workspaceId)&&!(ut!=null&&ut.workspacePath)})})},disabled:ee.includes(O.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:ee.includes(O.type)?"⏳":s.jsx(Aa,{size:14})}):s.jsx("button",{onClick:()=>He(O),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:s.jsx(wt,{size:14})})]})]}),se&&se.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:se.aiAgents.map(Ie=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${tc(Ie.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ie.name," · ",bt(Ie.status)]},Ie.id))}),se&&(Me[se.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:(Me[se.type]||[]).map(Ie=>s.jsxs("button",{disabled:We===`${se.type}.${Ie.type}`,onClick:async()=>{const Ee=`${se.type}.${Ie.type}`;Ae(Ee);try{await l(r,"set_ide_extension",{ideType:se.type,extensionType:Ie.type,enabled:!Ie.enabled}),Re(at=>({...at,[se.type]:(at[se.type]||[]).map(yt=>yt.type===Ie.type?{...yt,enabled:!yt.enabled}:yt)}))}catch(at){console.error("Extension toggle failed:",at)}finally{Ae(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))})]})]},O.id)})]}),X&&l&&s.jsx(fn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:je,directories:te,busy:ve,error:ke,confirmLabel:"Use this folder",onClose:()=>re(!1),onNavigate:O=>{H(O)},onConfirm:O=>{Z(O),pe("__custom__"),re(!1)}}),Oe&&s.jsx(ao,{title:Oe.title,description:Oe.description,details:Oe.details,workspaceOptions:Oe.workspaceOptions,selectedWorkspaceKey:Xe,onWorkspaceChange:O=>{tt.current=O,Ye(O)},confirmLabel:Oe.confirmLabel,busyLabel:Oe.busyLabel,busy:mt,onConfirm:De,onCancel:()=>{Le.current=null,ze(null)}}),Y&&Q&&s.jsx(Xa,{activeConv:Q,ides:[],isCreatingChat:!1,isRefreshingHistory:me,savedSessions:G,isSavedSessionsLoading:me,isResumingSavedSessionId:le,savedHistoryFilters:J,missingWorkspaceResumePath:Ge||null,onSavedHistoryFiltersChange:ue,onClose:()=>oe(!1),onNewChat:()=>{B(""),oe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{F(L)},onResumeSavedSession:O=>{if(!O.canResume||le)return;const se=P(O);B(O.providerSessionId),T(O),Se(O.providerSessionId),oe(!1),fe({type:O.providerType,workspaceId:se.workspaceId,workspacePath:se.workspacePath,useHome:se.useHome,resumeSessionId:O.providerSessionId}).finally(()=>{Se(ge=>ge===O.providerSessionId?null:ge)})}})]})}const Ci=[{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 Kg({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:m,initialWorkspacePath:d,sendDaemonCommand:h}){var p;const[f,v]=i.useState(u);i.useEffect(()=>{v(u)},[u]);const j=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:Ci.map(y=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${f===y.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>v(y.id),children:[s.jsx("span",{children:y.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${f===y.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:j[y.id]})]},y.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(p=Ci.find(y=>y.id===f))==null?void 0:p.helper})]}),f==="ide"&&s.jsx(Xn,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d}),f==="cli"&&s.jsx(Xn,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d}),f==="acp"&&s.jsx(Xn,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d})]})}function Og({onNicknameSynced:e}={}){var pe,ne,Z,ee,q,X,re,je,we,te;const{id:t}=vd(),r=Ls(),n=Na(),{sendCommand:a}=vt(),o=lr(),c=tl(),l=Lc(),u=l.ides||[],m=l.initialLoaded??!0,d=u.find(D=>D.id===t&&D.type==="adhdev-daemon"),h=u.some(D=>D.type==="adhdev-daemon"),f=t?(pe=l.connectionRetryStatuses)==null?void 0:pe[t]:void 0,v=!!(f!=null&&f.blocked),[j,p]=i.useState("workspace"),[y,x]=i.useState("ide"),b=i.useRef(null),[w,R]=i.useState(null),g=i.useRef("__home__"),[I,C]=i.useState("__home__"),[S,k]=i.useState(!1),W=i.useRef(null);i.useEffect(()=>{!t||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,d,t]),i.useEffect(()=>{if(!t||!d||j!=="overview")return;const D=d.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(()=>{})},[j,c,d,t]),mh(t&&j==="overview"?[t]:[],{enabled:j==="overview",intervalMs:nf});const L=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},M=Db({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:W});i.useEffect(()=>et.onToast(ve=>{l.setToasts(ke=>{if(ke.some(Oe=>Oe.message===ve.message&&ve.timestamp-Oe.timestamp<3e3))return ke;const Le={id:ve.id,message:ve.message,type:ve.type,timestamp:ve.timestamp,targetKey:ve.targetKey,actions:ve.actions};return[...ke.slice(-4),Le]});const Ce=ve.duration||5e3;setTimeout(()=>l.setToasts(ke=>ke.filter(Pe=>Pe.id!==ve.id)),Ce)}),[l]);const E=(d==null?void 0:d.availableProviders)||[],U={};for(const D of E)U[D.type]=D.icon;const K=D=>U[D]||"",N=d?{id:d.id,hostname:sc(d,{fallbackId:d.id}),platform:((ne=d.machine)==null?void 0:ne.platform)||"unknown",arch:((Z=d.machine)==null?void 0:Z.arch)||"",cpus:((ee=d.machine)==null?void 0:ee.cpus)||0,totalMem:((q=d.machine)==null?void 0:q.totalMem)||0,freeMem:(X=d.machine)==null?void 0:X.freeMem,availableMem:(re=d.machine)==null?void 0:re.availableMem,loadavg:(je=d.machine)==null?void 0:je.loadavg,uptime:(we=d.machine)==null?void 0:we.uptime,release:((te=d.machine)==null?void 0:te.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,A=u.filter(D=>D.daemonId===t&&D.type!=="adhdev-daemon").filter(D=>!rr(D)&&!ws(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:Qu(D.aiAgents||(D.agents||[]).map(ve=>({id:ve.name,name:ve.name,status:ve.status,version:ve.version}))),activeChat:D.activeChat||null,chats:D.chats||[],childSessions:D.childSessions||[],cdpConnected:D.cdpConnected||!1,daemonId:t})),z=u.filter(D=>D.daemonId===t&&rr(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})),$=u.filter(D=>D.daemonId===t&&ws(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})),B=d?St(d,{fallbackId:t}):"",G="workspace",V=n.state,me=V==null?void 0:V.initialMachineTab,ae=V==null?void 0:V.initialWorkspaceCategory,xe=V==null?void 0:V.initialWorkspaceId,de=V==null?void 0:V.initialWorkspacePath,be=me==="ides"||me==="clis"||me==="acps"?"workspace":me||G,he=me==="ides"?"ide":me==="clis"?"cli":me==="acps"?"acp":ae,Y=[...A.map(D=>{var ve,Ce,ke,Pe,Le;return{id:`ide:${D.type}:${D.workspace||""}`,label:((ve=D.activeChat)==null?void 0:ve.title)||D.type,kind:"ide",providerType:D.type,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Le=(Pe=(ke=(Ce=D.activeChat)==null?void 0:Ce.messages)==null?void 0:ke.at)==null?void 0:Pe.call(ke,-1))==null?void 0:Le.timestamp)||0}}),...z.map(D=>{var ve,Ce,ke,Pe,Le;return{id:`cli:${D.type}:${D.workspace||""}`,label:((ve=D.activeChat)==null?void 0:ve.title)||D.cliName,kind:"cli",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Le=(Pe=(ke=(Ce=D.activeChat)==null?void 0:Ce.messages)==null?void 0:ke.at)==null?void 0:Pe.call(ke,-1))==null?void 0:Le.timestamp)||0}}),...$.map(D=>{var ve,Ce,ke,Pe,Le;return{id:`acp:${D.type}:${D.workspace||""}`,label:((ve=D.activeChat)==null?void 0:ve.title)||D.acpName,kind:"acp",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:us(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Le=(Pe=(ke=(Ce=D.activeChat)==null?void 0:Ce.messages)==null?void 0:ke.at)==null?void 0:Pe.call(ke,-1))==null?void 0:Le.timestamp)||0}})].sort((D,ve)=>(ve.lastLaunchedAt||0)-(D.lastLaunchedAt||0)),oe=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(D=>({id:D.id,label:D.title||D.providerName||D.providerType,kind:D.kind,providerType:D.providerType,providerSessionId:D.providerSessionId,subtitle:us(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace,summaryMetadata:D.summaryMetadata,lastLaunchedAt:D.lastLaunchedAt})):Y,J=i.useMemo(()=>{var ve;const D=((ve=l.connectionStates)==null?void 0:ve[t||""])||void 0;return u.filter(Ce=>Ce.daemonId===t&&Ce.type!=="adhdev-daemon").flatMap(Ce=>Ja(Ce,{connectionStates:t&&D?{[t]:D}:void 0,defaultConnectionState:D})).filter(Ce=>!(Ce.transport==="pty"&&Ce.mode==="terminal")).sort((Ce,ke)=>da(ke)-da(Ce))},[u,l.connectionStates,t]),ue=i.useCallback(D=>{const ve=Ha(D);ve&&r(Gt(ve))},[r]),le=i.useCallback(()=>{b.current&&(k(!0),b.current().finally(()=>{b.current=null,k(!1),R(null)}))},[]),Se=i.useCallback(D=>{if(!N)return;const{options:ve,selectedKey:Ce}=is({machine:N,currentWorkspacePath:D.workspace}),ke=async()=>{x(D.kind),p("workspace")};b.current=async()=>{const Pe=ve.find(ze=>ze.key===g.current),Le=(Pe==null?void 0:Pe.workspacePath)??null,Oe=(Pe==null?void 0:Pe.workspaceId)??null;if(D.kind==="ide"&&D.providerType){await M.handleLaunchIde(D.providerType,Le?{workspace:Le}:void 0);return}if((D.kind==="cli"||D.kind==="acp")&&D.providerType){await M.runLaunchCliCore({cliType:D.providerType,dir:Oe?void 0:Le||"",workspaceId:Oe||void 0,model:D.kind==="acp"&&nc(D.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:D.providerSessionId});return}await ke()},g.current=Ce,C(Ce),R({title:D.kind==="ide"?rs("restart-ide",D.label):D.providerSessionId?qa(D.label):rs("start-fresh",D.label),description:D.kind==="ide"?ns("restart-ide"):D.providerSessionId?Ya():ns("start-fresh"),confirmLabel:D.kind==="ide"?Ms("restart-ide"):D.providerSessionId?Xr(!0):Ms("start-fresh"),busyLabel:D.kind==="ide"?Is("restart-ide"):D.providerSessionId?Va(!0):Is("start-fresh"),workspaceOptions:ve,details:[{label:"Mode",value:D.kind.toUpperCase()},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]})},[M,N]);if(i.useEffect(()=>{p(be)},[G,be,t]),i.useEffect(()=>{he&&x(he)},[he,t]),!N)return m?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:L,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const ie=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nt,{size:14})," Workspace"]}),count:A.length+z.length+$.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ds,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(tn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jd,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(qd,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:L,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[M.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:M.nicknameInput,onChange:D=>M.setNicknameInput(D.target.value),onKeyDown:D=>{D.key==="Enter"&&M.handleSaveNickname(),D.key==="Escape"&&M.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:M.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:()=>M.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:()=>{M.setEditingNickname(!0),M.setNicknameInput(N.machineNickname||"")},title:"Click to set nickname",children:B}),v?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:[N.platform," · ",N.arch]}),s.jsxs("span",{children:[N.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),N.p2p.available&&s.jsxs("span",{children:["P2P ",N.p2p.state==="connected"?"connected":N.p2p.state]}),N.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:N.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:()=>p(D.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${j===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 ${j===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:[j==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(Dg,{machineEntry:d,providers:E,recentLaunches:oe,currentConversations:J,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:Se,onOpenConversation:ue}),s.jsx(Kg,{machine:N,machineId:t,providers:E,ideSessions:A,cliSessions:z,acpSessions:$,actions:M,getIcon:K,initialCategory:y,initialWorkspaceId:xe,initialWorkspacePath:de,sendDaemonCommand:a})]}),j==="providers"&&s.jsx(zb,{machineId:t,providers:E,sendDaemonCommand:a}),j==="overview"&&s.jsx(Eb,{machineId:t,machine:N,ideSessions:A,cliSessions:z,acpSessions:$,actions:M,sendDaemonCommand:a}),j==="session-host"&&s.jsx(_g,{machineId:t,cliSessions:z,sendDaemonCommand:a}),j==="logs"&&s.jsx(Cg,{machineId:t,sendDaemonCommand:a})]})})}),M.launchPick&&N&&s.jsx(Pg,{machine:N,launchPick:M.launchPick,actions:M}),w&&s.jsx(ao,{title:w.title,description:w.description,details:w.details,workspaceOptions:w.workspaceOptions,selectedWorkspaceKey:I,onWorkspaceChange:D=>{g.current=D,C(D)},confirmLabel:w.confirmLabel,busyLabel:w.busyLabel,busy:S,onConfirm:le,onCancel:()=>{b.current=null,R(null)}}),s.jsx(Wc,{toasts:l.toasts||[],onDismiss:D=>l.setToasts(ve=>ve.filter(Ce=>Ce.id!==D)),onClickToast:D=>{D.targetKey&&r(Gt(D.targetKey))}}),s.jsx("style",{children:`
88
88
  @keyframes toast-in {
89
89
  from { opacity: 0; transform: translateX(40px); }
90
90
  to { opacity: 1; transform: translateX(0); }
91
91
  }
92
- `})]})}function lo(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Ag(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=lo();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 Pt(e,t){return await fetch(Ag(e),{credentials:"same-origin",...t})}function Pl(){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 Lg{constructor(){Ve(this,"adapters",new Map);Ve(this,"states",new Map);Ve(this,"runtimeListeners",new Map);Ve(this,"screenshotCallbacks",new Map);Ve(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 Pt(`${a.pathname}${a.search}`);if(!o.ok){let l=`Runtime snapshot unavailable (${o.status})`;try{const u=await o.json();u!=null&&u.error&&(l=u.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 Kt=new Lg;function Rg(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=lo();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Mr=Rg(),Ci=3e3,_g=3e4;let Lt=null,Pg=0;const Zr=new Map;let Jt=null,Qs=null;function Ti(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Fs(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Dg(e){return e==="connected"?"connected":e}async function Br(e,t,r){const n=Wc(e,r||{}),a=Lt;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++Pg}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{Zr.delete(o),l(new Error(`WS command timeout: ${t}`))},3e4);Zr.set(o,{resolve:m=>{clearTimeout(u),c(m)},reject:m=>{clearTimeout(u),l(m)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function ja(e,t){const r=Lt;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 Eg(e,t,r){const n=Lt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Wc(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 $g{constructor(t){Ve(this,"daemonId");Ve(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Lt==null?void 0:Lt.readyState)===WebSocket.OPEN}get connectionState(){return(Lt==null?void 0:Lt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Br(this.daemonId,t,r)}async sendInput(t,r){return Br(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Jt&&(clearInterval(Jt),Jt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Br(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());Kt.emitScreenshot(this.daemonId,a)}}catch{}};r(),Jt=setInterval(r,2e3)}stopScreenshots(t){Jt&&(clearInterval(Jt),Jt=null)}}let Tt=null;function Bg(e){return(!Tt||Tt.daemonId!==e)&&(Tt=new $g(e)),Tt}function Kg({children:e}){const t=i.useRef(er()),r=er();t.current=r;const{setUserName:n}=ls(),a=i.useRef(n);a.current=n;const o=i.useRef(null),c=i.useRef(null),[,l]=i.useState("disconnected"),u=i.useCallback((p,y)=>{l(p),Qs==null||Qs(p,y)},[]),m=i.useRef(null),d=i.useRef(),h=i.useRef(Ci),f=i.useRef(!0),w=i.useRef(!1),k=i.useRef("initial_connect");return i.useEffect(()=>{f.current=!0,w.current=!1;function p(){var b,v;if(!f.current||((b=m.current)==null?void 0:b.readyState)===WebSocket.OPEN||((v=m.current)==null?void 0:v.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Mr}...`),Fs("connect_attempt",{url:Mr,reason:k.current,delayMs:h.current});let x;try{x=new WebSocket(Mr)}catch(R){console.error("[Standalone WS] Failed to create WebSocket:",R),y();return}m.current=x,x.onopen=()=>{if(!f.current){x.close();return}u("connected"),h.current=Ci,Fs("open",{url:Mr,reason:k.current}),qt.resubscribeAll({sendData:ja}),console.log("[Standalone WS] Connected")},Lt=x,x.onmessage=R=>{var g,M;try{const C=JSON.parse(R.data);if((C.type==="command_result"||C.type==="error")&&C.requestId){const S=Zr.get(C.requestId);S&&(Zr.delete(C.requestId),C.type==="error"?S.reject(new Error(((g=C.data)==null?void 0:g.message)||"Command failed")):S.resolve(C.data));return}if(C.type==="session_output"){const S=C.sessionId||C.cliId||C.cliType;S&&Kt.emitSessionOutput(S,typeof C.data=="string"?C.data:"",typeof C.seq=="number"?C.seq:void 0);return}if(C.type==="runtime_snapshot"){Kt.emitRuntimeSnapshot(C.sessionId,typeof C.text=="string"?C.text:"",typeof C.seq=="number"?C.seq:0,!!C.truncated,typeof C.cols=="number"?C.cols:void 0,typeof C.rows=="number"?C.rows:void 0);return}if(C.type==="topic_update"){const S=C.update;S&&qt.publish(S);return}if(C.type==="status"||C.type==="initial_state"){const S=C.data;if(!S)return;const{injectEntries:j,markLoaded:W,getIdes:L}=t.current,I=S.instanceId||"standalone",D=L().find(N=>N.id===I),U=Bg(I);Kt.register(I,U),Kt.setState(I,"connected"),u("connected",I),Kt.emitStatus(I,S);const K=Gr(S,{daemonId:I,existingDaemon:D,existingEntries:L()});Ti("ws_status",{type:C.type,daemonId:I,sessions:(S.sessions||[]).map(N=>({id:N.id,parentId:N.parentId,providerType:N.providerType,kind:N.kind,transport:N.transport,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,title:N.title})),recentLaunches:(S.recentLaunches||[]).map(N=>({id:N.id,providerType:N.providerType,kind:N.kind,workspace:N.workspace,lastLaunchedAt:N.lastLaunchedAt}))}),Ti("entries",{daemonId:I,entries:K.filter(N=>N.type!=="adhdev-daemon").map(N=>({id:N.id,type:N.type,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,sessionId:N.sessionId}))}),K.length>0&&j(K,{authoritativeDaemonIds:[I]}),W(),c.current!==I&&((M=o.current)==null||M.call(o),c.current=I,o.current=qt.subscribe({sendData:ja},I,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${I}`,params:{includeSessions:!0}},N=>{if(N.topic!=="daemon.metadata")return;const A=t.current.getIdes(),z=A.find(B=>B.id===I),$=Gr(N.status,{daemonId:I,existingDaemon:z,existingEntries:A,timestamp:N.timestamp});$.length>0&&t.current.injectEntries($,{authoritativeDaemonIds:[I]}),N.userName&&a.current&&a.current(N.userName)}))}}catch(C){console.error("[Standalone WS] Parse error:",C)}},x.onclose=R=>{f.current&&(Tt==null||Tt.stopScreenshots(),Tt&&Kt.setState(Tt.daemonId,"disconnected"),u("disconnected"),m.current=null,k.current=`close:${R.code}${R.wasClean?":clean":":unclean"}`,Fs("close",{code:R.code,reason:R.reason||"",wasClean:R.wasClean}),y())},x.onerror=R=>{w.current||!f.current||(k.current="error",Fs("error",{message:R instanceof Event?"event":String(R),readyState:x.readyState}),console.warn("[Standalone WS] Error, will reconnect:",R))}}function y(){if(!f.current)return;clearTimeout(d.current);const x=h.current;console.log(`[Standalone WS] Reconnecting in ${x}ms...`),Fs("schedule_reconnect",{reason:k.current,delayMs:x}),d.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,_g),p()},x)}return p(),()=>{var x;f.current=!1,w.current=!0,(x=o.current)==null||x.call(o),o.current=null,c.current=null,clearTimeout(d.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Lt=null),Tt&&(Tt.stopScreenshots(),Kt.unregister(Tt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function Og({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(Qs=(c,l)=>{r(c),l&&a(l)},()=>{Qs=null}),[]);const o=i.useMemo(()=>{const c=t==="connected",l=Dg(t),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:t,isConnected:c,connectionStates:u}},[t,n]);return s.jsx(Dd,{connectionOverrides:o,children:s.jsx(Kg,{children:e})})}const Dl="adhdev_standalone_font_preferences",cs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},hn=[{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"}],ar=[{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"}],Wg=new Set(hn.map(e=>e.id)),Hg=new Set(ar.map(e=>e.id));function Et(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Kr("chat",t.chat),code:Kr("code",t.code),terminal:Kr("terminal",t.terminal)}}function Kr(e,t){const r=cs[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"?Wg:Hg).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Or(e,t){var a;const r=Kr(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?hn:ar;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function Fg(e){const t=Et(e),r=Or("chat",t.chat),n=Or("code",t.code),a=Or("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Zt(e,t=document.documentElement){const r=Et(e),n=Fg(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function ka(e){const t=Et(e);try{localStorage.setItem(Dl,JSON.stringify(t))}catch{}return t}function Ug(){try{const e=localStorage.getItem(Dl);if(e)return Et(JSON.parse(e))}catch{}return cs}function zg(){return Zt(Ug())}function Us(e,t){var n;const r=e==="chat"?hn:ar;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Vg=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Bi,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(ds,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(en,{}),label:"Settings"}];function Gg({children:e}){const t=Ls(),r=Na(),n=i.useMemo(()=>Vg.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(Oi,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Wi,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Tp,{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.54"]}),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 qg=[{icon:s.jsx(ds,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ht,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Hi,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Nt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(sr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Oi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Yg=[{icon:s.jsx(Xd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Bi,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(tn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Ud,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Ki,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Vd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Xg=[{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 Jg(){return s.jsxs(zc,{icon:s.jsx(Wi,{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.54"]}),children:[s.jsx(kt,{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(kt,{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:qg.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(kt,{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:Hc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Uc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Fc.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(kt,{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:Yg.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(kt,{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:Xg.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(Gc,{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(ou,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Xn(e,t,r){return{...e,[t]:r}}function Jn({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:Or(e,n)})]})]})]})}function Qg({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:c,onResetToSaved:l,onResetToDefaults:u}){const m=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Jn,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:hn,onChange:d=>o(Xn(e,"chat",d))}),s.jsx(Jn,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:ar,onChange:d=>o(Xn(e,"code",d))}),s.jsx(Jn,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:ar,onChange:d=>o(Xn(e,"terminal",d))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Us("chat",e.chat.preset)," · Code: ",Us("code",e.code.preset)," · Terminal: ",Us("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Us("chat",cs.chat.preset)," / ",Us("code",cs.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||!m,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:l,disabled:r||!m,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick:u,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function Zg(){const{ides:e}=ls(),t=e.find(Y=>Y.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=vt(),{userName:a}=ls(),[o,c]=i.useState(a||""),[l,u]=i.useState(null),[m,d]=i.useState(null),[h,f]=i.useState(cs),[w,k]=i.useState(!1),[p,y]=i.useState(""),[x,b]=i.useState(""),[v,R]=i.useState("127.0.0.1"),[g,M]=i.useState(""),[C,S]=i.useState(""),[j,W]=i.useState(""),[L,I]=i.useState(""),[D,U]=i.useState(""),[K,N]=i.useState(!1),A=async()=>{const oe=await(await Pt("/auth/session")).json();u(oe)},z=async()=>{const oe=await(await Pt("/api/v1/standalone/preferences")).json();d(oe),R(oe.standaloneBindHost);const J=Et(oe.standaloneFontPreferences);f(J),Zt(J),ka(J)};i.useEffect(()=>{a!==void 0&&c(a)},[a]),i.useEffect(()=>{Promise.all([A(),z()]).catch(Y=>{I(Y instanceof Error?Y.message:String(Y))})},[]),i.useEffect(()=>{Zt(h)},[h]);const $=Y=>{const oe=Y.target.value.trim();t!=null&&t.id&&oe!==a&&n(t.id,"set_user_name",{userName:oe}).catch(console.error)},[B,V]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),G=Y=>{V(Y);try{localStorage.setItem("adhdev_sound",Y?"1":"0")}catch{}},me=async()=>{y(""),b(""),k(!0);try{const Y=Et(h),oe=await Pt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:Y})}),J=await oe.json();if(!oe.ok)throw new Error((J==null?void 0:J.error)||"Failed to save standalone font preferences");const ue=Et(J.standaloneFontPreferences);d(J),f(ue),Zt(ue),ka(ue),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(Y){y(Y instanceof Error?Y.message:String(Y))}finally{k(!1)}},ne=()=>{const Y=Et(m==null?void 0:m.standaloneFontPreferences);y(""),b(""),f(Y),Zt(Y)},xe=()=>{y(""),b(""),f(cs),Zt(cs)},de=async()=>{I(""),U(""),N(!0);try{const Y=await Pt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:v})}),oe=await Y.json();if(!Y.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to save standalone network preference");d(oe),R(oe.standaloneBindHost),U(oe.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(Y){I(Y instanceof Error?Y.message:String(Y))}finally{N(!1)}},be=async()=>{if(I(""),U(""),C.trim().length<4){I("Password must be at least 4 characters.");return}if(C!==j){I("New password and confirmation do not match.");return}N(!0);try{const Y=await Pt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,newPassword:C})}),oe=await Y.json();if(!Y.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to save password");u(oe),await z(),M(""),S(""),W(""),U(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Pl()}catch(Y){I(Y instanceof Error?Y.message:String(Y))}finally{N(!1)}},he=async()=>{I(""),U(""),N(!0);try{const Y=await Pt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,clear:!0})}),oe=await Y.json();if(!Y.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to clear password");u(oe),await z(),M(""),S(""),W(""),U("Standalone password disabled.")}catch(Y){I(Y instanceof Error?Y.message:String(Y))}finally{N(!1)}};return s.jsxs(zc,{icon:s.jsx(en,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(wr,{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(wr,{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(kt,{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.54"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(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:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(kt,{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:()=>R("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:()=>R("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:()=>{de()},disabled:K,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:K?"Saving…":"Save default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(kt,{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."}),L&&s.jsx(wr,{variant:"error",children:L}),D&&s.jsx(wr,{variant:"success",children:D}),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:Y=>M(Y.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:C,onChange:Y=>S(Y.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:j,onChange:Y=>W(Y.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{be()},disabled:K,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:K?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{he()},disabled:K,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),s.jsx(kt,{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(Y=>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 ${Y.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:Y.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:Y.type})]},Y.type))})}),s.jsx(kt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Ep,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(kt,{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(Op,{})]}),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(qp,{})]}),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(Qg,{value:h,savedValue:Et(m==null?void 0:m.standaloneFontPreferences),saving:w,error:p,notice:x,onChange:f,onSave:()=>{me()},onResetToSaved:ne,onResetToDefaults:xe})]}),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(Jp,{})]})]})}),s.jsx(kt,{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(_p,{}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(au,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:B,onChange:G})]})}),s.jsx(kt,{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(Fd,{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:Y=>c(Y.target.value),onBlur:$,onKeyDown:Y=>{Y.key==="Enter"&&Y.currentTarget.blur()}})]})})})]})}Np();Vp();zg();const ey=Di({baseUrl:"",getToken:lo});function ty({children:e}){const[t,r]=i.useState(null),[n,a]=i.useState(!0),[o,c]=i.useState(""),[l,u]=i.useState(""),[m,d]=i.useState(!1),h=async()=>{a(!0),u("");try{const k=await(await Pt("/auth/session")).json();r(k)}catch(w){u(w instanceof Error?w.message:String(w))}finally{a(!1)}};i.useEffect(()=>{h()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let w=!1;return(async()=>{try{const k=await Pt("/api/v1/standalone/preferences");if(!k.ok)return;const p=await k.json();if(w)return;const y=Et(p.standaloneFontPreferences);Zt(y),ka(y)}catch{}})(),()=>{w=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const f=async w=>{w.preventDefault(),d(!0),u("");try{const k=await Pt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),p=await k.json();if(!k.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),Pl()}catch(k){u(k instanceof Error?k.message:String(k))}finally{d(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:f,children:[s.jsx("input",{type:"password",value:o,onChange:w=>c(w.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:m||!o,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:m?"Signing in…":"Unlock dashboard"})]}):s.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),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 Ii(){const{ides:e,initialLoaded:t}=ls();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(ea,{to:`/machines/${r.id}`,replace:!0}):s.jsx(ea,{to:"/dashboard",replace:!0})}function sy(){const e=i.useMemo(()=>({sendCommand:Br,sendData:ja,sendPtyInput:Eg}),[]);return s.jsx(gd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Bd,{client:ey,children:s.jsx(ty,{children:s.jsx(Og,{children:s.jsx(Od,{value:e,children:s.jsx(Gg,{children:s.jsxs(yd,{children:[s.jsx(Yt,{path:"/dashboard",element:s.jsx(kb,{})}),s.jsx(Yt,{path:"/machine",element:s.jsx(Ii,{})}),s.jsx(Yt,{path:"/machines/:id",element:s.jsx(Mg,{})}),s.jsx(Yt,{path:"/machines",element:s.jsx(Ii,{})}),s.jsx(Yt,{path:"/about",element:s.jsx(Jg,{})}),s.jsx(Yt,{path:"/settings",element:s.jsx(Zg,{})}),s.jsx(Yt,{path:"*",element:s.jsx(ea,{to:"/dashboard",replace:!0})})]})})})})})})})}Of({connectionManager:Kt});vd(document.getElementById("root")).render(s.jsx(sy,{}));
92
+ `})]})}function lo(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Wg(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=lo();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 Pt(e,t){return await fetch(Wg(e),{credentials:"same-origin",...t})}function $l(){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 Hg{constructor(){Ve(this,"adapters",new Map);Ve(this,"states",new Map);Ve(this,"runtimeListeners",new Map);Ve(this,"screenshotCallbacks",new Map);Ve(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 Pt(`${a.pathname}${a.search}`);if(!o.ok){let l=`Runtime snapshot unavailable (${o.status})`;try{const u=await o.json();u!=null&&u.error&&(l=u.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 Kt=new Hg;function Fg(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=lo();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Ir=Fg(),Ti=3e3,Ug=3e4;let Lt=null,zg=0;const en=new Map;let Jt=null,Qs=null;function Mi(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Fs(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Vg(e){return e==="connected"?"connected":e}async function Kr(e,t,r){const n=Uc(e,r||{}),a=Lt;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++zg}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{en.delete(o),l(new Error(`WS command timeout: ${t}`))},3e4);en.set(o,{resolve:m=>{clearTimeout(u),c(m)},reject:m=>{clearTimeout(u),l(m)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function ka(e,t){const r=Lt;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 Gg(e,t,r){const n=Lt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Uc(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 qg{constructor(t){Ve(this,"daemonId");Ve(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Lt==null?void 0:Lt.readyState)===WebSocket.OPEN}get connectionState(){return(Lt==null?void 0:Lt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Kr(this.daemonId,t,r)}async sendInput(t,r){return Kr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Jt&&(clearInterval(Jt),Jt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Kr(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());Kt.emitScreenshot(this.daemonId,a)}}catch{}};r(),Jt=setInterval(r,2e3)}stopScreenshots(t){Jt&&(clearInterval(Jt),Jt=null)}}let Tt=null;function Yg(e){return(!Tt||Tt.daemonId!==e)&&(Tt=new qg(e)),Tt}function Xg({children:e}){const t=i.useRef(er()),r=er();t.current=r;const{setUserName:n}=ls(),a=i.useRef(n);a.current=n;const o=i.useRef(null),c=i.useRef(null),[,l]=i.useState("disconnected"),u=i.useCallback((p,y)=>{l(p),Qs==null||Qs(p,y)},[]),m=i.useRef(null),d=i.useRef(),h=i.useRef(Ti),f=i.useRef(!0),v=i.useRef(!1),j=i.useRef("initial_connect");return i.useEffect(()=>{f.current=!0,v.current=!1;function p(){var b,w;if(!f.current||((b=m.current)==null?void 0:b.readyState)===WebSocket.OPEN||((w=m.current)==null?void 0:w.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Ir}...`),Fs("connect_attempt",{url:Ir,reason:j.current,delayMs:h.current});let x;try{x=new WebSocket(Ir)}catch(R){console.error("[Standalone WS] Failed to create WebSocket:",R),y();return}m.current=x,x.onopen=()=>{if(!f.current){x.close();return}u("connected"),h.current=Ti,Fs("open",{url:Ir,reason:j.current}),qt.resubscribeAll({sendData:ka}),console.log("[Standalone WS] Connected")},Lt=x,x.onmessage=R=>{var g,I;try{const C=JSON.parse(R.data);if((C.type==="command_result"||C.type==="error")&&C.requestId){const S=en.get(C.requestId);S&&(en.delete(C.requestId),C.type==="error"?S.reject(new Error(((g=C.data)==null?void 0:g.message)||"Command failed")):S.resolve(C.data));return}if(C.type==="session_output"){const S=C.sessionId||C.cliId||C.cliType;S&&Kt.emitSessionOutput(S,typeof C.data=="string"?C.data:"",typeof C.seq=="number"?C.seq:void 0);return}if(C.type==="runtime_snapshot"){Kt.emitRuntimeSnapshot(C.sessionId,typeof C.text=="string"?C.text:"",typeof C.seq=="number"?C.seq:0,!!C.truncated,typeof C.cols=="number"?C.cols:void 0,typeof C.rows=="number"?C.rows:void 0);return}if(C.type==="topic_update"){const S=C.update;S&&qt.publish(S);return}if(C.type==="status"||C.type==="initial_state"){const S=C.data;if(!S)return;const{injectEntries:k,markLoaded:W,getIdes:L}=t.current,M=S.instanceId||"standalone",E=L().find(N=>N.id===M),U=Yg(M);Kt.register(M,U),Kt.setState(M,"connected"),u("connected",M),Kt.emitStatus(M,S);const K=qr(S,{daemonId:M,existingDaemon:E,existingEntries:L()});Mi("ws_status",{type:C.type,daemonId:M,sessions:(S.sessions||[]).map(N=>({id:N.id,parentId:N.parentId,providerType:N.providerType,kind:N.kind,transport:N.transport,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,title:N.title})),recentLaunches:(S.recentLaunches||[]).map(N=>({id:N.id,providerType:N.providerType,kind:N.kind,workspace:N.workspace,lastLaunchedAt:N.lastLaunchedAt}))}),Mi("entries",{daemonId:M,entries:K.filter(N=>N.type!=="adhdev-daemon").map(N=>({id:N.id,type:N.type,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,sessionId:N.sessionId}))}),K.length>0&&k(K,{authoritativeDaemonIds:[M]}),W(),c.current!==M&&((I=o.current)==null||I.call(o),c.current=M,o.current=qt.subscribe({sendData:ka},M,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${M}`,params:{includeSessions:!0}},N=>{if(N.topic!=="daemon.metadata")return;const A=t.current.getIdes(),z=A.find(B=>B.id===M),$=qr(N.status,{daemonId:M,existingDaemon:z,existingEntries:A,timestamp:N.timestamp});$.length>0&&t.current.injectEntries($,{authoritativeDaemonIds:[M]}),N.userName&&a.current&&a.current(N.userName)}))}}catch(C){console.error("[Standalone WS] Parse error:",C)}},x.onclose=R=>{f.current&&(Tt==null||Tt.stopScreenshots(),Tt&&Kt.setState(Tt.daemonId,"disconnected"),u("disconnected"),m.current=null,j.current=`close:${R.code}${R.wasClean?":clean":":unclean"}`,Fs("close",{code:R.code,reason:R.reason||"",wasClean:R.wasClean}),y())},x.onerror=R=>{v.current||!f.current||(j.current="error",Fs("error",{message:R instanceof Event?"event":String(R),readyState:x.readyState}),console.warn("[Standalone WS] Error, will reconnect:",R))}}function y(){if(!f.current)return;clearTimeout(d.current);const x=h.current;console.log(`[Standalone WS] Reconnecting in ${x}ms...`),Fs("schedule_reconnect",{reason:j.current,delayMs:x}),d.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Ug),p()},x)}return p(),()=>{var x;f.current=!1,v.current=!0,(x=o.current)==null||x.call(o),o.current=null,c.current=null,clearTimeout(d.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Lt=null),Tt&&(Tt.stopScreenshots(),Kt.unregister(Tt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function Jg({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(Qs=(c,l)=>{r(c),l&&a(l)},()=>{Qs=null}),[]);const o=i.useMemo(()=>{const c=t==="connected",l=Vg(t),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:t,isConnected:c,connectionStates:u}},[t,n]);return s.jsx(Bd,{connectionOverrides:o,children:s.jsx(Xg,{children:e})})}const Bl="adhdev_standalone_font_preferences",cs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},xn=[{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"}],ar=[{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"}],Qg=new Set(xn.map(e=>e.id)),Zg=new Set(ar.map(e=>e.id));function Et(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Or("chat",t.chat),code:Or("code",t.code),terminal:Or("terminal",t.terminal)}}function Or(e,t){const r=cs[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"?Qg:Zg).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Wr(e,t){var a;const r=Or(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?xn:ar;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function ey(e){const t=Et(e),r=Wr("chat",t.chat),n=Wr("code",t.code),a=Wr("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Zt(e,t=document.documentElement){const r=Et(e),n=ey(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function ja(e){const t=Et(e);try{localStorage.setItem(Bl,JSON.stringify(t))}catch{}return t}function ty(){try{const e=localStorage.getItem(Bl);if(e)return Et(JSON.parse(e))}catch{}return cs}function sy(){return Zt(ty())}function Us(e,t){var n;const r=e==="chat"?xn:ar;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const ry=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Ki,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(ds,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(tn,{}),label:"Settings"}];function ny({children:e}){const t=Ls(),r=Na(),n=i.useMemo(()=>ry.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(Wi,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Hi,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Bp,{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.56"]}),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(ds,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ht,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Fi,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Nt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(sr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Wi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],oy=[{icon:s.jsx(Zd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Ki,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(sn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Gd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Oi,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Yd,{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 cy(){return s.jsxs(qc,{icon:s.jsx(Hi,{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.56"]}),children:[s.jsx(jt,{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(jt,{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(jt,{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:Gc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Vc.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(jt,{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:oy.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(jt,{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(Xc,{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(lu,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Jn(e,t,r){return{...e,[t]:r}}function Qn({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:Wr(e,n)})]})]})]})}function ly({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:c,onResetToSaved:l,onResetToDefaults:u}){const m=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Qn,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:xn,onChange:d=>o(Jn(e,"chat",d))}),s.jsx(Qn,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:ar,onChange:d=>o(Jn(e,"code",d))}),s.jsx(Qn,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:ar,onChange:d=>o(Jn(e,"terminal",d))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Us("chat",e.chat.preset)," · Code: ",Us("code",e.code.preset)," · Terminal: ",Us("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Us("chat",cs.chat.preset)," / ",Us("code",cs.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||!m,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:l,disabled:r||!m,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick:u,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function dy(){const{ides:e}=ls(),t=e.find(Y=>Y.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=vt(),{userName:a}=ls(),[o,c]=i.useState(a||""),[l,u]=i.useState(null),[m,d]=i.useState(null),[h,f]=i.useState(cs),[v,j]=i.useState(!1),[p,y]=i.useState(""),[x,b]=i.useState(""),[w,R]=i.useState("127.0.0.1"),[g,I]=i.useState(""),[C,S]=i.useState(""),[k,W]=i.useState(""),[L,M]=i.useState(""),[E,U]=i.useState(""),[K,N]=i.useState(!1),A=async()=>{const oe=await(await Pt("/auth/session")).json();u(oe)},z=async()=>{const oe=await(await Pt("/api/v1/standalone/preferences")).json();d(oe),R(oe.standaloneBindHost);const J=Et(oe.standaloneFontPreferences);f(J),Zt(J),ja(J)};i.useEffect(()=>{a!==void 0&&c(a)},[a]),i.useEffect(()=>{Promise.all([A(),z()]).catch(Y=>{M(Y instanceof Error?Y.message:String(Y))})},[]),i.useEffect(()=>{Zt(h)},[h]);const $=Y=>{const oe=Y.target.value.trim();t!=null&&t.id&&oe!==a&&n(t.id,"set_user_name",{userName:oe}).catch(console.error)},[B,G]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),V=Y=>{G(Y);try{localStorage.setItem("adhdev_sound",Y?"1":"0")}catch{}},me=async()=>{y(""),b(""),j(!0);try{const Y=Et(h),oe=await Pt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:Y})}),J=await oe.json();if(!oe.ok)throw new Error((J==null?void 0:J.error)||"Failed to save standalone font preferences");const ue=Et(J.standaloneFontPreferences);d(J),f(ue),Zt(ue),ja(ue),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(Y){y(Y instanceof Error?Y.message:String(Y))}finally{j(!1)}},ae=()=>{const Y=Et(m==null?void 0:m.standaloneFontPreferences);y(""),b(""),f(Y),Zt(Y)},xe=()=>{y(""),b(""),f(cs),Zt(cs)},de=async()=>{M(""),U(""),N(!0);try{const Y=await Pt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:w})}),oe=await Y.json();if(!Y.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to save standalone network preference");d(oe),R(oe.standaloneBindHost),U(oe.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(Y){M(Y instanceof Error?Y.message:String(Y))}finally{N(!1)}},be=async()=>{if(M(""),U(""),C.trim().length<4){M("Password must be at least 4 characters.");return}if(C!==k){M("New password and confirmation do not match.");return}N(!0);try{const Y=await Pt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,newPassword:C})}),oe=await Y.json();if(!Y.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to save password");u(oe),await z(),I(""),S(""),W(""),U(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),$l()}catch(Y){M(Y instanceof Error?Y.message:String(Y))}finally{N(!1)}},he=async()=>{M(""),U(""),N(!0);try{const Y=await Pt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,clear:!0})}),oe=await Y.json();if(!Y.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to clear password");u(oe),await z(),I(""),S(""),W(""),U("Standalone password disabled.")}catch(Y){M(Y instanceof Error?Y.message:String(Y))}finally{N(!1)}};return s.jsxs(qc,{icon:s.jsx(tn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(wr,{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(wr,{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(jt,{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.56"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(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:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(jt,{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:w==="127.0.0.1",onChange:()=>R("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:w==="0.0.0.0",onChange:()=>R("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:()=>{de()},disabled:K,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:K?"Saving…":"Save default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(jt,{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."}),L&&s.jsx(wr,{variant:"error",children:L}),E&&s.jsx(wr,{variant:"success",children:E}),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:Y=>I(Y.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:C,onChange:Y=>S(Y.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:k,onChange:Y=>W(Y.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{be()},disabled:K,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:K?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{he()},disabled:K,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),s.jsx(jt,{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(Y=>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 ${Y.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:Y.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:Y.type})]},Y.type))})}),s.jsx(jt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Gp,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(jt,{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(Jp,{})]}),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(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:"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(ly,{value:h,savedValue:Et(m==null?void 0:m.standaloneFontPreferences),saving:v,error:p,notice:x,onChange:f,onSave:()=>{me()},onResetToSaved:ae,onResetToDefaults:xe})]}),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(ch,{})]})]})}),s.jsx(jt,{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(Up,{}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(cu,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:B,onChange:V})]})}),s.jsx(jt,{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(Vd,{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:Y=>c(Y.target.value),onBlur:$,onKeyDown:Y=>{Y.key==="Enter"&&Y.currentTarget.blur()}})]})})})]})}Ep();rh();sy();const uy=Ei({baseUrl:"",getToken:lo});function my({children:e}){const[t,r]=i.useState(null),[n,a]=i.useState(!0),[o,c]=i.useState(""),[l,u]=i.useState(""),[m,d]=i.useState(!1),h=async()=>{a(!0),u("");try{const j=await(await Pt("/auth/session")).json();r(j)}catch(v){u(v instanceof Error?v.message:String(v))}finally{a(!1)}};i.useEffect(()=>{h()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let v=!1;return(async()=>{try{const j=await Pt("/api/v1/standalone/preferences");if(!j.ok)return;const p=await j.json();if(v)return;const y=Et(p.standaloneFontPreferences);Zt(y),ja(y)}catch{}})(),()=>{v=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const f=async v=>{v.preventDefault(),d(!0),u("");try{const j=await Pt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),p=await j.json();if(!j.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),$l()}catch(j){u(j instanceof Error?j.message:String(j))}finally{d(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:f,children:[s.jsx("input",{type:"password",value:o,onChange:v=>c(v.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:m||!o,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:m?"Signing in…":"Unlock dashboard"})]}):s.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),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 Ii(){const{ides:e,initialLoaded:t}=ls();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(ta,{to:`/machines/${r.id}`,replace:!0}):s.jsx(ta,{to:"/dashboard",replace:!0})}function fy(){const e=i.useMemo(()=>({sendCommand:Kr,sendData:ka,sendPtyInput:Gg}),[]);return s.jsx(wd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Wd,{client:uy,children:s.jsx(my,{children:s.jsx(Jg,{children:s.jsx(Fd,{value:e,children:s.jsx(ny,{children:s.jsxs(kd,{children:[s.jsx(Yt,{path:"/dashboard",element:s.jsx(Pb,{})}),s.jsx(Yt,{path:"/machine",element:s.jsx(Ii,{})}),s.jsx(Yt,{path:"/machines/:id",element:s.jsx(Og,{})}),s.jsx(Yt,{path:"/machines",element:s.jsx(Ii,{})}),s.jsx(Yt,{path:"/about",element:s.jsx(cy,{})}),s.jsx(Yt,{path:"/settings",element:s.jsx(dy,{})}),s.jsx(Yt,{path:"*",element:s.jsx(ta,{to:"/dashboard",replace:!0})})]})})})})})})})}Jf({connectionManager:Kt});jd(document.getElementById("root")).render(s.jsx(fy,{}));