@adhdev/daemon-standalone 0.9.43 → 0.9.45

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,83 +0,0 @@
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 Xl=Object.defineProperty;var Jl=(e,t,r)=>t in e?Xl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var ze=(e,t,r)=>Jl(e,typeof t!="symbol"?t+"":t,r);import{r as o,j as s,M as xa,a as Ql,b as Zl,c as ed,u as Is,R as jt,d as Js,t as td,e as sd,D as rd,f as Gn,g as qn,h as ba,i as nd,k as ad,B as od,l as id,m as Gt,N as Yn,n as cd}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 i of a)if(i.type==="childList")for(const c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();function ld(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(a),r.length>t&&r.splice(0,r.length-t),a},list(n={}){const a=Math.max(1,Math.floor(n.limit||100));return r.filter(i=>!n.interactionId||i.interactionId===n.interactionId).filter(i=>!n.topic||i.topic===n.topic).filter(i=>!n.kind||i.kind===n.kind).slice(-a).map(i=>({...i,payload:i.payload?{...i.payload}:{}}))},clear(){r.splice(0,r.length)}}}const js=ld();function co(e){const t={};for(const r of e)r.transport&&(t[r.transport]=(t[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:t}}function dd(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function ud(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function vi(e,t){var m;if(!e)return t??null;if(!t)return e??null;const r=ud(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,i=r&&a&&(n==null?void 0:n.length)===0&&Array.isArray(t.messages)&&t.messages.length>0,c=r?i?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 Fs(e,t){const r=dd(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:vi(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 wi(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 i=e.find(c=>c.id===a.id);return i?Fs(a,i):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(t.map(i=>i.id));for(const i of e)a.has(i.id)||n.push(i)}return n}function lo(e){return!!e&&typeof e=="object"&&"text"in e}function ga(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(i=>typeof i=="string"?i:lo(i)?String(i.text||""):"").join(r):lo(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function ks(e){return ga(e,{normalizeWhitespace:!0})}const ji=o.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}),ki=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function uo(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 Si(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,i=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),i&&(n.serverVersion=i),u&&(n.versionUpdateReason=u),a&&i&&a===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||c&&a&&i&&a!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function md(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 mn(e){if(!e||typeof e!="object")return"";const t=e,r=md(ks(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 fd(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=mn(n);for(let i=0;i<a.length;i+=1)r^=a.charCodeAt(i),r=Math.imul(r,16777619)>>>0}return{count:e.length,hash:r.toString(16).padStart(8,"0"),first:mn(e[0]),last:mn(e[e.length-1])}}function Xn(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Jn(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(Xn(e)&&Xn(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)Jn(e[l],t[l],r);return}const n=e,a=t,i=new Set([...Object.keys(n),...Object.keys(a)]);for(const c of i)c!=="messages"&&Jn(n[c],a[c],r)}function zs(e,t){return Array.isArray(e)?e.map(r=>zs(r,t)):!e||typeof e!="object"?e:Xn(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?fd(a,t):zs(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,zs(n,t)]))}function pd(e,t){try{const r=new WeakSet;return Jn(e,t,r),JSON.stringify(zs(e,r))===JSON.stringify(zs(t,r))}catch{return!1}}function Qn(e,t,r){return pd(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Ni(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function hd(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function mo(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,i=wi(e.childSessions,t.childSessions,{preserveMissing:n}),c=vi(t.activeChat,e.activeChat);return Si(e,t,{...e,...t,chats:a,childSessions:i,activeChat:c,_lastUpdate:r})}function xd(e,t,r){var a,i;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=wi(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((i=e.chats)!=null&&i.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"])hd(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function bd(e,t,r,n){const a=xd(e,t,n),i=Object.keys(a).length>0?Si(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return Qn(e,i,r)}function gd(e){const t=new Set(e.map(i=>i.id)),r=new Set,n=new Set,a=new Set;for(const i of e){const c=Ni(i);c&&r.add(c),c&&i.type!=="adhdev-daemon"&&n.add(c),c&&i.type==="adhdev-daemon"&&i._sessionListAuthoritative&&a.add(c)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function yd(e,t,r,n,a,i){return!a.has(t)||!i.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function vd(e,t,r,n){return!!(r.has(t)&&e.transport&&!n.has(t))}function wd(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 i=new Map;for(const f of t)i.set(f.id,f);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:u,daemonIdsWithAuthoritativeSessionList:m}=gd(e);for(const f of e){const v=i.get(f.id);if(!v){i.set(f.id,{...f,_lastUpdate:n});continue}const S=uo(f),p=uo(v),x=Ni(f),y=!a.has(x);if(S>p){const M=mo(v,f,n,y);i.set(f.id,Qn(v,M,n));continue}if(S<p){i.set(f.id,bd(v,f,n,y));continue}const g=f.timestamp||n,N=v._lastUpdate||v.timestamp||0;if(g>=N){const M=mo(v,f,n,y);i.set(f.id,Qn(v,M,n));continue}(d=f.chats)!=null&&d.length&&!((h=v.chats)!=null&&h.length)&&i.set(f.id,{...v,chats:f.chats})}for(const[f,v]of i){const S=v.daemonId||f.split(":")[0];if(!l.has(S))continue;if(a.has(S)&&m.has(S)&&!c.has(f)){i.delete(f);continue}const p=n-(v._lastUpdate||v.timestamp||0);yd(v,S,p,c,a,u)&&i.delete(f)}for(const[f,v]of i){const S=v.daemonId||f.split(":")[0];if(vd(v,S,l,u))continue;n-(v._lastUpdate||v.timestamp||0)>3e5&&v.status!=="online"&&i.delete(f)}return Array.from(i.values())}function jd(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 kd({children:e,connectionOverrides:t}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[u,m]=o.useState(void 0),d=o.useRef(r);o.useEffect(()=>{d.current=r},[r]);const h=o.useCallback((y,g)=>{n(N=>{let M=!1;const w=N.map(I=>I.id!==y||I.chats===g?I:(M=!0,{...I,chats:g}));return M?w:N})},[]),f=o.useCallback((y,g)=>{n(N=>{const M=N.length===0?y:wd(y,N,g),w=!jd(N,M);return w&&js.record({kind:"dashboard.entries_applied",payload:{incoming:co(y),next:co(M)}}),w?M:N})},[]),v=o.useCallback(()=>i(!0),[]),S=o.useMemo(()=>({injectEntries:f,markLoaded:v,getIdes:()=>d.current}),[f,v]),p=t,x=o.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,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,u]);return s.jsx(ki.Provider,{value:S,children:s.jsx(ji.Provider,{value:x,children:e})})}function os(){return o.useContext(ji)}function Qs(){return o.useContext(ki)}function Ci(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function i(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 S=await fetch(h,{...u,headers:m,signal:f.signal});if(S.status===401)throw n==null||n(),new Error("Unauthorized");if(!S.ok){const p=await S.json().catch(()=>({error:S.statusText}));throw new Error(p.error||`API Error: ${S.status}`)}return S.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=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Sd=Ci({baseUrl:"http://localhost:3847"}),Nd=o.createContext(Sd);function Cd({client:e,children:t}){return s.jsx(Nd.Provider,{value:e,children:t})}const Td={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Ti=o.createContext(Td);function Md({value:e,children:t}){return s.jsx(Ti.Provider,{value:e,children:t})}function wt(){return o.useContext(Ti)}function Id(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 Ad(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Mi(e){return e?Id([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Ad(e.content)]):""}const De={size:18};function Ii({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 ya({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function is({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Ai({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Ld({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Rd({size:e=De.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 Li({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 _d({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Xr({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Ri({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Pd({size:e=De.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 Wt({size:e=De.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 St({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 va({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Dd({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Ss({size:e=De.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 nr({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function Zs({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 er({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 _i({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Pi({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Di({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Ed({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 wa({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 $d({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 ja({size:e=De.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 Ei({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function vt({size:e=De.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 Bd({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Kd({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Od({size:e=De.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 Wd({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Jr({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Hd({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Fd({size:e=De.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 Ud({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function zd({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Vd({size:e=De.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 Gd({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 qd({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Yd({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Xd({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Jd({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Qd({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 Zd({size:e=De.size,className:t}){return s.jsxs("svg",{width: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 $i=[Ql,{singleTilde:!1}],Bi=[$i,Zl,ed],eu=[$i],ka=200,tu=80,fo=650,Ps=new Map;function Br(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function su(e,t){if(!Array.isArray(e)||e.length===0)return"0:empty";const r=String(t||"").trim();if(r)return`${e.length}:${r}`;const n=e[e.length-1];return`${e.length}:${Mi(n)}`}function ru(e,t,r,n){return e||!t?!1:Br(r,n)}function nu({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=tu,bottomThresholdPx:a=ka}){const i=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:i>n,showBottom:Math.max(0,c-i-l)>a}}function au(e){return nu({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Us(e,t=ka){return!!e&&e.fromBottom>=t}function ou(e,t){return Br(e,t)?!Us(e):!0}function iu({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function cu({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function fn(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function Ki(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function lu(e,t,r){return Number(e.receivedAt||r[Kr(e,t)]||0)||0}function Oi(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function du(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function ur(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 pn(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 po(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Oi(e)?s.jsx(xa,{remarkPlugins:Bi,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function mr({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:po(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=pn(r);return a?s.jsx("img",{src:a,alt:ur(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=pn(r);return a?s.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=pn(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:ur(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||ur(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=ur(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}),po(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 Kr(e,t){const r=e,n=ga(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 uu=o.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(xa,{remarkPlugins:eu,children:t.text}),s.jsx("span",{className:"action-time",children:Ki(t.timestamp)})]})},(e,t)=>e.log===t.log),mu=o.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var I,k,j;const u=(t.role||"").toLowerCase(),m=u==="user"||u==="human",d=t.kind||(u==="tool"?"tool":"standard"),h=du(t.content)?t.content:null,f=!!(h!=null&&h.some(b=>b.type!=="text")),v=ga(t.content,{joiner:`
4
- `});if(d==="thought"){const b=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(Od,{size:13}),s.jsx("span",{children:b})]}),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(mr,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:v})]});if(d==="terminal"){const b=(k=t.meta)!=null&&k.isRunning?"⏳":"✅",B=typeof((j=t.meta)==null?void 0:j.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:b}),s.jsx("span",{children:B})]}),f&&h?s.jsx("div",{className:"chat-msg-body",children:s.jsx(mr,{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(mr,{parts:h,renderAsPreformatted:!1}):v.slice(0,100)});const S=t.meta,x=(typeof(S==null?void 0:S.renderMode)=="string"?S.renderMode.trim():"")==="preformatted",y=v,g=!1,N=y,M=x,w=!M&&Oi(N);return s.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${m?"self-end":"self-start"}`,children:(y||f||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${y||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:Ki(r)})]}),(y||f)&&s.jsx("div",{className:"chat-markdown",children:f&&h?s.jsx(mr,{parts:h,renderAsPreformatted:M}):M?s.jsx("pre",{className:"chat-preformatted",children:N}):w?s.jsx(xa,{remarkPlugins:Bi,children:N}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:N})}),g]})})},(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),fu=o.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},lastMessageHash:m,emptyState:d,onLoadMore:h,isLoadingMore:f,hasMoreHistory:v,hiddenLiveCount:S=0,loadError:p,scrollToBottomRequestNonce:x,isVisible:y=!0},g){const N=o.useRef(null),M=o.useRef(null),w=o.useRef(null),I=o.useRef(0),k=o.useRef(""),j=o.useRef(""),b=o.useRef(!1),B=o.useRef(null),R=o.useRef(!1),P=o.useRef(null),F=o.useRef(!1),[U,W]=o.useState(new Set),[T,L]=o.useState({showTop:!1,showBottom:!1}),z=o.useRef(!1),$=o.useRef(!1),E=o.useRef(y),V=o.useRef(y),q=o.useRef(null);V.current=y;const ve=()=>{const Y=N.current;return Y?Y.scrollHeight-Y.scrollTop-Y.clientHeight<ka:!0},ne=o.useCallback(()=>{const Y=N.current,X=Y?au(Y):{showTop:!1,showBottom:!1};L(le=>le.showTop===X.showTop&&le.showBottom===X.showBottom?le:X)},[]),pe=o.useCallback((Y="auto")=>{var le;const X=N.current;X&&(X.scrollTo({top:X.scrollHeight,behavior:Y}),(le=X.ownerDocument.defaultView)==null||le.requestAnimationFrame(()=>ne()))},[ne]),ie=o.useCallback((Y="auto")=>{var le;const X=N.current;X&&(X.scrollTo({top:0,behavior:Y}),(le=X.ownerDocument.defaultView)==null||le.requestAnimationFrame(()=>ne()))},[ne]),ge=o.useCallback(()=>{var oe;const Y=N.current,X=(oe=window.getSelection)==null?void 0:oe.call(window);if(!Y||!X||X.rangeCount===0||X.isCollapsed){F.current=!1;return}const le=X.anchorNode,D=X.focusNode;F.current=!!(le&&D&&Y.contains(le)&&Y.contains(D))},[]),be=su(t,m),H=o.useCallback(()=>{const Y=N.current;if(!Y||!l||!V.current)return;const X={top:Y.scrollTop,fromBottom:Math.max(0,Y.scrollHeight-Y.scrollTop-Y.clientHeight),messageFingerprint:be};q.current={contextKey:l,snapshot:X},Ps.set(l,X)},[l,be]),Q=o.useCallback((Y="auto")=>{B.current!=null&&cancelAnimationFrame(B.current),B.current=requestAnimationFrame(()=>{B.current=null,pe(Y)})},[pe]),re=o.useCallback(()=>{z.current=!1,R.current=!0,$.current=!0,P.current!=null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{R.current=!1,P.current=null},fo)},[]);o.useEffect(()=>{const Y=!b.current,X=j.current!==l;if(j.current=l,Y||X){b.current=!0;const D=l?Ps.get(l):null,oe=!!D&&Br(D,be);z.current=oe?Us(D):!1,R.current=ou(D,be),F.current||(oe?requestAnimationFrame(()=>{const J=N.current;J&&(fn(J,D),z.current=Us(D),ne(),$.current=!0)}):Q("auto")),I.current=t.length,k.current=be;return}t.length>I.current;const le=be!==k.current;iu({hasSelection:F.current,userScrolledUp:z.current,hasChatContentChanged:le})&&Q("auto"),I.current=t.length,k.current=be},[be,l,t.length,Q,ne]),o.useEffect(()=>{x&&(re(),F.current||Q("auto"))},[re,Q,x]),o.useEffect(()=>{V.current=y;const Y=E.current;E.current=y;const X=l?Ps.get(l):null;if(ru(Y,y,X,be)){if(!X)return;z.current=Us(X),R.current=!1,F.current||requestAnimationFrame(()=>{const le=N.current;le&&(fn(le,X),ne())});return}},[y,l,be,re,Q,ne]),o.useEffect(()=>()=>{const Y=q.current;Y&&Ps.set(Y.contextKey,Y.snapshot),B.current!=null&&cancelAnimationFrame(B.current),P.current!=null&&window.clearTimeout(P.current)},[]),o.useEffect(()=>{const Y=M.current,X=N.current;if(!Y||!X)return;const le=()=>{P.current!=null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{R.current=!1,P.current=null},fo)},D=new ResizeObserver(()=>{ne();const oe=R.current;cu({hasSelection:F.current,userScrolledUp:z.current,contextAutoScrollActive:oe})&&(Q("auto"),oe&&le())});return D.observe(Y),X!==Y&&D.observe(X),()=>{D.disconnect(),P.current!=null&&(window.clearTimeout(P.current),P.current=null)}},[Q,l,ne]),o.useImperativeHandle(g,()=>({scrollToBottom:(Y="smooth")=>{pe(Y)}}),[pe]),o.useEffect(()=>{const Y=N.current;if(!Y)return;let X;const le=()=>{H(),clearTimeout(X),X=setTimeout(()=>{z.current=!ve(),ne()},50)};return Y.addEventListener("scroll",le,{passive:!0}),()=>{Y.removeEventListener("scroll",le),clearTimeout(X)}},[H,ne]),o.useEffect(()=>(document.addEventListener("selectionchange",ge),()=>document.removeEventListener("selectionchange",ge)),[ge]);const he=o.useRef(0),ue=o.useRef(!1);o.useEffect(()=>{const Y=N.current;if(!Y||!ue.current||he.current===0)return;const X=Y.scrollHeight-he.current;X>0&&(Y.scrollTop=X),ne(),H(),he.current=0,ue.current=!1},[t.length,H,ne]),o.useEffect(()=>{if($.current||!l)return;const Y=Ps.get(l),X=N.current;if(!(!Y||!X)){if(!Br(Y,be)){pe("auto"),$.current=!0;return}fn(X,Y),z.current=Us(Y),ne(),$.current=!0}},[l,be,t.length,pe,ne]);const je=()=>{const Y=N.current;Y&&(he.current=Y.scrollHeight),ue.current=!0,h==null||h()},ce=()=>{z.current=!0,ie("smooth"),H()},xe=()=>{re(),pe("smooth"),H()},Z=o.useMemo(()=>{const Y=t.map((oe,J)=>({type:"message",data:oe,index:J,ts:lu(oe,J,u)}));if(!r||r.length===0)return Y;const X=[...r].sort((oe,J)=>oe.timestamp-J.timestamp).map((oe,J)=>({type:"action",data:oe,index:J,ts:oe.timestamp})),le=[];let D=0;for(const oe of Y){for(;D<X.length&&oe.ts>0&&X[D].ts<oe.ts;)le.push(X[D++]);le.push(oe)}for(;D<X.length;)le.push(X[D++]);return le},[t,r,u]),ae=S>0||!!v,te=S>0?`↑ Show ${Math.min(S,80)} earlier messages${S>80?` (${S} hidden)`:""}`:p?`↻ ${p}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:N,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:M,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..."}),ae&&!f&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{onClick:je,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${p&&S===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:te})}),Z.length===0&&!ae&&(d||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),Z.map(Y=>{if(Y.type==="action"){const Ne=Y.data;return s.jsx(uu,{log:Ne},`action-${Y.index}`)}const X=Y.data,le=Y.index,D=Kr(X,le),oe=X.receivedAt||u[D],J=`${l}-${D}`,we=U.has(J);return s.jsx(mu,{message:X,receivedAt:oe,agentName:n,userName:a,isCliMode:i,isTextExpanded:we,onToggleTextExpanded:()=>W(Ne=>{const Ae=new Set(Ne);return we?Ae.delete(J):Ae.add(J),Ae})},`msg-${D}`)}),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:w})]})}),(T.showTop||T.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[T.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:ce,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),T.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:xe,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),pu=o.memo(fu,(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),hu="modulepreload",xu=function(e){return"/"+e},ho={},bu=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=xu(u),u in ho)return;ho[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":hu,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 i(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"&&i(l.reason);return t().catch(i)})};let xo=!1;const Wi=o.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:i="measured"},c)=>{const l=o.useRef(null),[u,m]=o.useState(null),d=o.useRef([]),h=o.useRef(!1),f=o.useRef(!1),v=o.useRef(!1),S=o.useRef(!1),p=()=>{const x=l.current;if(x){h.current&&(x.clear(),h.current=!1);for(const y of d.current)x.write(y.data,y.onProcessed);d.current=[],f.current&&(x.fit(),f.current=!1),v.current&&(x.bumpResize(),v.current=!1),S.current&&(x.scrollToTop(),S.current=!1)}};return o.useImperativeHandle(c,()=>({write:(x,y)=>{l.current?l.current.write(x,y):d.current.push({data:x,onProcessed:y})},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:(x,y)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(x,y)},fit:()=>{l.current?l.current.fit():f.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():v.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():S.current=!0},getSelection:()=>{var x,y;return((y=(x=l.current)==null?void 0:x.getSelection)==null?void 0:y.call(x))||""},getVisibleText:()=>{var x,y;return((y=(x=l.current)==null?void 0:x.getVisibleText)==null?void 0:y.call(x))||""}}),[]),o.useEffect(()=>{u&&p()},[u]),o.useEffect(()=>{let x=!1;return bu(()=>import("./terminal-DbJP_JGY.js"),__vite__mapDeps([0,1,2])).then(y=>{xo||(xo=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),x||m(()=>y.GhosttyTerminalView)}).catch(y=>{console.error("[CliTerminal] failed to load terminal renderer",y)}),()=>{x=!0}},[]),u?s.jsx(u,{ref:l,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:i,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"}})});Wi.displayName="CliTerminal";function fr({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 bo({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:i=!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 i?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 gu({cursorPos:e,viewportRef:t,imgRef:r}){var g;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(g=t.current)==null?void 0:g.getBoundingClientRect();if(!i)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 S=a.left-i.left+f+d*e.nx,p=a.top-i.top+v+h*e.ny,x=Math.max(8,Math.min(i.width-8,S)),y=Math.max(8,Math.min(i.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:x-8,top:y-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 yu({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:m,zoom:d,isMobile:h,mobileFillZoom:f,onZoomOut:v,onZoomReset:S,onZoomIn:p,transportType:x,screenshotUsage:y,lastActionStatus:g}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:N=>N.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(N=>!N),i(!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:N=>N.stopPropagation(),onChange:N=>l(N.target.value),onKeyDown:N=>{u(N)},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:()=>{i(N=>!N),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),"%"]}),x==="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"}),x==="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"}),y&&y.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:y.budgetExhausted?"TURN blocked":`TURN ${y.dailyUsedMinutes}/${y.dailyBudgetMinutes}m`}),g&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:g})]})]}),a&&s.jsxs("div",{onTouchStart:N=>N.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:N=>{N.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:N=>{N.stopPropagation(),S()},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:N=>{N.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 vu({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 wu(){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 go(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 ar(e,t){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!wu())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,go(l)]))}),r.current=t;return}const i=Object.keys({...a,...t}).filter(c=>!Object.is(a[c],t[c]));i.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(c=>[c,go(t[c])]))}),r.current=t})}function ju({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:m,setPanY:d,setZoom:h,lastWheelTimeRef:f,onAction:v,setLastActionStatus:S,spawnRippleFromNormalized:p,clampPan:x,isMobile:y,mobileFillZoom:g}){const[N,M]=o.useState(null),w=o.useRef(null),I=o.useRef(null),k=o.useRef(null),j=o.useRef(!1),b=o.useRef(null),B=o.useRef(0),R=o.useRef(null),P=o.useRef(1),F=o.useRef({x:0,y:0}),U=o.useRef(!1),W=o.useRef(n),T=o.useRef(v),L=30,z=550,$=18,E=60,V=400,q=12,ve=()=>{if(w.current)return;const ie={nx:.5,ny:.5};w.current=ie,M(ie)};return o.useEffect(()=>{W.current=n,n==="mouse"&&ve()},[n]),o.useEffect(()=>{T.current=v},[v]),o.useEffect(()=>{const ie=e.current;if(!ie)return;const ge=ue=>{if(!r.current)return null;const je=r.current.getBoundingClientRect();return!je.width||!je.height?null:{nx:Math.max(0,Math.min(1,(ue.clientX-je.left)/je.width)),ny:Math.max(0,Math.min(1,(ue.clientY-je.top)/je.height))}},be=(ue,je)=>{if(!r.current)return{dnx:0,dny:0};const ce=r.current,xe=ce.getBoundingClientRect(),Z=ce.naturalWidth||xe.width,ae=ce.naturalHeight||xe.height,te=Z/ae,Y=xe.width/xe.height;let X,le;return te>Y?(X=xe.width,le=xe.width/te):(le=xe.height,X=xe.height*te),{dnx:ue/X,dny:je/le}},H=(ue,je,ce)=>{if(ce<=1.05)return;const xe=-(ue-.5)*100,Z=-(je-.5)*100,ae=x(xe,Z,ce);(Math.abs(ae.x-l.current)>.1||Math.abs(ae.y-u.current)>.1)&&(m(ae.x),d(ae.y),l.current=ae.x,u.current=ae.y)},Q=ue=>{const je=t.current;if(je&&ue.target instanceof Node&&je.contains(ue.target))ue.preventDefault();else return;if(ue.touches.length===1){const ce=ue.touches[0];I.current={x:ce.clientX,y:ce.clientY,time:Date.now()},k.current={x:ce.clientX,y:ce.clientY},U.current||(j.current=!1),b.current=setTimeout(()=>{if(!j.current&&!U.current)if(j.current=!0,W.current==="mouse"){const xe=w.current||{nx:.5,ny:.5};S("Right Click"),p(xe.nx,xe.ny,"right"),T.current("input_click",{...xe,button:"right"}).catch(()=>{})}else{const xe=ge(ce);xe&&(S("Right Click"),p(xe.nx,xe.ny,"right"),T.current("input_click",{...xe,button:"right"}).catch(()=>{}))}},500);return}if(ue.touches.length===2){b.current&&clearTimeout(b.current),j.current=!0,U.current=!0;const ce=ue.touches[1].clientX-ue.touches[0].clientX,xe=ue.touches[1].clientY-ue.touches[0].clientY;R.current=Math.sqrt(ce*ce+xe*xe),P.current=c.current,F.current={x:(ue.touches[0].clientX+ue.touches[1].clientX)/2,y:(ue.touches[0].clientY+ue.touches[1].clientY)/2}}},re=ue=>{const je=t.current;if(je&&ue.target instanceof Node&&je.contains(ue.target)&&ue.preventDefault(),ue.touches.length===1&&k.current){const ce=ue.touches[0],xe=ce.clientX-k.current.x,Z=ce.clientY-k.current.y;if(!j.current&&I.current){const ae=ce.clientX-I.current.x,te=ce.clientY-I.current.y;Math.sqrt(ae*ae+te*te)>8&&(j.current=!0,b.current&&clearTimeout(b.current))}if(j.current)if(W.current==="mouse"){const ae=be(xe,Z),te=w.current||{nx:.5,ny:.5},Y=Math.max(0,Math.min(1,te.nx+ae.dnx)),X=Math.max(0,Math.min(1,te.ny+ae.dny));w.current={nx:Y,ny:X},M({nx:Y,ny:X}),S(`Cursor: ${Math.round(Y*100)}%, ${Math.round(X*100)}%`),H(Y,X,c.current);const le=Date.now();le-f.current>=30&&(f.current=le,T.current("input_mouseMoved",{nx:Y,ny:X}).catch(()=>{}))}else if(c.current>1){const ae=t.current;if(ae){const te=ae.clientWidth,Y=ae.clientHeight,X=l.current+xe/te*100,le=u.current+Z/Y*100,D=x(X,le,c.current);m(D.x),d(D.y),l.current=D.x,u.current=D.y}}else{const ae=ge(ce);if(ae){const te=Date.now();te-f.current>=40&&(f.current=te,S("Scroll"),T.current("input_wheel",{nx:ae.nx,ny:ae.ny,deltaX:Math.round(-xe*2.5),deltaY:Math.round(-Z*2.5)}).catch(()=>{}))}}k.current={x:ce.clientX,y:ce.clientY};return}if(ue.touches.length===2&&R.current!==null){const ce=ue.touches[1].clientX-ue.touches[0].clientX,xe=ue.touches[1].clientY-ue.touches[0].clientY,ae=Math.sqrt(ce*ce+xe*xe)/R.current,te=(ue.touches[0].clientX+ue.touches[1].clientX)/2,Y=(ue.touches[0].clientY+ue.touches[1].clientY)/2,X=te-F.current.x,le=Y-F.current.y,D=Math.abs(ae-1)>.03;if(W.current==="mouse"){if(D){const oe=Math.max(i,Math.min(5,P.current*ae));h(oe),c.current=oe}else if(Math.abs(X)>2||Math.abs(le)>2){const oe=w.current||{nx:.5,ny:.5},J=Date.now();J-f.current>=30&&(f.current=J,S("Scroll"),T.current("input_wheel",{nx:oe.nx,ny:oe.ny,deltaX:Math.round(-X*3),deltaY:Math.round(-le*3)}).catch(()=>{}))}}else{const oe=Math.max(i,Math.min(5,P.current*ae));h(oe),c.current=oe;const J=t.current;if(J&&oe>1){const we=J.clientWidth,Ne=J.clientHeight,Ae=l.current+X/we*100,Me=u.current+le/Ne*100,Ue=x(Ae,Me,oe);m(Ue.x),d(Ue.y),l.current=Ue.x,u.current=Ue.y}}F.current={x:te,y:Y}}},he=ue=>{var je;if(b.current&&clearTimeout(b.current),R.current=null,ue.touches.length===1&&U.current){const ce=ue.touches[0];I.current={x:ce.clientX,y:ce.clientY,time:Date.now()},k.current={x:ce.clientX,y:ce.clientY},j.current=!0;return}if(ue.touches.length===0){if(U.current){U.current=!1,j.current=!1;return}if(ue.changedTouches.length===1){const ce=ue.changedTouches[0],xe=Date.now(),Z=xe-(((je=I.current)==null?void 0:je.time)||0),ae=I.current?ce.clientX-I.current.x:0,te=I.current?ce.clientY-I.current.y:0,Y=Math.sqrt(ae*ae+te*te);if(W.current==="mouse"){if(Z<L||Z>z||Y>$){j.current=!1;return}const X=w.current||ge(ce);X&&(S(`Click: ${Math.round(X.nx*100)}%, ${Math.round(X.ny*100)}%`),p(X.nx,X.ny,"left"),T.current("input_click",{...X}).catch(()=>{}))}else{if(j.current){j.current=!1;return}if(Z<E||Z>V||Y>q){j.current=!1;return}const X=ge(ce);if(!X)return;xe-B.current<300?(S("Double tap"),p(X.nx,X.ny,"double"),T.current("input_click",{...X,clickCount:2}).catch(()=>{}),B.current=0):(S(`Tap: ${Math.round(X.nx*100)}%, ${Math.round(X.ny*100)}%`),p(X.nx,X.ny,"left"),T.current("input_click",{...X}).catch(()=>{}),B.current=xe)}}j.current=!1}};return ie.addEventListener("touchstart",Q,{passive:!1}),ie.addEventListener("touchmove",re,{passive:!1}),ie.addEventListener("touchend",he,{passive:!1}),()=>{ie.removeEventListener("touchstart",Q),ie.removeEventListener("touchmove",re),ie.removeEventListener("touchend",he),b.current&&clearTimeout(b.current)}},[e,t,r,i,c,l,u,m,d,h,f,S,p,x]),{cursorPos:N,cursorPosRef:w,handleToggleInputMode:()=>{a(ie=>{const ge=ie==="touch"?"mouse":"touch";return ge==="mouse"&&ve(),ge})},handleZoomReset:()=>{const ie=y?g:1;h(ie),c.current=ie,m(0),d(0),l.current=0,u.current=0}}}function Hi({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),u=o.useRef(null),[m,d]=o.useState(null),[h,f]=o.useState(""),[,v]=o.useState(!1),[S,p]=o.useState([]),x=o.useRef(0),[y,g]=o.useState(!1),[N,M]=o.useState(!1),w=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[I,k]=o.useState(w?"mouse":"touch"),[j,b]=o.useState(1),B=o.useRef(!1),[R,P]=o.useState(1),[F,U]=o.useState(0),[W,T]=o.useState(0);ar("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:I,zoom:R,panX:F,panY:W,isMenuOpen:y,isImeOpen:N});const L=o.useRef(0),z=o.useRef(R),$=o.useRef(F),E=o.useRef(W);o.useEffect(()=>{z.current=R},[R]),o.useEffect(()=>{$.current=F},[F]),o.useEffect(()=>{E.current=W},[W]),o.useEffect(()=>{var Z;(Z=c.current)==null||Z.focus()},[]);const V=r==="connected",q=n,ve=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";o.useEffect(()=>{if(!w||B.current||!q)return;const Z=u.current,ae=l.current;if(!Z||!ae)return;const te=()=>{const Y=ae.clientWidth,X=ae.clientHeight,le=Z.naturalWidth,D=Z.naturalHeight;if(!le||!D||!Y||!X)return;const oe=Math.min(Y/le,X/D),we=Math.max(Y/le,X/D)/oe;we>1.01&&(b(we),P(we),z.current=we),B.current=!0};Z.complete&&Z.naturalWidth?te():Z.addEventListener("load",te,{once:!0})},[q,w]);const pe=.5;o.useEffect(()=>{R<=pe&&(U(0),T(0))},[R,pe]);const ie=(Z,ae,te)=>{if(te<=pe)return{x:0,y:0};const Y=(te-1)/(2*te)*100,X=(te-1)/(2*te)*100;return{x:Math.max(-Y,Math.min(Y,Z)),y:Math.max(-X,Math.min(X,ae))}},ge=(Z,ae)=>{if(!u.current)return null;const te=u.current.getBoundingClientRect();return!te.width||!te.height?null:{nx:Math.max(0,Math.min(1,(Z-te.left)/te.width)),ny:Math.max(0,Math.min(1,(ae-te.top)/te.height))}},be=(Z,ae,te)=>{const Y=l.current;if(!Y)return;const X=Y.getBoundingClientRect(),le=++x.current;p(D=>[...D,{id:le,x:Z-X.left,y:ae-X.top,type:te}]),setTimeout(()=>p(D=>D.filter(oe=>oe.id!==le)),600)},H=(Z,ae,te)=>{const Y=u.current,X=l.current;if(!Y||!X)return;const le=Y.getBoundingClientRect(),D=X.getBoundingClientRect(),oe=Y.naturalWidth||le.width,J=Y.naturalHeight||le.height,we=oe/J,Ne=le.width/le.height;let Ae,Me,Ue,We;we>Ne?(Ae=le.width,Me=le.width/we,Ue=0,We=(le.height-Me)/2):(Me=le.height,Ae=le.height*we,Ue=(le.width-Ae)/2,We=0);const Be=le.left-D.left+Ue+Ae*Z,Ye=le.top-D.top+We+Me*ae,Xe=++x.current;p(Je=>[...Je,{id:Xe,x:Be,y:Ye,type:te}]),setTimeout(()=>p(Je=>Je.filter(Ve=>Ve.id!==Xe)),600)},Q=async Z=>{var te;const ae=ge(Z.clientX,Z.clientY);if(ae){d(`Click: ${Math.round(ae.nx*100)}%, ${Math.round(ae.ny*100)}%`),be(Z.clientX,Z.clientY,"left"),(te=c.current)==null||te.focus();try{const Y=await e("input_click",{nx:ae.nx,ny:ae.ny});Y!=null&&Y.success||t(`❌ Click failed: ${Y==null?void 0:Y.error}`)}catch(Y){t(`❌ Click error: ${Y.message||Y}`)}}},re=async(Z,ae,te,Y=0)=>{try{await e("input_key",{type:te?"char":"keyDown",key:Z,code:ae,text:te?Z:void 0,unmodifiedText:te?Z:void 0,modifiers:Y})}catch(X){t(`❌ Key error: ${X.message||X}`)}},he=async Z=>{if(Z.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(Z.key)&&Z.preventDefault();let te=0;Z.altKey&&(te|=1),Z.ctrlKey&&(te|=2),Z.metaKey&&(te|=4),Z.shiftKey&&(te|=8),d(`Key: ${Z.key}`),await re(Z.key,Z.code,Z.key.length===1,te)},ue=async Z=>{if(Z.key==="Enter"){if(Z.nativeEvent.isComposing)return;if(h){const ae=h;f(""),d(`IME Sent: ${ae}`);try{const te=await e("input_type",{text:ae});te!=null&&te.success||t(`❌ IME error: ${te==null?void 0:te.error}`)}catch(te){t(`❌ IME error: ${te.message}`)}}else d("Key: Enter"),await re("Enter","Enter",!1)}};o.useEffect(()=>{const Z=c.current;if(!Z)return;const ae=te=>{var Y;if((Y=u.current)!=null&&Y.contains(te.target)){te.preventDefault();const X=Date.now();if(X-L.current<40)return;L.current=X;const le=ge(te.clientX,te.clientY);if(!le)return;d(`Scroll: ${Math.round(te.deltaY)}`),e("input_wheel",{nx:le.nx,ny:le.ny,deltaX:Math.round(te.deltaX),deltaY:Math.round(te.deltaY)}).catch(()=>{})}};return Z.addEventListener("wheel",ae,{passive:!1}),()=>Z.removeEventListener("wheel",ae)},[e]);const{cursorPos:je,handleToggleInputMode:ce,handleZoomReset:xe}=ju({containerRef:c,viewportRef:l,imgRef:u,inputMode:I,setInputMode:k,minZoom:pe,zoomRef:z,panXRef:$,panYRef:E,setPanX:U,setPanY:T,setZoom:P,lastWheelTimeRef:L,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:H,clampPan:ie,isMobile:w,mobileFillZoom:j});return s.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:he,onContextMenu:Z=>Z.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:[q?s.jsx("img",{ref:u,src:q,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${R}) translate(${F}%, ${W}%)`,transformOrigin:"center center",cursor:I==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:Q,onContextMenu:Z=>Z.preventDefault(),onDragStart:Z=>Z.preventDefault()}):s.jsx(vu,{waitingLabel:ve,waitingHint:ne,transportType:i}),I==="mouse"&&q&&s.jsx(gu,{cursorPos:je,viewportRef:l,imgRef:u}),S.map(Z=>{const te={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[Z.type];return s.jsxs("div",{style:{position:"absolute",left:Z.x,top:Z.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${te}, 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(${te}, 0.9)`,boxShadow:`0 0 12px rgba(${te}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},Z.id)})]}),s.jsx(yu,{inputMode:I,onToggleInputMode:ce,isImeOpen:N,setIsImeOpen:M,isMenuOpen:y,setIsMenuOpen:g,imeText:h,setImeText:f,handleImeSubmit:ue,isConnActive:V,zoom:R,isMobile:w,mobileFillZoom:j,onZoomOut:()=>P(Z=>Math.max(.5,Z-.25)),onZoomReset:xe,onZoomIn:()=>P(Z=>Math.min(5,Z+.25)),transportType:i,screenshotUsage:a,lastActionStatus:m}),s.jsx("style",{children:`
5
- @keyframes slideUp {
6
- from { opacity: 0; transform: translateY(6px); }
7
- to { opacity: 1; transform: translateY(0); }
8
- }
9
- @keyframes slideUpSidebar {
10
- from { opacity: 0; transform: translateY(6px); }
11
- to { opacity: 1; transform: translateY(0); }
12
- }
13
- @keyframes click-ripple-ring {
14
- 0% { transform: scale(0.3); opacity: 1; }
15
- 100% { transform: scale(2.2); opacity: 0; }
16
- }
17
- @keyframes click-ripple-dot {
18
- 0% { transform: scale(1); opacity: 0.9; }
19
- 50% { transform: scale(1.8); opacity: 0.6; }
20
- 100% { transform: scale(0.5); opacity: 0; }
21
- }
22
- @keyframes remote-float {
23
- 0% { transform: translateY(0px); }
24
- 50% { transform: translateY(-7px); }
25
- 100% { transform: translateY(0px); }
26
- }
27
- `})]})}function Qr(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,i=Date.now()-e,c=Math.floor(i/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 Fi=e=>Qr(e);function ku(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 As(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 Su(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...ku(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 Or(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 Zr(e,t,r){const n=Or(e,t),a=As(e),i=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:i,isConnecting:c,isGenerating:l,isWaiting:u,inboxBucket:m?"needs_attention":d?"working":f?"task_complete":"idle"}}function Nu(e,t,r){return Zr(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Ui({activeConv:e,onModalButton:t}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!As(e).isWaiting||!e.modalButtons)return null;const i=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(Zs,{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:()=>i(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 Sa="adhdev_controls_bar_visible",Zn="adhdev:controlsbarvisibilitychange";function hn(e){if(!e)return!1;try{return e.getItem(Sa)==="1"}catch{return!1}}function yo(e,t){if(t)try{t.setItem(Sa,e?"1":"0")}catch{}}function vo(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Zn,{detail:{visible:e}}))}function zi(){const[e,t]=o.useState(()=>typeof window>"u"?!1:hn(window.localStorage));o.useEffect(()=>{const a=c=>{const l=c.detail;if(typeof(l==null?void 0:l.visible)=="boolean"){t(l.visible);return}t(hn(window.localStorage))},i=c=>{c.key===Sa&&t(hn(window.localStorage))};return window.addEventListener(Zn,a),window.addEventListener("storage",i),()=>{window.removeEventListener(Zn,a),window.removeEventListener("storage",i)}},[]);const r=o.useCallback(a=>{t(a),typeof window<"u"&&yo(a,window.localStorage),vo(a)},[]),n=o.useCallback(()=>{t(a=>{const i=!a;return typeof window<"u"&&yo(i,window.localStorage),vo(i),i})},[]);return{isVisible:e,setVisibility:r,toggleVisibility:n}}var Cu=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Tu(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function bt(e,t){if(Tu(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Cu.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 Vi(e){return bt(e)==="generating"}function rt(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Mu(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),i=r%24;return`${a}d ${i}h`}function xn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function en(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(/[\\/]+$/,""),i=a.split(/[\\/]/).filter(Boolean);return i[i.length-1]||a}function Iu(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 Au(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Lu(e){return Iu(e.trim().replace(/\.local$/i,""))}function Ru(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function Gi(e,t={}){var a,i;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(i=e.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!Au(c));if(r&&r!=="Unknown")return Lu(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Tt(e,t={}){return Ru(e)||Gi(e,t)}function qi(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 Yi(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function cs(e,t){return qi(e).join(" · ")}function tr(e){return e.transport==="pty"}function gs(e){return e.transport==="acp"}function _u(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:rt(e)}function wo(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=rt(r||"").trim().toLowerCase();return n===a||n===i||n===c}function Pu(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Du(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,"-"),i=t.get(a),c=bt(n.status);if(!i){t.set(a,{...n,status:c});continue}const l=r.indexOf(i.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 Eu(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 $u(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&&Eu(t.receivedAt)||0}function Bu(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ea(e){return Math.max(Bu(e),$u(e.activeChat))}function Ku(e,t,r,n,a,i){const c=t-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(i)}function Na(e,t){return Ku(ea(e),ea(t),Tt(e,{fallbackId:e.id}),Tt(t,{fallbackId:t.id}),e.id,t.id)}const Xi="adhdev_notification_prefs",jo={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Ou(){try{const e=localStorage.getItem(Xi);if(e){const t=JSON.parse(e);return{...jo,...t}}}catch{}return{...jo}}function Wu(e){try{localStorage.setItem(Xi,JSON.stringify(e))}catch{}}let Kt=Ou(),Tr=[];function Hu(){Tr.forEach(e=>e())}function Fu(e){Kt={...Kt,...e},Wu(Kt),Hu()}function Uu(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Tr.push(r),()=>{Tr=Tr.filter(n=>n!==r)}},[]);const t=o.useCallback(r=>{Fu(r)},[]);return[{...Kt},t]}function Vs(e){if(!Kt.globalEnabled)return!1;switch(e){case"disconnect":return Kt.disconnectAlert;case"completion":return Kt.completionAlert;case"approval":return Kt.approvalAlert;case"browser":return Kt.browserNotifications;default:return!0}}const zu={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Ji(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Qi(){return"Notification"in window&&Notification.permission==="granted"}let qt=null;function Vu(e){return e!==!1}async function Gu(){if(qt!==null)return qt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return qt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(qt=!!await e.pushManager.getSubscription(),qt):(qt=!1,!1)}catch{return qt=!1,!1}}function ta(e,t,r){if(Qi())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 qu(e,t={}){const r={...zu,...t},n=o.useRef(new Map),a=o.useRef(0),[i,c]=o.useState(null);o.useEffect(()=>{let u=!1;return Gu().then(m=>{u||c(m)}),()=>{u=!0}},[]);const l=o.useCallback((u,m,d)=>{const h=Date.now();h-a.current<r.throttleMs||(a.current=h,ta(u,m,d))},[r.throttleMs]);o.useEffect(()=>{var u;if(!(!r.enabled||!Qi())&&Vs("browser")&&!Vu(i)){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&&Vs("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&&Vs("completion")&&Vi(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,i,l])}const Yu=/^(run|approve|accept|yes|allow|always)/,Xu=/^(run|approve|accept|yes|allow|always|proceed|save)/,Ju=/^(reject|deny|delete|remove|abort|cancel|no)/;function Ca(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Qu(e){const t=Ca(e).toLowerCase();return Yu.test(t)?"primary":Ju.test(t)?"danger":"default"}function Zu(e){return Xu.test(Ca(e).toLowerCase())?"approve":"reject"}function em(e){return e.map((t,r)=>({label:Ca(t),variant:Qu(t),action:Zu(t),button:t,buttonIndex:r}))}function tm(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function sm(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 rm{constructor(){ze(this,"dedupMap",new Map);ze(this,"DEDUP_WINDOW_MS",5e3);ze(this,"DEDUP_MAX_SIZE",50);ze(this,"DEDUP_CLEANUP_AGE_MS",1e4);ze(this,"toastCallbacks",[]);ze(this,"resolveActionFn",null);ze(this,"viewRequestRespondFn",null);ze(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,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(i=>i.id===t.daemonId&&i.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 i=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(i)return i}}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 S;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),i=n||t.daemonId||"",c=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),l=`${i}:${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=rt(m);const h=this.resolveOwningDaemon(t);if(h){const p=Tt(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",(S=t.modalButtons)!=null&&S.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const x=this.resolveActionFn,y=em(t.modalButtons).map(M=>({label:M.label,variant:M.variant,onClick:()=>{x(p,"resolve_action",{action:M.action,button:M.button,buttonIndex:M.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),g=tm(d,t.modalMessage,f),N=Date.now();this.emitToast({id:N,message:g,type:v,timestamp:N,targetKey:n||p,actions:y,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",Vs("browser")&&!document.hasFocus()&&ta(`⚠️ ${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",x=t.requestId,y=t.orgId;if(f=`👁️ ${p} wants to view your session`,v="warning",x&&y&&this.viewRequestRespondFn){const g=Date.now(),N=sm(y,x,this.viewRequestRespondFn,(M,w)=>console.error(`[EventManager] ${M} view request failed:`,w));this.emitToast({id:g,message:f,type:v,timestamp:g,actions:N,duration:3e4}),f=""}Vs("browser")&&!document.hasFocus()&&ta("👁️ View Request",`${p} wants to view your session`,`view-request-${x}`)}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 it=new rm,ko=new Map;function Wr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ys(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function tn(e){return Wr(e)?Wr(e.result)?e.result:e:null}function nm(e){const t=tn(e);return!t||!Wr(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function pr(e){const t=tn(e);return!t||!Wr(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Ds(e){const t=tn(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function hr(e){const t=tn(e);return!!t&&t.success===!1}function am(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";it.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";it.showToast(n.notification.body,a)}}}function om(e,t){return e&&ys(e.currentValue)?e.currentValue:t}function im(e,t){return ys(t)?ys(e)?typeof e=="string"&&e.trim()==="":!0:!1}function cm(e,t){var i,c;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(ys(l))return l}const n=(i=t.controlValues)==null?void 0:i[e];if(ys(n))return n;const a=(c=t.defaultValues)==null?void 0:c[e];return ys(a)?a:void 0}function Mr(e,t){return e.options||t[e.id]||[]}const lm={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 dm(e,t,r){var n;return((n=lm[t])==null?void 0:n.has(r.id))===!0}function Ta(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!dm(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function bn(e,t){return{value:t}}function um(e,t,r){var a;return r?((a=Mr(e,t).find(i=>i.value===r))==null?void 0:a.label)||r:""}const mm={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function fm({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=wt(),u=`${e}:${t||n}`,m=mm[n]||"#94a3b8",[d,h]=o.useState({}),f=o.useRef({}),v=o.useRef(c);f.current=d,v.current=c;const S=o.useRef(0),p={};for(const L of i||[])L.defaultValue!==void 0&&(p[L.id]=L.defaultValue);const x={...p,...c||{},...Date.now()<S.current?d:{}};o.useEffect(()=>{c&&Date.now()>S.current&&h({})},[c]);const[y,g]=o.useState(ko.get(u)||{}),[N,M]=o.useState(null),[w,I]=o.useState(null),k=o.useCallback(async(L,z={})=>{const $={...z,...t&&{targetSessionId:t}};return await l(e,L,$)},[e,t,l]),j=o.useCallback(async(L,z={})=>{const $=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await k("invoke_provider_script",{...$,scriptName:L,...z})},[k,n,r,t]),b=o.useCallback((L,z,$)=>{const E=om($,z);h(V=>({...V,[L.id]:E})),am($==null?void 0:$.effects)},[]),B=o.useCallback((L,z)=>{h($=>{const E={...$};return z===void 0?delete E[L.id]:E[L.id]=z,E}),S.current=0},[]);if(!i||i.length===0)return null;const R=Ta(i,{hostIdeType:r,providerType:n});if(R.length===0)return null;const P=async L=>{if(N===L.id){M(null);return}if(Mr(L,y).length>0){M(L.id);return}if(L.dynamic&&L.listScript){I(L.id);try{const $=await j(L.listScript,{}),E=nm($);if(!E){const ve=Ds($);ve&&it.showToast(ve,"warning");return}const V=E.options;g(ve=>{const ne={...ve,[L.id]:V};return ko.set(u,ne),ne});const q=cm(L.id,{localOverrideUntil:S.current,localValues:f.current,controlValues:v.current,defaultValues:p});if(im(q,E.currentValue)){const ve=E.currentValue;h(ne=>({...ne,[L.id]:ve}))}M(L.id)}catch($){const E=$ instanceof Error?$.message:`Could not load ${L.label}`;it.showToast(E,"warning")}finally{I(null)}}},F=async(L,z)=>{M(null);const $=(c==null?void 0:c[L.id])??p[L.id];h(E=>({...E,[L.id]:z})),S.current=Date.now()+5e3;try{if(!L.setScript)return;const E=await j(L.setScript,bn(L,z)),V=pr(E);if(V&&!V.ok||hr(E))throw new Error((V==null?void 0:V.error)||Ds(E)||`Could not update ${L.label}`);b(L,z,V)}catch(E){B(L,$);const V=E instanceof Error?E.message:`Could not update ${L.label}`;it.showToast(V,"warning")}},U=async L=>{const z=Mr(L,y).map(ne=>ne.value);if(z.length===0)return;const $=String(x[L.id]||""),V=(z.indexOf($)+1)%z.length,q=z[V];if(typeof q!="string")return;const ve=(c==null?void 0:c[L.id])??p[L.id];h(ne=>({...ne,[L.id]:q})),S.current=Date.now()+5e3;try{if(!L.setScript)return;const ne=await j(L.setScript,bn(L,q)),pe=pr(ne);if(pe&&!pe.ok||hr(ne))throw new Error((pe==null?void 0:pe.error)||Ds(ne)||`Could not update ${L.label}`);b(L,q,pe)}catch(ne){B(L,ve);const pe=ne instanceof Error?ne.message:`Could not update ${L.label}`;it.showToast(pe,"warning")}},W=async L=>{const $=!x[L.id],E=(c==null?void 0:c[L.id])??p[L.id];h(V=>({...V,[L.id]:$})),S.current=Date.now()+5e3;try{if(!L.setScript)return;const V=await j(L.setScript,bn(L,$)),q=pr(V);if(q&&!q.ok||hr(V))throw new Error((q==null?void 0:q.error)||Ds(V)||`Could not update ${L.label}`);b(L,$,q)}catch(V){B(L,E);const q=V instanceof Error?V.message:`Could not update ${L.label}`;it.showToast(q,"warning")}},T=async L=>{if(!L.invokeScript)return;if(L.confirmMessage){const $=[L.confirmTitle,L.confirmMessage,L.confirmLabel].filter(V=>typeof V=="string"&&V.trim().length>0);if(!window.confirm($.join(`
28
-
29
- `)))return}const z=(c==null?void 0:c[L.id])??p[L.id];try{const $=await j(L.invokeScript),E=pr($);if(E&&!E.ok||hr($))throw new Error((E==null?void 0:E.error)||Ds($)||`Could not run ${L.label}`);E&&b(L,z??!0,E)}catch($){B(L,z);const E=$ instanceof Error?$.message:`Could not run ${L.label}`;it.showToast(E,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${m}33`,background:`${m}12`,color:m},children:a}),R.map(L=>{const z=String(x[L.id]||""),$=um(L,y,z),E=N===L.id,V=w===L.id,q=Mr(L,y),ve="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(L.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${ve} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${m}55`:"var(--border-default)",background:E?`${m}10`:"var(--surface-tertiary)",color:z?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void P(L),title:L.label,children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:V?"Loading…":$||L.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),E&&q.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>M(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:L.label}),q.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:pe=>{pe.currentTarget.style.background=`${m}10`},onMouseLeave:pe=>{pe.currentTarget.style.background=ne.value===z?`${m}14`:"transparent"},onClick:()=>void F(L,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))]})]})]},L.id);case"cycle":return s.jsxs("button",{type:"button",className:`${ve} 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(L),title:`Click to cycle: ${q.map(ne=>ne.label).join(" → ")}`,children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$||L.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},L.id);case"toggle":return s.jsxs("button",{type:"button",className:`${ve} 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 W(L),"aria-pressed":!!z,children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),L.label]},L.id);case"action":return s.jsxs("button",{type:"button",className:`${ve} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void T(L),children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:L.resultDisplay==="inline"&&z?`${L.label}: ${z}`:L.label})]},L.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:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:z?`${L.label}: ${z}`:L.label})]},L.id);default:return null}})]})})}function pm({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:m}=zi(),d=Ta(l,{hostIdeType:a,providerType:i});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(fm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:d,controlValues:u})})}function hm({hasDraft:e,isBusy:t=!1}){return!e||t}const Zi=o.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1,animateVisibility:m=!0}){const d=o.useRef(null),[h,f]=o.useState(""),{isVisible:v,toggleVisibility:S}=zi();o.useEffect(()=>{f("")},[t]),o.useEffect(()=>{var x;l&&((x=d.current)==null||x.focus({preventScroll:!0}))},[t,l]);const p=async()=>{const x=h.trim();if(!x||a)return;await c(x)!==!1&&f("")};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:S,"aria-label":v?"Hide controls":"Show controls","aria-pressed":v,title:v?"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:d,type:"text",placeholder:i||`Send message to ${r}...`,value:h,onChange:x=>f(x.target.value),onPaste:x=>{const y=x.clipboardData.getData("text");y&&f(g=>g+y),x.preventDefault()},onKeyDown:x=>{if(x.key==="Enter"){if(x.nativeEvent.isComposing){x.preventDefault();return}x.preventDefault(),p()}},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:()=>{p()},disabled:hm({hasDraft:!!h.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${h.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:h.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:h.trim()?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),Ze=e=>e.transport==="pty",Ls=(e,t)=>Ze(e)?e.mode||"terminal":"chat",ec=(e,t)=>Ze(e)&&Ls(e)==="terminal",Ge=e=>e.transport==="acp";function Ut(e){return e.streamSource!=="agent-stream"}function ms(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function tc(e){return e.machineName||""}function Rs(e){return ms(e)}function $t(e){return e.agentType||""}function Hr(e){return e.hostIdeType||""}function Ma(e){return e.displayPrimary||e.agentName||"Agent"}function sc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function xm(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function So(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 bm(e){return So(e==null?void 0:e.receivedAt)||So(e==null?void 0:e.timestamp)||0}function rc(e){const t=xm(e),r=ks(t==null?void 0:t.content),n=bm(t),a=ks(e.lastMessagePreview),i=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0;return a&&!r?a:r&&!a?r:a&&r&&i>0&&n>0&&i>n?a:r||a||""}function gm(e){return rc(e)||e.displaySecondary||""}function nc(e){return[e.displaySecondary,tc(e)].filter(Boolean)}function Ns(e){return e.agentName||rt($t(e))}function ym(e){var t,r;if(!Ut(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return rt(Hr(e)||$t(e))}function ac(e){return Ut(e)?e.sessionId:e.nativeSessionId}function No(e){return Ut(e)?"native":e.tabKey}function vm(e){return e.sessionId}function wm(e,t){if(t)return Ut(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function jm(e,t){const r=$t(e),n=Ut(e),a=Ze(e)||Ge(e),i=n?a?Ns(e)||(t==null?void 0:t.cliName)||rt(Hr(e)||r):t!=null&&t.type?rt(t.type):rt(Hr(e)||r):Ns(e);return{isNativeConversation:n,isCli:Ze(e),isAcp:Ge(e),isCliTerminal:ec(e),providerType:r,displayLabel:i,targetEntry:wm(e,t)}}function gt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ot(e,t){const r=gt(t);return r?`${e}:${r}`:void 0}function Ft(e,t,r){const n=Ot(t,r),a=gt(r);n&&e.push(n),a&&e.push(a)}function bs(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function oc(e){return gt(e.providerSessionId)||gt(e.sessionId)||gt(e.tabKey)||gt(e.routeId)}function Ia(e){return bs([gt(e.providerSessionId),gt(e.sessionId)])}function vs(e){const t=[];return Ft(t,"provider",e.providerSessionId),Ft(t,"session",e.sessionId),Ft(t,"tab",e.tabKey),Ft(t,"route",e.routeId),bs(t)}function km(e){const t=[];return gt(e.providerSessionId)?(Ft(t,"provider",e.providerSessionId),bs(t)):gt(e.sessionId)?(Ft(t,"session",e.sessionId),bs(t)):gt(e.tabKey)?(Ft(t,"tab",e.tabKey),bs(t)):gt(e.routeId)?(Ft(t,"route",e.routeId),bs(t)):[]}function Aa(e){return Ot("provider",e.providerSessionId)||Ot("session",e.sessionId)||Ot("tab",e.tabKey)||Ot("route",e.routeId)||"unknown:"}function or(e){return Ia(e)[0]}function Sm(e){const t=gt(e.providerSessionId),r=gt(e.sessionId),n=gt(e.tabKey),a=gt(e.routeId),i=[Ot("provider",t),Ot("session",r),Ot("tab",n),Ot("route",a)].filter(u=>typeof u=="string"),c=vs({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=Aa({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:oc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:or({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function sa(e,t){const r=Sm(e);return km(t).some(n=>r.lookupKeys.includes(n))}function Co(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 Qt(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=Co(t==null?void 0:t.receivedAt)||Co(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function ra(e,t=0){return Qt(e)||e.lastUpdated||t||0}function ic(e){return Qt(e)||e.lastUpdated||0}function cc(e,t,r=ic){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(t.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(t.displaySecondary);return c!==0?c:e.tabKey.localeCompare(t.tabKey)}function na(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 Nm(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!na(e)&&!e.title.trim()}function Cm(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(na(r))-Number(na(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:cc(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"),i=Cm(a);return n?i&&Nm(n)?i:n:i||r[0]||null}function zt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function La(e){return or(e)||e.tabKey||e.routeId||null}function lc(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(i=>i.routeId===n);return a?La(a):null}function dc({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Is(),c=ms(e),l=tc(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=Ns(e),f=ym(e),v=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),S=o.useCallback(()=>{if(r){r();return}const p=La(e);p&&i(zt(p))},[e,i,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:S,title:f,children:[s.jsx(St,{size:12}),s.jsx("span",{children:f})]}):s.jsxs("span",{className:"conversation-meta-chip",title:f,children:[s.jsx(St,{size:12}),s.jsx("span",{children:f})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(er,{size:12}),s.jsx("span",{children:h})]}),d&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(er,{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(is,{size:12}),s.jsx("span",{children:l})]}):s.jsxs("span",{className:"conversation-meta-chip",title:l,children:[s.jsx(is,{size:12}),s.jsx("span",{children:l})]}))]})}function gn(e,t){return`${e}:${t}`}function Tm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Es(e,t){Tm()&&console.debug(`[subscription-manager] ${e}`,t)}class Mm{constructor(){ze(this,"active",new Map);ze(this,"retryTimers",new Map)}subscribe(t,r,n,a,i){var d;const c=gn(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),Es("subscribe",{daemonId:r,topic:n.topic,key:n.key}),u=((d=t.sendData)==null?void 0:d.call(t,r,n))??!1,!u&&(i!=null&&i.retryIntervalMs)&&this.scheduleRetry(c,t,i.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};Es("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=gn(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,js.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),js.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=gn(t,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(t){var r;Es("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(i=>i.daemonId===t);Es("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}scheduleRetry(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var l;this.retryTimers.delete(t);const i=this.active.get(t);if(!i)return;const c=((l=r.sendData)==null?void 0:l.call(r,i.daemonId,i.request))??!1;Es("subscribe_retry",{id:t,accepted:c,topic:i.request.topic,key:i.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 Vt=new Mm;function Im(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 i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function Am(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 Fr(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=t,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:m,childrenByParent:d}=Am(u),h=Im(i,n),f=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,v=m.filter(x=>x.kind==="workspace"&&x.transport==="cdp-page"),S=m.filter(x=>x.kind==="agent"&&x.transport==="pty"),p=m.filter(x=>x.kind==="agent"&&x.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(x=>!!x.cdpConnected)});for(const x of v){const y=h.get(x.id),g=Fs(x,y),N=(d.get(x.id)||[]).map(M=>Fs(M,h.get(M.id)));r.push({id:`${n}:ide:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:g.parentId,sessionKind:g.kind,transport:g.transport,sessionCapabilities:g.capabilities,type:g.providerType,status:g.cdpConnected?"online":"detected",daemonId:n,instanceId:x.id,workspace:g.workspace,terminals:0,childSessions:N,agents:N.map(M=>({id:M.id,name:M.providerName||M.providerType,type:M.providerType,status:M.status})),activeChat:g.activeChat,chats:[],cdpConnected:g.cdpConnected,...g.lastMessagePreview!==void 0&&{lastMessagePreview:g.lastMessagePreview},...g.lastMessageRole!==void 0&&{lastMessageRole:g.lastMessageRole},...g.lastMessageAt!==void 0&&{lastMessageAt:g.lastMessageAt},...g.lastMessageHash!==void 0&&{lastMessageHash:g.lastMessageHash},lastUpdated:g.lastUpdated,unread:g.unread,lastSeenAt:g.lastSeenAt,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,seenCompletionMarker:g.seenCompletionMarker,surfaceHidden:g.surfaceHidden,...g.controlValues!==void 0&&{controlValues:g.controlValues},...g.providerControls!==void 0&&{providerControls:g.providerControls},...g.summaryMetadata!==void 0&&{summaryMetadata:g.summaryMetadata},timestamp:l})}for(const x of S){const y=h.get(x.id),g=Fs(x,y);r.push({id:`${n}:cli:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:g.parentId,sessionKind:g.kind,transport:g.transport,sessionCapabilities:g.capabilities,type:g.providerType,agentType:g.providerType,status:g.status||"running",daemonId:n,instanceId:x.id,cliName:g.providerName||g.providerType,mode:g.mode||(y==null?void 0:y.mode)||"terminal",workspace:g.workspace||"",activeChat:g.activeChat,...g.resume!==void 0&&{resume:g.resume},...g.runtimeKey!==void 0&&{runtimeKey:g.runtimeKey},...g.runtimeDisplayName!==void 0&&{runtimeDisplayName:g.runtimeDisplayName},...g.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:g.runtimeWorkspaceLabel},...g.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:g.runtimeWriteOwner},...g.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:g.runtimeAttachedClients},...g.lastMessagePreview!==void 0&&{lastMessagePreview:g.lastMessagePreview},...g.lastMessageRole!==void 0&&{lastMessageRole:g.lastMessageRole},...g.lastMessageAt!==void 0&&{lastMessageAt:g.lastMessageAt},...g.lastMessageHash!==void 0&&{lastMessageHash:g.lastMessageHash},lastUpdated:g.lastUpdated,unread:g.unread,lastSeenAt:g.lastSeenAt,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,seenCompletionMarker:g.seenCompletionMarker,surfaceHidden:g.surfaceHidden,...g.controlValues!==void 0&&{controlValues:g.controlValues},...g.providerControls!==void 0&&{providerControls:g.providerControls},...g.summaryMetadata!==void 0&&{summaryMetadata:g.summaryMetadata},timestamp:l,_isCli:!0})}for(const x of p){const y=h.get(x.id),g=Fs(x,y);r.push({id:`${n}:acp:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:g.parentId,sessionKind:g.kind,transport:g.transport,sessionCapabilities:g.capabilities,type:g.providerType,agentType:g.providerType,status:g.status||"running",daemonId:n,instanceId:x.id,cliName:g.providerName||g.providerType,mode:"chat",workspace:g.workspace||"",activeChat:g.activeChat,...g.runtimeKey!==void 0&&{runtimeKey:g.runtimeKey},...g.runtimeDisplayName!==void 0&&{runtimeDisplayName:g.runtimeDisplayName},...g.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:g.runtimeWorkspaceLabel},...g.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:g.runtimeWriteOwner},...g.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:g.runtimeAttachedClients},...g.lastMessagePreview!==void 0&&{lastMessagePreview:g.lastMessagePreview},...g.lastMessageRole!==void 0&&{lastMessageRole:g.lastMessageRole},...g.lastMessageAt!==void 0&&{lastMessageAt:g.lastMessageAt},...g.lastMessageHash!==void 0&&{lastMessageHash:g.lastMessageHash},lastUpdated:g.lastUpdated,unread:g.unread,lastSeenAt:g.lastSeenAt,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,seenCompletionMarker:g.seenCompletionMarker,surfaceHidden:g.surfaceHidden,...g.controlValues!==void 0&&{controlValues:g.controlValues},...g.providerControls!==void 0&&{providerControls:g.providerControls},...g.summaryMetadata!==void 0&&{summaryMetadata:g.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const Lm=15e3,Rm=15e3,_m=6e4,Pm=1200,To=12,Dm=8e3,Em=4e3,yn=new Map,vn=new Map,xr=new Set,Gs=new Map;function $m(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 Mo(e,t){const r=Gs.get(e);!r||r.size===0||(Gs.delete(e),r.forEach(n=>n(t)))}function Bm(e,t){return new Promise(r=>{const n=Gs.get(e)||new Set;Gs.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&Gs.delete(e),r(c)},i=setTimeout(()=>a(!1),t);n.add(a)})}function ir(){const{sendCommand:e,sendData:t}=wt(),{injectEntries:r,getIdes:n}=Qs();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??_m,l=vn.get(a)||0;if(!(i!=null&&i.force)&&xr.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=yn.get(a);if(u)return u;const m=(async()=>{if(t&&!xr.has(a)){const p=Vt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},x=>{const y=n(),g=y.find(M=>M.id===a),N=Fr(x.status,{daemonId:a,existingDaemon:g,existingEntries:y,timestamp:x.timestamp});N.length>0&&r(N),vn.set(a,Date.now()),Mo(a,!0)});if(p.initialSendAccepted?xr.add(a):xr.delete(a),!(i!=null&&i.force)&&p.initialSendAccepted&&await Bm(a,Pm))return}const d=await e(a,"get_status_metadata"),h=$m(d);if(!h)return;const f=n(),v=f.find(p=>p.id===a),S=Fr(h,{daemonId:a,existingDaemon:v,existingEntries:f,timestamp:h.timestamp||Date.now()});S.length>0&&r(S,{authoritativeDaemonIds:[a]}),vn.set(a,Date.now()),Mo(a,!0)})().finally(()=>{yn.delete(a)});return yn.set(a,m),m},[n,r,e,t])}function sn(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}function ws(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:Ze(e)||Ge(e)?{agentType:$t(e)}:e.streamSource==="agent-stream"?{agentType:$t(e)}:t}function sr(e){return e?Rs(e):""}function $s(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Ra(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Km(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."}const Om=60,Wm=1e3;function uc(e={}){return e.isCliLike?Wm:Om}function Hm(e={}){return uc(e)}const cr=60,Fm=1e3,_a=12e4,Um=new Set(["generating","waiting_approval","starting","streaming","working"]),Io=new Map;function Pa(e,t){return`${e}::${t}`}function aa(e=cr){return{liveMessages:[],cursor:mc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function oa(e){return Mi(e)}function mc(e,t=cr){return{knownMessageCount:e.length,lastMessageSignature:oa(e[e.length-1]),tailLimit:t}}function br(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 Ao(e){for(let t=e.length-1;t>=0;t-=1){const r=sn(e[t]);if(r>0)return r}return 0}function zm(e,t){if(t.length===0)return!1;if(e.length===0)return!0;const r=Ao(e),n=Ao(t);return!(r>0&&n<=0||r>0&&n>0&&n<r||r>0&&n===r&&t.length<e.length)}function Vm(e,t){const r=Array.isArray(t.messages)?t.messages:[];switch(t.syncMode){case"noop":return e;case"append":return[...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 Gm{constructor(t){ze(this,"manager");ze(this,"sendData");ze(this,"daemonId");ze(this,"sessionId");ze(this,"historySessionId");ze(this,"subscriptionKey");ze(this,"snapshot");ze(this,"transportSubscription",null);ze(this,"listeners",new Set);ze(this,"retainCount",0);ze(this,"loadHistoryPromise",null);ze(this,"pendingDisconnectTimer",null);this.manager=t.manager||Vt,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=aa(Math.max(0,t.tailLimit??cr))}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),i=n?"":this.snapshot.cursor.lastMessageSignature;this.snapshot={...this.snapshot,cursor:{knownMessageCount:a,lastMessageSignature:i,tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect())}}}getSnapshot(){return this.snapshot}hydrateLiveMessages(t){const r=Array.isArray(t)?t:[];if(!zm(this.snapshot.liveMessages,r))return;const n=r,a=mc(n,this.snapshot.cursor.tailLimit);br(this.snapshot.liveMessages)===br(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(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...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:Fm}))}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=oa(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=Vm(this.snapshot.liveMessages,t),i={knownMessageCount:a.length,lastMessageSignature:typeof t.lastMessageSignature=="string"?t.lastMessageSignature:oa(a[a.length-1]),tailLimit:this.snapshot.cursor.tailLimit};br(this.snapshot.liveMessages)===br(a)&&this.snapshot.cursor.knownMessageCount===i.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===i.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:a,cursor:i},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:i.knownMessageCount,lastMessageSignature:i.lastMessageSignature}),this.emit())}}function fc(e){const t=Pa(e.daemonId,e.sessionId),r=Io.get(t);if(r)return r.updateOptions(e),r;const n=new Gm(e);return Io.set(t,n),n}function qm(e,t){return{...e,loadHistoryPage:t}}function Ym(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Xm(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Um.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??_a)),i=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return i>0?n-i<=a:Array.isArray(e.messages)&&e.messages.length>0}function Jm(e=_a){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Qm(e,t={}){const r=new Set,n=[];for(const a of e){if(!Xm(a,t))continue;const i=Rs(a),c=a.sessionId||"";if(!i||!c)continue;const l=Pa(i,c);if(r.has(l))continue;r.add(l);const u=or(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Ym),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Zm(e,t){const{sendData:r,sendCommand:n}=wt(),a=(t==null?void 0:t.enabled)!==!1,i=Rs(e),c=e.sessionId||"",l=or(e)||c,u=`daemon:${i}:session:${c}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??cr),d=o.useMemo(()=>!a||!i||!c?null:fc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:m}),[i,a,l,r,c,u,m]),[h,f]=o.useState(()=>(d==null?void 0:d.getSnapshot())||aa(m));o.useEffect(()=>{if(!d){f(aa(m));return}d.retain(),f(d.getSnapshot());const S=d.subscribe(p=>{f(p)});return()=>{S(),d.release()}},[d,m]),o.useEffect(()=>{d&&(d.hydrateLiveMessages(e.messages),f(d.getSnapshot()))},[e.messages,d]);const v=o.useCallback(async()=>{!d||!i||!c||await d.loadHistoryPage(async()=>{const S=e.agentType,p=await n(i,"chat_history",{agentType:S,offset:d.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),x=p&&typeof p=="object"&&"result"in p?p.result||{}:p||{};return{messages:Array.isArray(x.messages)?x.messages:[],hasMore:x.hasMore===!0}})},[e.agentType,d,i,l,n,c]);return o.useMemo(()=>qm(h,v),[v,h])}function ef(e,t){const{sendData:r}=wt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??cr),i=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??_a)),c=Jm(i),[l,u]=o.useState(0),[m,d]=o.useState(()=>new Map);o.useEffect(()=>{if(!n||e.length===0)return;const f=setInterval(()=>{u(v=>v+1)},c);return()=>{clearInterval(f)}},[e.length,n,c]);const h=o.useMemo(()=>Qm(e,{recentActivityMs:i}),[e,i,l]);return o.useEffect(()=>{if(!n||!r||h.descriptors.length===0){d(x=>x.size===0?x:new Map);return}const f=h.descriptors.map(x=>({key:Pa(x.daemonId,x.sessionId),controller:fc({...x,sendData:r,tailLimit:a})})),v=new Set(f.map(({key:x})=>x)),S=(x,y)=>{d(g=>{const N=new Map(g);for(const M of N.keys())v.has(M)||N.delete(M);return N.set(x,y),N})},p=f.map(({key:x,controller:y})=>(y.retain(),S(x,y.getSnapshot()),y.subscribe(g=>S(x,g))));return()=>{p.forEach(x=>x()),f.forEach(({controller:x})=>x.release())}},[h.signature,n,r,a]),m}function Lo(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 Ur(e){for(let t=e.length-1;t>=0;t-=1){const r=sn(e[t]);if(r>0)return r}return 0}function tf(e){const t=Rs(e),r=e.sessionId||"";return t&&r?`${t}::${r}`:""}function sf(e,t){if(t.length===0)return!1;const r=Array.isArray(e.messages)?e.messages:[];if(r.length===0)return!0;const n=Ur(r),a=Ur(t);if(n<=0||a<=n)return!1;const i=Lo(r,e.status),c=Lo(t,e.status);return i!==c}function rf(e,t){const r=t[t.length-1],n=sn(r),a=ks(r==null?void 0:r.content);return{...e,messages:t,...a?{lastMessagePreview:a}:{},...n>0?{lastMessageAt:n}:{}}}function nf(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=Ur(r),i=Ur(n);return a>0&&(i<=0||a>=i)?r:n}function af(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,i=Math.max(0,r.length-n)>0?r.slice(-n):r;return t.length===0?i:[...t,...i]}function Ro(e,t){if(t.size===0||e.length===0)return e;let r=!1;const n=e.map(a=>{var l;const i=tf(a);if(!i)return a;const c=((l=t.get(i))==null?void 0:l.liveMessages)||[];return sf(a,c)?(r=!0,rf(a,c)):a});return r?n:e}function of(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function cf(e){return of(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const lf=60;function ia({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:m=!1,scrollToBottomRequestNonce:d,isInputActive:h=!0,isVisible:f=!0}){var ie,ge,be,H,Q;const v=o.useRef(new Map),S=ir();ar("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const p=jt.useMemo(()=>As(e),[e.status,e.connectionState]),x=o.useMemo(()=>jm(e,t),[e,t]),y=o.useMemo(()=>{var re;return Ta((re=x.targetEntry)==null?void 0:re.providerControls,{hostIdeType:e.hostIdeType,providerType:x.providerType})},[e.hostIdeType,x.providerType,(ie=x.targetEntry)==null?void 0:ie.providerControls]),g=uc({isCliLike:x.isCli||x.isAcp}),N=Hm({isCliLike:x.isCli||x.isAcp}),M=Zm(e,{enabled:f&&!!e.sessionId,tailLimit:N}),[w,I]=o.useState(g),k=e.tabKey,j=M.historyMessages,b=M.hasMoreHistory,B=M.historyError,R=nf(e,M);o.useEffect(()=>{I(g)},[g,k]);const P=Math.max(0,R.length-w),F=Ma(e),U=Rs(e),W=cf(e),T=Ra(e),L=a||T,z=!!T,[$,E]=o.useState(!1);o.useEffect(()=>{const re=x.targetEntry;U&&(!re||re.providerControls===void 0||re.controlValues===void 0)&&S(U,{minFreshMs:3e4}).catch(()=>{})},[U,x.isAcp,(ge=x.targetEntry)==null?void 0:ge.providerControls,(be=x.targetEntry)==null?void 0:be.controlValues,S]);const V=o.useCallback(async()=>{if(!$){if(R.length>w){I(re=>Math.min(R.length,re+lf));return}E(!0);try{await M.loadHistoryPage()}finally{E(!1)}}},[M,$,R.length,w]),{allMessages:q,receivedAtMap:ve}=o.useMemo(()=>{const re=af({historyMessages:j,liveMessages:R,visibleLiveCount:w}),he={};return re.forEach((ue,je)=>{const ce=`${e.tabKey}:${Kr(ue,je)}`;let xe=sn(ue)||v.current.get(ce)||0;xe||(xe=Date.now(),v.current.set(ce,xe)),he[Kr(ue,je)]=xe}),{allMessages:re,receivedAtMap:he}},[e.tabKey,P,j,R,w]),ne=o.useMemo(()=>l.filter(re=>re.routeId===e.tabKey).sort((re,he)=>re.timestamp-he.timestamp),[l,e.tabKey]),pe=o.useMemo(()=>{if(R.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((p.isGenerating||e.status==="streaming")&&E(!1),e.status==="not_monitored"&&W)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(er,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ss,{size:14})," Open ",F," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&W)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(_i,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ss,{size:14})," Open ",F," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!$)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,W,i,c,$,R.length,F,p.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&s.jsx(dc,{conversation:e,className:"chat-pane-meta-row"}),s.jsx(pu,{messages:q,actionLogs:ne,agentName:Ns(e)||F||"Agent",userName:u,isCliMode:x.isCli||x.isAcp,isWorking:p.isGenerating,contextKey:e.tabKey,receivedAtMap:ve,lastMessageHash:e.lastMessageHash,onLoadMore:V,isLoadingMore:$,hasMoreHistory:b,hiddenLiveCount:P,loadError:B??void 0,emptyState:pe,scrollToBottomRequestNonce:d,isVisible:f}),s.jsx(pm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:x.providerType,displayLabel:x.displayLabel,controls:(H=x.targetEntry)==null?void 0:H.providerControls,controlValues:(Q=x.targetEntry)==null?void 0:Q.controlValues,isActive:h,isCliTerminal:x.isCliTerminal}),!x.isCliTerminal&&s.jsx(Zi,{contextKey:e.tabKey,panelLabel:F,isSending:n,isBusy:z,statusMessage:L,onSend:r,isActive:h,showControlsToggle:y.length>0})]})}let pc=os;function hc(){return pc()}class df{constructor(){ze(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{var n;(n=this.listeners.get(t))==null||n.delete(r)}}emit(t,...r){var n;(n=this.listeners.get(t))==null||n.forEach(a=>a(...r))}}let xc=new df;class uf{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 uf;function mf(e){e.dashboardWS&&(xc=e.dashboardWS),e.connectionManager&&(lt=e.connectionManager),e.useDaemonsHook&&(pc=e.useDaemonsHook)}const ff=.5,pf=1.25;function ot(e){return Ma(e)}function ls(e){return nc(e).join(" · ")}function bc(e){const t=rc(e);return t||(e.title?e.title:ls(e)||"No messages yet")}function gc(e,t){const{isReconnecting:r,isConnecting:n}=As(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function hf(e,t){const r=["Chat",...nc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function Zt(e){return gc(e)||ls(e)}function xf(e){return`${ot(e)} · ${bc(e)}`}function bf(e){const t=Hr(e),r=t?rt(t):Ns(e);return`${ot(e)} — ${r||"Agent"}`}function gf(e){return Ns(e)||"CLI"}function yc(e){return sc(e)}function vc(e){return e?`Remote · ${ot(e)||e.workspaceName||"Session"}`:"Remote"}function yf({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var mt;os();const{sendPtyInput:u}=wt(),[m,d]=o.useState(!1),h=o.useRef(!1);h.current=m;const[f,v]=o.useState("Runtime terminal unavailable"),[S,p]=o.useState(!1),[x,y]=o.useState(null),[g,N]=o.useState(!1),[M,w]=o.useState(!1),[I,k]=o.useState(1),[j,b]=o.useState({width:0,height:0}),[B,R]=o.useState({width:0,height:0}),[P,F]=o.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[U,W]=o.useState(null),T=o.useRef(null),L=o.useRef(null),z=o.useRef(!1),$=o.useRef(!1),E=o.useRef(0),V=o.useRef(!1),q=o.useRef(""),ve=o.useRef(null),ne=o.useRef(!1),pe=o.useRef(!1),ie=o.useRef(null),ge=o.useRef(null),be=o.useRef(null),H=32*1024,Q=()=>{var A,C,_,O;return((C=(A=T.current)==null?void 0:A.ownerDocument)==null?void 0:C.defaultView)||((O=(_=L.current)==null?void 0:_.ownerDocument)==null?void 0:O.defaultView)||window},re=A=>{const C=Q();return{ownerWindow:C,frameId:C.requestAnimationFrame(A)}},he=()=>{const A=ie.current;if(A){try{A.ownerWindow.cancelAnimationFrame(A.frameId)}catch{}ie.current=null}},ue=()=>{const A=ge.current;if(A){try{A.ownerWindow.clearTimeout(A.timeoutId)}catch{}ge.current=null}},je=()=>{const A=be.current;if(A){try{A.ownerWindow.clearTimeout(A.timeoutId)}catch{}be.current=null}},ce=()=>{c&&ie.current===null&&(ie.current=re(()=>{Ye()}))},xe=e.tabKey,Z=e.sessionId||"",ae=e.daemonId||((mt=e.routeId)==null?void 0:mt.split(":")[0])||e.routeId||"",te=Ra(e),Y=m?i||te:f,X=ff,le=pf,D=.05,oe=()=>{const A=B.width,C=B.height;if(!Number.isFinite(j.width)||j.width<=0||!Number.isFinite(j.height)||j.height<=0||!Number.isFinite(A)||A<=0||!Number.isFinite(C)||C<=0)return 1;const _=j.width/A,O=j.height/C;return Number(Math.min(le,Math.max(X,Math.min(_,O))).toFixed(2))},J=oe(),we=z.current&&I>J,Ne=Number.isFinite(B.width)&&B.width>0?Math.max(j.width,Math.round(B.width*I)):j.width,Ae=Number.isFinite(B.height)&&B.height>0?Math.max(j.height,Math.round(B.height*I)):j.height,Me=()=>{re(()=>{const A=L.current;A&&(A.scrollLeft=0,A.scrollTop=A.scrollHeight-A.clientHeight)})},Ue=()=>{var A,C;E.current=0,V.current=!1,q.current="",ve.current=null,ne.current=!1,pe.current=!1,z.current||($.current=!1,k(1)),ie.current!==null&&he(),d(!1),v("Runtime terminal unavailable"),je(),ue(),y(null),W(null),p(!1),N(!1),w(!1),(C=(A=r.current)==null?void 0:A.reset)==null||C.call(A)},We=()=>{var A,C;E.current=0,V.current=!1,q.current="",ve.current=null,ne.current=!1,pe.current=!1,ie.current!==null&&he(),d(!0),v(""),je(),ue(),y(null),W(null),p(!1),N(!1),w(!1),(C=(A=r.current)==null?void 0:A.reset)==null||C.call(A)},Be=()=>{pe.current&&(pe.current=!1,re(()=>{var A,C;(C=(A=r.current)==null?void 0:A.scrollToTop)==null||C.call(A)}))},Ye=()=>{if(ie.current=null,!c)return;const A=q.current;if(!A)return;const C=A.slice(0,H);q.current=A.slice(C.length);const _=r.current;if(!_){q.current=C+q.current,ce();return}_.write(C,()=>{if(q.current.length>0){ce();return}Be()})},Xe=A=>{A&&(q.current+=A,ce())},Je=(A,C=0,_,O,G={})=>{var de,ye,Se,Re;const ee=!!G.force;!ee&&C>0&&E.current>=C||!ee&&C===0&&V.current||(E.current=C,C>0&&N(!0),d(!0),v(""),typeof _=="number"&&typeof O=="number"&&_>0&&O>0&&((ye=(de=r.current)==null?void 0:de.resize)==null||ye.call(de,_,O)),q.current="",(Re=(Se=r.current)==null?void 0:Se.reset)==null||Re.call(Se),A?Xe(A):Be())};o.useEffect(()=>{Ue()},[Z]),o.useEffect(()=>{var C;if(!Z)return;const A=((C=lt.onRuntimeEvent)==null?void 0:C.call(lt,Z,_=>{if(!(!_||_.sessionId!==Z)){if(_.type==="runtime_snapshot"){if(!c){ve.current={text:_.text||"",seq:_.seq||0,cols:_.cols,rows:_.rows,force:!!_.force};return}Je(_.text||"",_.seq||0,_.cols,_.rows,{force:!!_.force});return}if(_.type==="session_output"){V.current=!0,typeof _.seq=="number"&&(E.current=Math.max(E.current,_.seq),_.seq>0&&N(!0)),h.current||d(!0),h.current||v(""),typeof _.data=="string"&&Xe(_.data);return}if(_.type==="session_cleared"){if(!c){ne.current=!0,q.current="",ve.current=null;return}We();return}if(_.type==="session_io_error"){const O=typeof _.error=="string"&&_.error?_.error:typeof _.reason=="string"&&_.reason?_.reason:"unknown error";d(!1),v(`Runtime input failed: ${O}`);return}}},ae))||(()=>{});return()=>{A()}},[ae,Z,r,c]);const Ve=async(A={})=>{var C;if(!ae||!Z)return{success:!1,error:"daemonId and sessionId are required"};A.preserveStatus||v(A.loadingMessage||"Loading runtime terminal...");try{const _=await((C=lt.requestRuntimeSnapshot)==null?void 0:C.call(lt,ae,Z,{sinceSeq:A.sinceSeq,force:A.force}));return _&&_.success===!1?(A.preserveStatus||(d(!1),v(`Runtime terminal unavailable: ${_.error}`)),_):_||{success:!0}}catch(_){const O=(_==null?void 0:_.message)||String(_);return A.preserveStatus||(d(!1),v(`Runtime terminal unavailable: ${O}`)),{success:!1,error:O}}},ht=async A=>{var ee,de;const C=((ee=T.current)==null?void 0:ee.ownerDocument)||document,_=C.defaultView||window,O=(de=_.navigator)==null?void 0:de.clipboard;if(O!=null&&O.writeText&&_.isSecureContext)try{return await O.writeText(A),!0}catch{}let G=null;try{return G=C.createElement("textarea"),G.value=A,G.setAttribute("readonly","true"),G.style.position="fixed",G.style.left="-9999px",G.style.top="0",C.body.appendChild(G),G.focus(),G.select(),C.execCommand("copy")}catch{return!1}finally{G==null||G.remove()}},ut=A=>{ue(),W(A);const C=Q();ge.current={ownerWindow:C,timeoutId:C.setTimeout(()=>{ge.current=null,W(_=>_===A?null:_)},2200)}},ft=A=>{je(),y(A);const C=Q();be.current={ownerWindow:C,timeoutId:C.setTimeout(()=>{be.current=null,y(_=>_===A?null:_)},2200)}},Ce=async()=>{var G,ee,de,ye;const A=((ee=(G=r.current)==null?void 0:G.getSelection)==null?void 0:ee.call(G))||"",C=((ye=(de=r.current)==null?void 0:de.getVisibleText)==null?void 0:ye.call(de))||"",_=A.trimEnd()||C.trimEnd();if(!_){ut("Nothing to copy");return}if(!await ht(_)){ut("Copy failed");return}ut(A.trimEnd()?"Copied selection":"Copied visible terminal")},He=async()=>{if(S)return;p(!0),y("Loading older terminal output..."),pe.current=!0;const A=await Ve({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),(A==null?void 0:A.success)===!1){pe.current=!1,y(`Older terminal output unavailable: ${A.error}`);return}w(!0),ft("Older terminal output loaded"),re(()=>{var C;(C=r.current)==null||C.bumpResize()})};o.useEffect(()=>{var C,_;if(!Z)return;ae&&((C=lt.getState)==null?void 0:C.call(lt,ae))==="connected"&&Ve();const A=(_=lt.onStateChange)==null?void 0:_.call(lt,(O,G)=>{O!==ae||G!=="connected"||Ve()});return()=>{A==null||A()}},[ae,Z,r]),o.useEffect(()=>{t&&Ue()},[t,xe,r]),o.useEffect(()=>{var O,G;const A=T.current,C=(G=(O=A==null?void 0:A.ownerDocument)==null?void 0:O.defaultView)==null?void 0:G.ResizeObserver;if(!A||!C)return;const _=new C(ee=>{const de=ee[0];if(!de)return;const{width:ye,height:Se}=de.contentRect;b(Re=>{const ke=Math.round(ye),Ee=Math.round(Se);return Re.width===ke&&Re.height===Ee?Re:{width:ke,height:Ee}})});return _.observe(A),()=>_.disconnect()},[]),o.useEffect(()=>{if(z.current)return;const A=oe();!Number.isFinite(A)||A<=0||k(C=>$.current?A<C-D?A:C:($.current=!0,A))},[B.height,B.width,j.height,j.width]),o.useEffect(()=>{we&&Me()},[we,Ae,Ne]),o.useEffect(()=>{var C;if(!c)return;ne.current&&(ne.current=!1,We());const A=ve.current;A&&(ve.current=null,Je(A.text,A.seq,A.cols,A.rows,{force:!!A.force})),ae&&Z&&((C=lt.getState)==null?void 0:C.call(lt,ae))==="connected"&&Ve(),q.current&&ie.current===null&&ce(),re(()=>{var _;(_=r.current)==null||_.bumpResize()})},[ae,c,Z]),o.useEffect(()=>()=>{ie.current!==null&&he(),ue(),je()},[]),o.useEffect(()=>{const A=O=>{var ee;const G=O.detail;G!=null&&G.sessionId&&G.sessionId!==Z||m&&((ee=r.current)==null||ee.bumpResize())},C=Q(),_=C===window?[window]:[window,C];for(const O of _)O.addEventListener("adhdev:fit-cli-terminal",A);return()=>{for(const O of _)O.removeEventListener("adhdev:fit-cli-terminal",A)}},[m,Z,r]);const nt=m&&g&&!M&&(P.atTop||!P.canScroll)||S||!!x;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:T,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[nt&&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:()=>{He()},disabled:!Z||S,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:S?"Loading older...":"Load older terminal output"}),x&&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:x})]}),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:()=>{Ce()},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,k(A=>{const C=Math.max(J,Number((A-.1).toFixed(2)));return C>J&&Me(),C})},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,k(A=>{const C=Math.min(le,Number((A+.1).toFixed(2)));return C>J&&Me(),C})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:L,className:we?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:Ne>0?`${Ne}px`:"100%",height:Ae>0?`${Ae}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:B.width>0?`${B.width}px`:"100%",height:B.height>0?`${B.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:I},children:s.jsx(Wi,{ref:r,readOnly:!m||!c,sizingMode:"measured",onViewportMetrics:R,onScrollMetrics:F,onInput:A=>{!m||(u==null||u(ae,Z,A))}})})})}),!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(Zi,{contextKey:e.tabKey,panelLabel:ot(e),isSending:a,isBusy:!!te,statusMessage:Y,onSend:async A=>te?!1:n(A),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const vf=5e3;function wf(e){return e==="disconnected"||e==="reconnecting"}function jf({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=vf}){const i=wf(e),[c,l]=o.useState(()=>!i||a<=0),u=o.useRef(!1);o.useEffect(()=>{if(!i){l(!1);return}if(u.current=!1,a<=0){u.current=!0,l(!0);return}l(!1);const y=setTimeout(()=>{u.current=!0,l(!0)},a);return()=>clearTimeout(y)},[a,i]);const m=i?c:e==="offline"||e==="auth_failed",d=o.useMemo(()=>!t||e!=="connected"?!1:a<=0||u.current,[a,t,e]),h=e==="auth_failed"?"red":e==="offline"?"orange":"accent",f={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},v={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},S={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},p="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",x={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[m&&s.jsx("div",{className:p,style:x,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-4 py-3 text-[13px] font-semibold flex items-center gap-2.5 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:f[h],border:v[h],color:S[h]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),n&&e!=="auth_failed"&&s.jsx("button",{type:"button",className:"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,disabled:e==="offline",children:"Reconnect now"})]})}),d&&s.jsx("div",{className:p,style:x,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 kf({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=o.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=o.useState(!1);if(o.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!t||!e||e.backend!=="xterm"||i)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 Da({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(wa,{size:n}):s.jsx(Wt,{size:n})})}const Dt="New session",wc="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 Sf({wsStatus:e,isConnected:t,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),i=a.filter(l=>l==="connected").length,c=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&c>0&&i===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 _o({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Po({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=Qr(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",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(),i()},children:"Delete"})]})]})}function Nf({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:u,onHideConversation:m,hiddenConversations:d=[],onShowConversation:h,onShowAllHidden:f,onResetPanelsToMain:v,inboxOpen:S,onInboxOpenChange:p,hiddenOpen:x,onHiddenOpenChange:y,onOpenNewSession:g,actionShortcuts:N,notifications:M,notificationUnreadCount:w,onOpenNotification:I,onMarkNotificationRead:k,onMarkNotificationUnread:j,onDeleteNotification:b}){const{ides:B,p2pStates:R={}}=os(),P=!!e&&Ze(e)&&!Ge(e),F=!!e&&Ge(e),U=l||(e?ec(e)?"terminal":"chat":null),[W,T]=o.useState(!1),L=o.useRef(null),z=o.useRef(null),$=B.filter(H=>H.type==="adhdev-daemon"),E=Sf({wsStatus:t,isConnected:r,daemonCount:$.length,p2pStates:R}),V=E.subtitle,q=E.tone==="connected"?"#22c55e":E.tone==="limited"?"#eab308":"#ef4444",ve=E.tone==="connected"?"0 0 4px #22c55e80":E.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",ne=o.useMemo(()=>M.filter(H=>!H.readAt),[M]),pe=o.useMemo(()=>M.filter(H=>!!H.readAt),[M]),ie=o.useMemo(()=>ne.slice(0,9),[ne]),ge=w;o.useEffect(()=>{if(!S)return;const H=Q=>{var re;(re=L.current)!=null&&re.contains(Q.target)||p(!1)};return document.addEventListener("mousedown",H),()=>document.removeEventListener("mousedown",H)},[S,p]),o.useEffect(()=>{if(!x)return;const H=Q=>{var re;(re=z.current)!=null&&re.contains(Q.target)||y(!1)};return document.addEventListener("mousedown",H),()=>document.removeEventListener("mousedown",H)},[x,y]),o.useEffect(()=>{if(!x&&!S)return;const H=Q=>{if(!Q.altKey)return;const re=Q.code.match(/^Digit([1-9])$/);if(!re)return;const he=Number(re[1])-1,ue=x?d[he]:void 0,je=S?ie[he]:void 0;if(!(!ue&&!je)){if(Q.preventDefault(),Q.stopPropagation(),ue){h==null||h(ue),y(!1);return}je&&(I(je),p(!1))}};return window.addEventListener("keydown",H,!0),()=>window.removeEventListener("keydown",H,!0)},[d,x,S,ie,y,p,I,h]);const be=H=>{if(!H)return;const Q=n.find(re=>re.tabKey===H);Q&&(m==null||m(Q))};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(Wt,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?ot(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:q,boxShadow:ve}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[s.jsx("span",{title:E.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:q,boxShadow:ve}}),V&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",V]}),g&&s.jsx("button",{type:"button",onClick:g,className:"btn btn-secondary btn-sm ml-2",title:Dt,"aria-label":Dt,children:s.jsx(Ei,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(P||F||!Ge(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:ls(e)||ot(e),children:ot(e)}),(P||F)&&c&&s.jsxs(s.Fragment,{children:[P&&u&&U&&s.jsx(Da,{mode:U,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:F?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(vt,{size:14})})]}),!Ge(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(va,{size:14})}),!P&&!Ge(e)&&s.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(St,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:L,children:[s.jsxs("div",{className:`dashboard-header-hidden${W?" is-drop-target":""}`,ref:z,onDragEnter:H=>{H.dataTransfer.types.includes("text/tab-key")&&(H.preventDefault(),T(!0))},onDragOver:H=>{H.dataTransfer.types.includes("text/tab-key")&&(H.preventDefault(),H.dataTransfer.dropEffect="move",T(!0))},onDragLeave:H=>{H.currentTarget.contains(H.relatedTarget)||T(!1)},onDrop:H=>{const Q=H.dataTransfer.getData("text/tab-key");H.preventDefault(),T(!1),be(Q)},children:[s.jsxs("button",{type:"button",onClick:()=>y(!x),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${N!=null&&N.toggleHiddenTabs?` (${N.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Pi,{size:16}),d.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),x&&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(_o,{value:N==null?void 0:N.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(),y(!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(_o,{value:N==null?void 0:N.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:ot(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(H=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(H),y(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:ot(H)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(H)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(H)+1]}):null,ls(H)]})]},H.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!S),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Jr,{size:16}),ge>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ge})]}),S&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ne.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),ne.map(H=>s.jsx(Po,{notification:H,shortcutIndex:ie.indexOf(H)>=0?ie.indexOf(H)+1:void 0,onOpen:()=>I(H),onMarkRead:()=>k(H.id),onMarkUnread:()=>j(H.id),onDelete:()=>b(H.id)},H.id))]}),pe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),pe.map(H=>s.jsx(Po,{notification:H,onOpen:()=>I(H),onMarkRead:()=>k(H.id),onMarkUnread:()=>j(H.id),onDelete:()=>b(H.id)},H.id))]}),M.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function pt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Cf(e,t){return String(e||"")!==String(t||"")}function Tf(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),i=!!t.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(u=>String(u||"").toLowerCase()).join(`
30
- `).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!qi(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
31
- `).includes(a)))}function Mf(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 i=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function jc(e,t={}){return Mf(Tf(e,t),t.sortMode||"recent")}function zr(e){return e?"Resume saved history":"Start fresh"}function Ea(e){return e?"Resuming saved history…":"Starting fresh…"}function If(){return"Start fresh"}function kc(e,t=!1){return e==="cli"?zr(t):e==="ide"?"Start IDE":"Start ACP session"}function Sc(e,t=!1){return e==="cli"?Ea(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Af(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Lf(){return"Open saved history"}function Rf(){return"Saved History"}function $a(){return"Use saved history when you want continuity in the same provider conversation."}function _f(){return"No saved history found yet."}function Pf(){return"Refresh saved history"}function Df(){return"Refreshing saved history…"}function es(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function ts(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 Cs(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ts(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Ba(e){return`Resume saved history with ${e}?`}function Ka(){return"Review or change the target workspace before resuming saved history."}function Ef(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 Oa({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:m,onNewChat:d,onSwitchSession:h,onRefreshHistory:f,onResumeSavedSession:v}){var j;const S=t.find(b=>b.id===e.routeId),p=(S==null?void 0:S.chats)||[],x=(j=S==null?void 0:S.activeChat)==null?void 0:j.id,y=Ze(e)&&!Ge(e),[g,N]=o.useState(()=>pt()),M=l||g,w=b=>{if(u){u(b);return}N(b)},I=o.useMemo(()=>jc(a,{textQuery:M.textQuery,workspaceQuery:M.workspaceQuery,modelQuery:M.modelQuery,resumableOnly:M.resumableOnly,sortMode:M.sortMode}),[M.modelQuery,M.resumableOnly,M.sortMode,M.textQuery,M.workspaceQuery,a]),k=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:m,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:y?Rf():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:bf(e)}),y&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:$a()})]}),s.jsx("button",{onClick:m,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!y&&s.jsx("button",{onClick:d,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),y?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:M.textQuery,onChange:b=>w({...M,textQuery:b.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:M.workspaceQuery,onChange:b=>w({...M,workspaceQuery:b.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:M.modelQuery,onChange:b=>w({...M,modelQuery:b.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:M.sortMode,onChange:b=>w({...M,sortMode:b.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:M.resumableOnly,onChange:b=>w({...M,resumableOnly:b.target.checked})}),"Resume-ready only"]})]}),I.map(b=>{const B=e.providerSessionId===b.providerSessionId,R=B||!b.canResume||!!c;return s.jsxs("button",{type:"button",onClick:()=>{R||!v||v(b)},disabled:R,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${B?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${R?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${B?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:b.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:b.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Ef(b.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:b.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:[b.workspace||"Workspace unknown",cs(b.summaryMetadata)?` · ${cs(b.summaryMetadata)}`:"",b.messageCount>0?` · ${b.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:B?"ACTIVE":b.canResume?c===b.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},b.id)})]}):p.map(b=>s.jsxs("div",{onClick:()=>{h(e.routeId,b.id),m()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===b.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===b.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:b.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:[b.id.substring(0,12),"..."]}),x===b.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},b.id)),(y&&!i&&I.length===0||!y&&p.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(Wd,{size:32})}),s.jsx("div",{className:"text-[13px]",children:y?a.length>0?"No saved history matches these filters.":_f():"No recent chat sessions found."})]}),y&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Df()})})]}),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:f,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(nr,{size:13})," ",y?Pf():"Refresh History"]})})})]})]});return typeof document>"u"?k:Js.createPortal(k,document.body)}const Do={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 Nc({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=Do[n.type]||Do.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=n.actions)!=null&&i.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:i=>{i.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(vt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:l=>{l.stopPropagation(),i.onClick(),t(n.id)},children:i.label},c))})]})]},n.id)})})}const $f=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Bf(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Kf(e){return e.sessionId||e.instanceId||e.agentType}function wn(e,t){return e||t}function Cc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Tt(r,{fallbackId:r.id}));return t}function Tc(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 Wa(e,t={}){return Of(e,Tc(e,t))}function Of(e,t={}){var d,h,f,v,S,p;const r=[],n=t.machineName,a=t.connectionState,i=Bf(e),c=_u(e.type,{agentName:e.cliName}),l=Ze(e)||Ge(e)?c:rt(e.type),u=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var y,g;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||rt(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((y=x.activeChat)==null?void 0:y.messages)||[],activeModal:((g=x.activeChat)==null?void 0:g.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,surfaceHidden:x.surfaceHidden}}):[],m=$f(e);if(m){const x=e.sessionId||e.instanceId,y=c,g=(d=e.activeChat)==null?void 0:d.activeModal,N=g&&Array.isArray(g.buttons)&&g.buttons.length>0,M=bt((h=e.activeChat)==null?void 0:h.status,{activeModal:(f=e.activeChat)==null?void 0:f.activeModal})||bt((S=(v=e.agents)==null?void 0:v[0])==null?void 0:S.status)||"idle",w=e.activeChat||{title:"",messages:[]};let I=w.title&&String(w.title).trim()?String(w.title).trim():"";const k=(p=e.activeChat)==null?void 0:p.id,j=e.chats;if(k&&Array.isArray(j)&&j.length>0){const P=j.find(F=>F.id===k||F.id&&String(F.id)===String(k));P!=null&&P.title&&String(P.title).trim()&&(I=String(P.title).trim())}const b=(Ze(e)||Ge(e),e.type),B=(Ze(e)||Ge(e))&&wo(I,y,b)?"":I,R=w.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:y,agentType:b,status:M,title:B,messages:R,resume:e.resume,hostIdeType:!Ze(e)&&!Ge(e)?e.type:void 0,workspaceName:i,displayPrimary:B||i||(Ze(e)?e.mode==="chat"?y:"Terminal":y),displaySecondary:l,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:N?g.buttons:void 0,modalMessage:N?g.message:void 0,streamSource:"native",tabKey:wn(x,e.id),machineName:n,connectionState:a})}if(m&&(Ze(e)||Ge(e)))return r;for(const x of u){const y=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,g=Pu(x),N=Kf(x),M=`${e.id}:${N}`,w=x.title&&String(x.title).trim()||"",I=wo(w,x.agentName,x.agentType)?"":w,k=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||k.length>0||y||I||!["idle","panel_hidden","disconnected","not_monitored"].includes(g))&&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:g,title:I,messages:k,hostIdeType:e.type,workspaceName:i,displayPrimary:I||i||x.agentName||l,displaySecondary:`${l} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,modalButtons:y?x.activeModal.buttons:void 0,modalMessage:y?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:wn(x.sessionId||x.instanceId,M),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:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:i,displayPrimary:i||l,displaySecondary:l,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:wn(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function Wf(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 Mc(e,t){const r=Wf(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Ic=[{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:"🏄"}],Ac=[{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:"🧩"}],Lc=[{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:"🟠"}],Hf=Ic,Ff=Ac,Uf=Lc;function ds(...e){return td(sd(e))}function zf({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:ds("dashboard-header",i),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 Rc({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(zf,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ds("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const ca="adhdev:themechange";function Vf(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function hs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function xs(e){return e==="system"?Vf():e}function _c(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Ir(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(ca,{detail:{preference:e,theme:t}}))}function Gf(){const e=hs(),t=xs(e);_c(t),Ir(e,t)}function Ha(){const[e,t]=o.useState(hs),[r,n]=o.useState(()=>xs(hs()));o.useEffect(()=>{_c(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const m=u.matches?"light":"dark";n(m),Ir("system",m)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const m=u.detail||{},d=m.preference,h=m.theme;t(d==="dark"||d==="light"||d==="system"?d:hs()),n(h==="dark"||h==="light"?h:xs(hs()))},l=u=>{if(u.key!=="theme")return;const m=hs(),d=xs(m);t(m),n(d)};return window.addEventListener(ca,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ca,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=xs(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Ir(c,l)},[]),i=o.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=xs(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Ir(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const Eo={dark:"Dark",light:"Light",system:"System"};function qf({collapsed:e}){const{preference:t,cycleTheme:r}=Ha(),n=t==="dark"?s.jsx(Fd,{size:16}):t==="light"?s.jsx(Hd,{size:16}):s.jsx(Ud,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Eo[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Eo[t]})]})}function jn(e,t){return e?typeof e=="function"?e(t):e:null}function Yf({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:u="sidebar-collapsed"}){const[m,d]=o.useState(!1),[h,f]=o.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),v=()=>d(!0),S=()=>d(!1),p=()=>{f(N=>{const M=!N;try{localStorage.setItem(u,M?"1":"0")}catch{}return M})},x=o.useMemo(()=>({collapsed:h,mobileMenuOpen:m,openMobileMenu:v,closeMobileMenu:S,toggleCollapsed:p}),[h,m]),y=N=>`nav-item${N.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${N.className?` ${N.className}`:""}`,g=N=>s.jsxs("div",{className:y(N),id:`nav-${N.id}`,onClick:()=>{N.onSelect(),S()},title:h?N.title??(typeof N.label=="string"?N.label:void 0):N.title,children:[s.jsx("span",{className:"nav-icon",children:N.icon}),!h&&N.label]},N.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:S,onKeyDown:N=>N.key==="Escape"&&S()}),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:jn(t,x)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:S,children:s.jsx(vt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(g)}),n.map(N=>s.jsxs("div",{className:N.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&N.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:N.title}):null,N.items.map(g)]},N.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(g),jn(i,x),s.jsx(qf,{collapsed:h}),jn(c,x)]})]}),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:i}){return s.jsxs("div",{className:ds("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})]}),i]})}function Pc({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ds("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 Xf={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"},Jf={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function gr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ds("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Xf[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Jf[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 Qf={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"},Zf={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function ep({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ds("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Qf[e],r),children:[s.jsx("span",{className:ds("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Zf[e])}),n]})}function Xt({label:e,description:t,checked:r,disabled:n,onChange:a,extra:i}){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:[i,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 tp({onPrefChange:e}){const[t,r]=Uu(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.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 i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>i("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(St,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>i("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:()=>{Ji().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(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vd,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(er,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>i("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 Vr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function sp(e,t){const r=Vr(e),n=Vr(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 Dc(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function qs(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||sp(r,t)>=0)return!1;const n=Vr(r),a=Vr(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function rp(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function kn(e,t){return e instanceof Error?e.message:t}function np({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Pc,{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:i.map(c=>s.jsx(op,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function $o({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return Js.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,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:i,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 ap(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Hf,...Ff,...Uf].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 op({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var U,W;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[m,d]=o.useState(null),[h,f]=o.useState("idle"),[v,S]=o.useState(""),p=e.version||null,x=((U=e.machine)==null?void 0:U.platform)||((W=e.system)==null?void 0:W.platform)||"",y=Tt(e,{fallbackId:e.id}),g=x==="win32"?"🪟":x==="darwin"?"🍎":"🐧",N=t.filter(T=>T.daemonId===e.id&&T.transport==="cdp-page"),M=t.filter(T=>T.daemonId===e.id&&T.transport==="pty"),w=t.filter(T=>T.daemonId===e.id&&T.transport==="acp"),I=e.p2p,k=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const T=rp(await r(e.id,"daemon_upgrade",{}));T.alreadyLatest?(c("done"),u(`Already on v${T.version||"latest"}.`)):T.upgraded||T.success?(c("done"),u(`Upgrade to v${T.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(T.error||"Upgrade failed"))}catch(T){c("error"),u(kn(T,"Connection lost during upgrade"))}}},j=async()=>{if(d(null),!!n){f("loading");try{await n(e.id),f("done"),S("Machine disconnected.")}catch(T){f("error"),S(kn(T,"Failed to disconnect"))}}},b=async()=>{if(d(null),!!a){f("loading");try{await a(e.id),f("done"),S("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(T){f("error"),S(kn(T,"Failed to revoke token"))}}},B="0.9.43",R=Dc(e,B),P=qs(e,B),F=N.length+M.length+w.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:g}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:y}),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] ${R?"":"bg-bg-secondary"}`,style:R?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!R&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&R&&s.jsx("button",{onClick:k,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${B}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${P?"↑ Update now":`↑ Update${` to v${B}`}`}`}),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(ep,{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&&F>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),F>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(T=>{const L=ap(T.type),z=T.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:L.icon}),s.jsx("span",{children:L.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..."})]},T.id)}),M.map(T=>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:T.cliName||"CLI"})]},T.id)),w.map(T=>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:T.cliName||"ACP"})]},T.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 ${i==="error"||h==="error"?"text-red-400":i==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:v||l})]}),m==="disconnect"&&s.jsx($o,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
32
-
33
- This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
34
-
35
- Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:j,onCancel:()=>d(null)}),m==="revoke"&&s.jsx($o,{title:"⚠️ Remove Machine",message:`Remove "${y}" from your dashboard?
36
-
37
- This will:
38
- • Immediately disconnect the machine
39
- • Delete the machine registration
40
- • Require restarting ADHDev on that machine
41
-
42
- Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:b,onCancel:()=>d(null)})]})}const ip=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function cp(){const{preference:e,setPreference:t}=Ha();return s.jsx("div",{className:"flex gap-2",children:ip.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 lp(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 dp(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Sn(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Bo(e){const{r:t,g:r,b:n}=dp(e);return .2126*Sn(t)+.7152*Sn(r)+.0722*Sn(n)}function Ko(e,t){const r=Bo(e),n=Bo(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Ec(e){const t=lp(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Ko(t,r)>=Ko(t,n)?r:n}const la={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},da={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},up=[{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"}}}],$c="adhdev-chat-theme",Bc="adhdev-chat-theme-custom";function Ar(){if(typeof window>"u")return"ember";try{return localStorage.getItem($c)||"ember"}catch{return"ember"}}function Rt(e){try{const t=localStorage.getItem(Bc);if(t){const r=JSON.parse(t);return{...e==="dark"?la:da,...r[e]}}}catch{}return e==="dark"?la:da}function yr(e,t){try{localStorage.setItem(Bc,JSON.stringify({dark:e,light:t}))}catch{}}function Nt(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 Gr(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 mp={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Ys(e,t){var a;const r=(a=mp[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",Gr(r,24)),n.style.setProperty("--accent-on-primary",Ec(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Gr(r,18)})`),n.style.setProperty("--border-accent",Nt(r,.35)),n.style.setProperty("--nav-active-bg",Nt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Nt(r,.06)}`)}function ss(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Nt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Nt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Nt(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",Nt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Nt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Gr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Ec(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Gr(e.accentColor,40)})`),t.style.setProperty("--border-accent",Nt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Nt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Nt(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 ${Nt(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 Fa(){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 fp(e){try{localStorage.setItem($c,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=rs()?"dark":"light";ss(Rt(t))}else Fa(),Ys(e,rs()?"dark":"light")}function pp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Ar();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=rs()?"dark":"light";ss(Rt(t))}else Fa(),Ys(e,rs()?"dark":"light")}function rs(){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 Bs({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 hp({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=o.useState(()=>Rt(r));o.useEffect(()=>{a(Rt(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const m={...u,[c]:l},h=Rt(r==="dark"?"light":"dark");return r==="dark"?yr(m,h):yr(h,m),ss(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(Bs,{title:"App Background",children:[s.jsx(xt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(xt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(xt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Bs,{title:"App Text",children:[s.jsx(xt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(xt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(xt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Bs,{title:"Borders & Accent",children:[s.jsx(xt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(xt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(xt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Bs,{title:"Chat Bubbles",children:[s.jsx(xt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(xt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(xt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(xt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Bs,{title:"Chat Layout",children:[s.jsx(xt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(xt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(xt,{label:"Input border",value:n.inputBorder,onChange:c=>i("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=>i("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?la:da,u=Rt(e?"light":"dark");e?yr(c,u):yr(u,c),a(c),ss(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 xp(){const[e,t]=o.useState(Ar),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Rt("dark"));o.useEffect(()=>{n(rs());const u=new MutationObserver(()=>{const h=rs();n(h);const f=Ar();f==="custom"?ss(Rt(h?"dark":"light")):Ys(f,h?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const h=rs();n(h);const f=Ar();f==="custom"?ss(Rt(h?"dark":"light")):Ys(f,h?"dark":"light")};return m.addEventListener("change",d),()=>{u.disconnect(),m.removeEventListener("change",d)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ss(Rt(r?"dark":"light")):(Fa(),Ys(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Rt(r?"dark":"light"))},[r]);const c=u=>{t(u),fp(u)},l=[...up,{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(hp,{dark:r,onColorsChange:u=>i(u)})]})}const Ua="adhdev_mobileDashboardMode_v1",ua="adhdev:mobile-dashboard-mode-change";function za(){try{return localStorage.getItem(Ua)==="workspace"?"workspace":"chat"}catch{return"chat"}}function bp(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??za())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==Ua||t()};return window.addEventListener(ua,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ua,r),window.removeEventListener("storage",n)}}function gp(e){try{localStorage.setItem(Ua,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ua,{detail:e}))}function yp(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(za()==="chat")},[]),s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Wt,{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),gp(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Nn=new Map,Oo=new Map;function vp(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 wp(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 Kc(){const{sendCommand:e}=wt(),{injectEntries:t,getIdes:r}=Qs();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??Rm,c=Oo.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=Nn.get(n);if(l)return l;const u=(async()=>{const m=await e(n,"get_machine_runtime_stats"),d=vp(m);if(!d)return;const h=r().find(v=>v.id===n),f=wp(h,n,d.machine,d.timestamp||Date.now());t([f]),Oo.set(n,Date.now())})().finally(()=>{Nn.delete(n)});return Nn.set(n,u),u},[r,t,e])}function jp(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 kp(e,t){const{sendData:r}=wt(),{injectEntries:n,getIdes:a}=Qs(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>Vt.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=jp(h,u,d);n([f])}));return()=>{l.forEach(u=>u())}},[i,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function Sp(e,t){const{sendData:r}=wt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.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=Vt.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)},Em):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:i,applyDiagnostics:a}}function Np(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Oc(e){const{sendData:t}=wt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=Np(e);if(!a||!e.sessionId||!t){n({});return}const i=Vt.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}),js.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 i.initialSendAccepted||n({}),()=>{i()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const Wc="adhdev_hiddenTabs";function Cp(){try{const e=localStorage.getItem(Wc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function fs(e){try{localStorage.setItem(Wc,JSON.stringify([...e]))}catch{}}function Cn(e){return Aa(e)}function Va(e,t){return vs(t).some(r=>e.has(r))}function Tp(){const[e,t]=o.useState(Cp),r=o.useCallback(m=>{const d=Cn(m);t(h=>{const f=new Set(h);return f.has(d)?f.delete(d):f.add(d),fs(f),f})},[]),n=o.useCallback(m=>{const d=Cn(m);t(h=>{if(h.has(d))return h;const f=new Set(h);return f.add(d),fs(f),f})},[]),a=o.useCallback(m=>{const d=Cn(m);t(h=>{if(!h.has(d))return h;const f=new Set(h);return f.delete(d),fs(f),f})},[]),i=o.useCallback(()=>{t(m=>{if(m.size===0)return m;const d=new Set;return fs(d),d})},[]),c=o.useCallback((m,d)=>{t(h=>{const f=new Set(h);for(const v of d)f.add(v);return fs(f),f})},[]),l=o.useCallback((m,d)=>{t(h=>{const f=new Set(h);for(const v of d)f.delete(v);return fs(f),f})},[]),u=o.useCallback(m=>Va(e,m),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Hc(e){return e instanceof Error?e.message:String(e||"")}function Fc(e){const t=Hc(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 Uc(e){const t=Hc(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function zc({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Ze(e)||Ge(e))return;const i=Ls(e);if(i===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(ms(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:$t(e),mode:t})}catch(l){const u=Uc(l);c&&!u&&a(m=>{const d={...m};return i===Vc(r,c)?delete d[c]:d[c]=i,d}),Fc(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 Wo(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 Mp(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 i=Wo(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>Wo(u,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Vc(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 Ip(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))Vc(t,a)===i&&(delete n[a],r=!0);return r?n:e}function Ap({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Ji()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:yc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return qu(a),o.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]),o.useEffect(()=>{const i=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(i)},[n]),null}function Lp(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 i=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function Tn(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 Rp(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 Ho(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Rp(ks(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 _p(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||""),Ho(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||""),Ho(r.activeChat)].join(":"))].join("|")}function Pp(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 Dp(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const i of vs({routeId:n.routeId}))r.set(i,a);for(const i of vs({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of vs({tabKey:n.tabKey}))r.set(i,n)}return r}function Ep(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function $p(e){const t=Ep(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=ks(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Bp({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>Lp(e),[e]),i=o.useMemo(()=>Cc(e),[e]),c=o.useRef([]),l=o.useRef([]),u=o.useRef([]),m=o.useRef(new Map),d=o.useRef(new Map),h=o.useMemo(()=>{const M=new Map,w=[];for(const b of a){const{connectionState:B="new",machineName:R}=Tc(b,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),P=_p(b),F=m.current.get(b.id);if(F&&F.ide===b&&F.sourceSignature===P&&F.connectionState===B&&F.machineName===R){M.set(b.id,F),w.push(...F.conversations);continue}const U=Wa(b,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),W={ide:b,sourceSignature:P,connectionState:B,machineName:R,conversations:U};M.set(b.id,W),w.push(...U)}m.current=M;const I=new Map,k=b=>{const B=$p(b),R=d.current.get(b.tabKey);if(R&&R.signature===B)return I.set(b.tabKey,R),R.timestamp;const P={signature:B,timestamp:ic(b)||(R==null?void 0:R.timestamp)||0};return I.set(b.tabKey,P),P.timestamp},j=[...w].sort((b,B)=>cc(b,B,k));return d.current=I,j},[a,t,i]),f=o.useMemo(()=>{const M=Pp(h,r);return Tn(c.current,M)?c.current:(c.current=M,M)},[h,r]),v=o.useMemo(()=>{const M=new Map,w=Array.from(new Set(f.map(I=>I.routeId)));for(const I of w){const k=_t(f,I);k&&M.set(I,k)}return M},[f]),S=o.useMemo(()=>{const M=new Map;for(const w of f){const I=v.get(w.routeId),k=w.streamSource==="native"&&I?I:w;for(const j of vs({providerSessionId:w.providerSessionId,sessionId:w.sessionId}))M.set(j,k)}return M},[f,v]),p=o.useMemo(()=>Dp(f,v),[f,v]),x=o.useCallback(M=>{if(M)return S.get(M)},[S]),y=o.useCallback(M=>{if(M)return p.get(M)},[p]),g=o.useMemo(()=>{const M=f.filter(w=>!Va(n,w));return Tn(l.current,M)?l.current:(l.current=M,M)},[f,n]),N=o.useMemo(()=>{const M=g.map(w=>w.tabKey);return Tn(u.current,M)?u.current:(u.current=M,M)},[g]);return{chatIdes:a,conversations:f,visibleConversations:g,visibleTabKeys:N,resolveConversationBySessionId:x,resolveConversationByTarget:y}}function Kp({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),i=o.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=o.useCallback(()=>{t&&n(l=>{const u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Op({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{it.setIdes(e)},[e]),o.useEffect(()=>{it.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),o.useEffect(()=>{const a=it.onToast(i=>{r(l=>l.some(m=>m.message===i.message&&i.timestamp-m.timestamp<3e3)?l:[...l.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions}]);const c=i.duration||5e3;setTimeout(()=>r(l=>l.filter(u=>u.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=xc.on("status_event",i=>{it.handleRawEvent(i,"ws")});return()=>{a()}},[]),o.useEffect(()=>{var i;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(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(v);t(d,"resolve_action",{action:S?"approve":"reject",button:f,...Number.isFinite(h)&&{buttonIndex:h},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};return(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,t])}const Wp="adhdev_dashboardLayout_v1",Hp="adhdev_dashboardDockview_v1",Fp="adhdev_dashboardDockviewHiddenRestore_v1",Ks={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ga(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Up(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Gc(e){return`${Wp}:${e}`}function zp(e){const t=Gc(e);return Ga(t,null)}function Vp(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=Gc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function qc(e){return`${Hp}:${e}`}function Gp(e){const t=qc(e);return Ga(t,null)}function qp(e,t){try{const r=qc(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Yc(e){return`${Fp}:${e}`}function Yp(e){const t=Yc(e);return Ga(t,{})}function Xp(e,t){try{const r=Yc(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Jp(){return{groupAssignments:[...Ks.groupAssignments],focusedGroup:Ks.focusedGroup,groupActiveTabIds:{...Ks.groupActiveTabIds},groupTabOrders:{...Ks.groupTabOrders},groupSizes:[...Ks.groupSizes]}}function Qp(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Zp(){const[e]=o.useState(()=>Up(typeof window<"u"?window.innerWidth:1280)),[t,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[m,d]=o.useState([]),[h,f]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[v,S]=o.useState(!1),p=o.useCallback(()=>{if(v)return;const b=zp(e)??Jp();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),u(b.groupTabOrders),d(b.groupSizes),S(!0)},[v,e]);o.useEffect(()=>{v&&Vp(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:m})},[v,e,t,n,i,l,m]),o.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),B=R=>f(R.matches);return b.addEventListener("change",B),()=>b.removeEventListener("change",B)},[]);const x=o.useCallback(b=>{r(b)},[]),y=o.useCallback(b=>{a(b)},[]),g=o.useCallback(b=>{c(b)},[]),N=o.useCallback(b=>{u(b)},[]),M=o.useCallback(b=>{d(b)},[]),w=o.useCallback(b=>{y(b)},[y]),I=o.useCallback((b,B)=>{c(R=>(R[b]??null)===(B??null)?R:{...R,[b]:B})},[]),k=o.useCallback((b,B)=>{u(R=>{const P=R[b];return Qp(P,B)?R:{...R,[b]:B}})},[]),j=o.useCallback((b,B)=>{const R=B.get(b)??0;return I(R,b),w(R),R},[w,I]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:n,updateFocusedGroup:y,focusGroup:w,groupActiveTabIds:i,updateGroupActiveTabIds:g,setGroupActiveTab:I,groupTabOrders:l,updateGroupTabOrders:N,setGroupTabOrder:k,groupSizes:m,updateGroupSizes:M,isMobile:h,hasHydratedStoredLayout:v,hydrateStoredLayout:p,focusConversationTab:j}}function eh(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Ia(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function th({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:u,activeConv:m,isRefreshingHistory:d,ides:h,handleRefreshHistory:f}){const v=o.useRef(!1),S=o.useRef(!1),p=o.useRef(null),x=o.useRef(!1);o.useEffect(()=>{if(!e||v.current||t.length===0)return;if(!a){i();return}const y=r(e);y&&(c(y.tabKey,n),v.current=!0,S.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(g=>{const N=new URLSearchParams(g);return N.delete("activeTab"),N},{replace:!0}))},[e,t,r,n,a,i,c,l]),o.useEffect(()=>{if(!(S.current||a)&&t.length!==0){if(!e){i(),S.current=!0;return}if(v.current){S.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(S.current||a)&&(i(),S.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,i]),o.useEffect(()=>{if(!u){x.current=!1;return}if(!m||x.current||d)return;const y=h.find(g=>g.id===m.routeId);y&&(!y.chats||y.chats.length===0||eh(y.chats,m))&&(x.current=!0,f())},[u,m,d,h,f])}function Mn(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=Ia(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Xc({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[u,m]=o.useState(!1),d=o.useCallback(async S=>{try{await e("standalone","launch_ide",{ideType:S,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=o.useCallback(async(S,p)=>{try{const x=S||(t==null?void 0:t.daemonId)||"",y=await e(x,"switch_chat",{id:p,sessionId:p,...ws(t)}),g=y==null?void 0:y.result;if((y==null?void 0:y.success)===!0||g==="switched"||g==="switched-by-title")return;g===!1||g==="not_found"?$s(a,"⚠️ Session tab not found — try refreshing history"):typeof g=="string"&&g.startsWith("error:")?$s(a,`⚠️ Switch error: ${g}`):$s(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),$s(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,a]),f=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const S=sr(t);await e(S,"new_chat",{...ws(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(S){console.error("New chat failed",S)}finally{l(!1)}}},[t,c,e,i]),v=o.useCallback(async()=>{var S,p;if(!(!t||u)){m(!0);try{const x=sr(t),y=async()=>e(x,"list_chats",{forceExpand:!0,...ws(t)});let g=await y(),N=(g==null?void 0:g.chats)||((S=g==null?void 0:g.result)==null?void 0:S.chats);Mn(N,t)&&(await new Promise(M=>setTimeout(M,450)),g=await y(),N=(g==null?void 0:g.chats)||((p=g==null?void 0:g.result)==null?void 0:p.chats)),g!=null&&g.success&&Array.isArray(N)&&(n(t.routeId,N),Mn(N,t)&&!Mn(r,t)&&$s(a,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{m(!1)}}},[t,r,u,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:h,handleNewChat:f,handleRefreshHistory:v}}function sh(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 rh(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Fo(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 vr(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 i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const u=a[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function Uo(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=t[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function nh(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 ah(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),i=a.reduce((c,l)=>c+l,0);return i>0?a.map(c=>c/i*100):Array(r).fill(100/r)}function zo(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=t?i+1:i]=a}return r}function Vo(e){return Array(e).fill(100/e)}function oh({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:m}){const d=o.useRef(null),h=o.useMemo(()=>vr(e,m),[e,m]),f=h.assignments,v=o.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),S=v>1,p=o.useCallback((w,I)=>{t(k=>{const j=new Map(vr(k,m).assignments);return I===0?j.delete(w):j.set(w,I),j}),n(k=>({...k,[I]:w})),r(I)},[t,m,n,r]),x=o.useCallback(w=>{t(I=>{const k=vr(I,m).assignments,j=new Map;for(const[b,B]of k)B!==w&&(B>w?j.set(b,B-1):j.set(b,B));return j}),c(I=>{if(I.length<=1)return[];const k=[...I];k.splice(w,1);const j=k.reduce((b,B)=>b+B,0);return j>0?k.map(b=>b/j*100):[]}),r(0)},[t,m,c,r]),y=o.useCallback((w,I)=>{I.preventDefault();const k=d.current;if(!k)return;const j=I.clientX,b=k.offsetWidth,B=i.length===v?[...i]:Vo(v),R=F=>{const W=(F.clientX-j)/b*100,T=[...B];T[w]=Math.max(15,B[w]+W),T[w+1]=Math.max(15,B[w+1]-W),c(T)},P=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",P),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",R),document.addEventListener("mouseup",P)},[i,v,c]),g=o.useCallback((w,I,k)=>{if(v>=4)return;const j=k==="left"?I:I+1;t(b=>{const B=vr(b,m).assignments,R=new Map;for(const P of u){const F=B.get(P.tabKey)??0,U=F>=j?F+1:F;U>0&&R.set(P.tabKey,U)}return j>0&&R.set(w,j),R}),c(b=>{const B=b.length===v?[...b]:Vo(v),R=B[I]??100/v,P=Math.max(15,R/2),F=Math.max(15,R/2),U=[...B];U[I]=P,U.splice(j,0,F);const W=U.reduce((T,L)=>T+L,0);return U.map(T=>T/W*100)}),n(b=>{const B=zo(b,j);return B[j]=w,B}),a(b=>{const B=zo(b,j);return B[j]=[w],B}),r(j)},[v,t,m,u,c,n,a,r]);o.useEffect(()=>{sh(e,f)||t(f)},[e,f,t]),o.useEffect(()=>{const{mapping:w,usedGroups:I}=h;n(k=>{const j=Uo(k,w);return Fo(k,j)?k:j}),a(k=>{const j=Uo(k,w);return Fo(k,j)?k:j}),r(k=>{const j=l?0:nh(k,I,w);return k===j?k:j}),c(k=>{const j=l?[]:ah(k,I,h.groupCount);return rh(k,j)?k:j})},[h,l,n,a,r,c]);const N=o.useMemo(()=>{const w=Array.from({length:v},()=>[]);for(const I of u){const k=f.get(I.tabKey)??0,j=Math.min(k,v-1);w[j].push(I)}return w},[u,f,v]),M=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:d,normalizedGroupAssignments:f,numGroups:v,isSplitMode:S,groupedConvs:N,moveTabToGroup:p,closeGroup:x,handleResizeStart:y,splitTabRelative:g,clearAllSplits:M}}function ih({ides:e,sendDaemonCommand:t}){const r="0.9.43",n=o.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:Dc(d,r)).sort((d,h)=>Number(qs(h,r))-Number(qs(d,r))),[r,e]),a=o.useMemo(()=>n.some(d=>qs(d,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),m=o.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(S=>({...S,[d]:"done"})):u(S=>({...S,[d]:"error"}))}catch{u(v=>({...v,[d]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:m}}const Jc=80;function Lr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function ch(e){return{...e,createdAt:Lr(e.createdAt),updatedAt:Lr(e.updatedAt,e.createdAt),lastEventAt:Lr(e.lastEventAt,e.updatedAt||e.createdAt)}}function lh(e){const t=Aa(e);return t==="unknown:"?e.id:t}function dh(e){return[e.type,oc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function uh(e,t=Jc){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=lh(n),i=r.get(a);if(!i){r.set(a,n);continue}(n.updatedAt>i.updatedAt||n.updatedAt===i.updatedAt&&n.createdAt>i.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const i=a.updatedAt-n.updatedAt;return i!==0?i:a.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function mh(e,t){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?t.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=Zr(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const u=Lr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),m=dh({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(i==null?void 0:i.lastUpdated)||a.lastUpdated});n.push(ch({id:m,dedupKey:m,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:sc(a),preview:gm(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return uh(n)}function fh(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function ph(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Jc}=e,a=o.useMemo(()=>mh(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>fh(a),[a]);return{notifications:a,unreadCount:i}}function hh({notifications:e,sendDaemonCommand:t}){const r=o.useCallback(i=>{const c=e.find(u=>u.id===i),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=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=o.useCallback(i=>{const c=e.find(l=>l.id===i);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 rn(...e){const t=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();t.has(c)||(t.add(c),r.push(i))};for(const a of e){if(Array.isArray(a)){for(const i of a)n(i);continue}n(a)}return r}function xh(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 nn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=xh(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 bh(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 gh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function an(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=gh(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 i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.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(i,m.name)})).sort((m,d)=>m.name.localeCompare(d.name)):[];return{path:i,directories:u}}function yh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Go(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function vh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function wh({ides:e,conversations:t,onOpenSession:r}){const[n,a]=o.useState(null),i=o.useCallback(c=>{a(c)},[]);return o.useEffect(()=>{if(!n)return;const c=Go(n.workspacePath),l=e.find(m=>{var S,p,x,y;if(!m||m.type==="adhdev-daemon"||yh(m.daemonId||m.id)!==n.machineId||(tr(m)?"cli":gs(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 g=Go(m.workspace||m.runtimeWorkspaceLabel);return g?g===c:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((y=(x=(p=(S=m.activeChat)==null?void 0:S.messages)==null?void 0:p.at)==null?void 0:x.call(p,-1))==null?void 0:y.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const u=lc({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});u&&(a(null),r(u))},[t,e,r,n]),o.useEffect(()=>{if(!n)return;const c=window.setTimeout(()=>{a(l=>!l||l.startedAt!==n.startedAt?l:null)},45e3);return()=>window.clearTimeout(c)},[n]),{trackPendingLaunch:i}}function jh({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=o.useCallback(async(f,v)=>an(e,f,v),[e]),l=o.useCallback(async(f,v)=>{if(!v.trim())return{ok:!1,error:"Choose a workspace path first."};try{const S=await e(f,"workspace_add",{path:v.trim()});return S!=null&&S.success?{ok:!0}:{ok:!1,error:(S==null?void 0:S.error)||"Could not save workspace"}}catch(S){return{ok:!1,error:S instanceof Error?S.message:"Could not save workspace"}}},[e]),u=o.useCallback(async(f,v,S)=>{var p;try{const x={ideType:v,enableCdp:!0};(p=S==null?void 0:S.workspacePath)!=null&&p.trim()&&(x.workspace=S.workspacePath.trim());const y=await e(f,"launch_ide",x);return!(y!=null&&y.success)&&(y==null?void 0:y.success)!==void 0?{ok:!1,error:(y==null?void 0:y.error)||"Could not launch IDE"}:(t({machineId:f,kind:"ide",providerType:v,workspacePath:(S==null?void 0:S.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Could not launch IDE"}}},[e,t]),m=o.useCallback(async(f,v,S,p)=>{var y,g,N;const x=Date.now();try{const M={cliType:S};(y=p==null?void 0:p.workspacePath)!=null&&y.trim()?M.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(M.workspaceId=p.workspaceId),(g=p==null?void 0:p.resumeSessionId)!=null&&g.trim()&&(M.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(M.cliArgs=p.cliArgs),(N=p==null?void 0:p.initialModel)!=null&&N.trim()&&(M.initialModel=p.initialModel.trim());const w=await e(f,"launch_cli",M),I=(w==null?void 0:w.result)||w,k=(I==null?void 0:I.sessionId)||(I==null?void 0:I.id);return w!=null&&w.success&&k?(r(k),{ok:!0}):w!=null&&w.success?(t({machineId:f,kind:v,providerType:S,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:x}),{ok:!0}):{ok:!1,error:(w==null?void 0:w.error)||(I==null?void 0:I.error)||`Could not launch ${v.toUpperCase()} session`}}catch(M){return vh(M)?(t({machineId:f,kind:v,providerType:S,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:x}),{ok:!0}):{ok:!1,error:M instanceof Error?M.message:`Could not launch ${v.toUpperCase()} session`}}},[r,e,t]),d=o.useCallback(async(f,v)=>{if(!f||!v)return[];try{const S=await e(f,"list_saved_sessions",{providerType:v,kind:"cli",limit:30}),p=(S==null?void 0:S.result)??S;return Array.isArray(p==null?void 0:p.sessions)?p.sessions:[]}catch(S){return console.error("List saved sessions failed",S),[]}},[e]),h=o.useCallback(async f=>{await zc({conversation:n,mode:f,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:i})},[n,a,e,i]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineSavedSessions:d,setActiveCliViewMode:h}}function kh(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 Sh(e,t,r=Date.now()){return!e||!kh(t)?null:{tabKey:e,nonce:r}}function Nh({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,u]=o.useState(null),[m,d]=o.useState(null),h=o.useMemo(()=>{var x,y;if(!e){if(l){const g=t.find(N=>N.tabKey===l);if(g)return g}return r[0]}const p=n[a];if(p){const g=t.find(N=>N.tabKey===p);if(g)return g}return((x=i[a])==null?void 0:x[0])||((y=i[0])==null?void 0:y[0])},[t,l,a,n,i,e,r]),f=o.useCallback(p=>{u(p)},[]),v=o.useCallback(p=>{u(p.tabKey),c(x=>{const y=new URLSearchParams(x),g=vm(p);return g?y.set("activeTab",g):y.delete("activeTab"),y},{replace:!0})},[c]),S=o.useCallback((p,x)=>{const y=Sh(p,x);y&&d(y)},[]);return{activeConv:h,openDesktopConversation:v,requestScrollToBottom:S,scrollToBottomRequest:m,setDesktopActiveTab:f}}function Ch(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 Th(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&t&&t!==r),autoReadKey:i,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Mh({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=o.useRef(null),i=o.useRef(null),c=o.useRef(null),l=o.useRef(null),u=o.useRef(null);o.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),i.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const d=Or(e,r),h=Th({tabKey:e.tabKey,historySessionId:or(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Qt(e),liveState:d}),f=h.autoReadKey,v=Ch({autoReadKey:f,shouldMarkSeen:h.shouldMarkSeen,completedKey:a.current,pendingKey:i.current});if(!h.shouldMarkSeen){v.shouldCancelPending&&m(),a.current=f;return}if(!v.shouldSchedule)return;v.shouldCancelPending&&m();const S=()=>{if(document.visibilityState!=="visible"||a.current===f)return;a.current=f,i.current=null,c.current=null,l.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null);const x=h.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:x,completionMarker:h.completionMarker}).catch(()=>{})};if(i.current=v.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(S,1500);const x=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};u.current=x,document.addEventListener("visibilitychange",x);return}const p=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(S,800),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null))};u.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),o.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function Ih({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:u}){var T;const[m,d]=o.useState(!1),[h,f]=o.useState([]),[v,S]=o.useState(()=>pt()),[p,x]=o.useState(!1),[y,g]=o.useState(null),N=o.useRef(null),M=o.useMemo(()=>r||t||e,[e,r,t]),w=!!M&&Ze(M)&&!Ge(M),I=o.useMemo(()=>{if(!M||!w)return null;const L=M.daemonId||M.routeId||"",z=$t(M);return`${L}:${z}`},[M,w]),{isCreatingChat:k,isRefreshingHistory:j,handleSwitchSession:b,handleNewChat:B,handleRefreshHistory:R}=Xc({sendDaemonCommand:a,activeConv:M,chats:(T=n.find(L=>L.id===(M==null?void 0:M.routeId)))==null?void 0:T.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),P=o.useCallback(()=>{d(!0)},[]),F=o.useCallback(()=>{d(!1)},[]),U=o.useCallback(async()=>{if(!(!M||!w||p)){x(!0);try{const L=M.daemonId||M.routeId,z=$t(M),$=await a(L,"list_saved_sessions",{agentType:z,providerType:z,kind:"cli",limit:50}),E=($==null?void 0:$.result)??$;f(Array.isArray(E==null?void 0:E.sessions)?E.sessions:[])}catch(L){console.error("Refresh saved sessions failed",L),f([])}finally{x(!1)}}},[M,p,w,a]);o.useEffect(()=>{if(!m){N.current=null;return}if(!w){N.current=null,f([]),x(!1);return}!I||p||N.current!==I&&(N.current=I,U())},[U,m,p,w,I]);const W=o.useCallback(async L=>{if(!M||!w||!L.providerSessionId||!L.workspace)return;const z=M.daemonId||M.routeId,$=$t(M);try{g(L.providerSessionId);const E=await a(z,"launch_cli",{cliType:$,dir:L.workspace,resumeSessionId:L.providerSessionId,initialModel:Yi(L.summaryMetadata,"model",{preferShortValue:!0})||void 0}),V=(E==null?void 0:E.result)??E,q=typeof(V==null?void 0:V.sessionId)=="string"?V.sessionId:typeof(V==null?void 0:V.id)=="string"?V.id:"";q&&u(ve=>{const ne=new URLSearchParams(ve);return ne.set("activeTab",q),ne},{replace:!0}),F()}catch(E){console.error("Resume saved session failed",E)}finally{g(null)}},[F,M,w,a,u]);return{historyModalOpen:m,openHistoryModal:P,closeHistoryModal:F,historyTargetConv:M,isSavedSessionHistoryTarget:w,isHistoryCreatingChat:k,isHistoryRefreshingHistory:j,handleHistorySwitchSession:b,handleHistoryNewChat:B,handleHistoryRefresh:R,savedHistorySessions:h,savedHistoryFilters:v,setSavedHistoryFilters:S,isSavedHistoryLoading:p,resumingSavedHistorySessionId:y,handleRefreshSavedHistory:U,handleResumeSavedHistorySession:W}}function Ah({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,m]=o.useState(null),[d,h]=o.useState(null),f=o.useMemo(()=>{if(e||!n)return null;const y=l(n);return y&&!Ze(y)&&!Ge(y)?y:null},[e,n,l]),v=o.useMemo(()=>{const y=u==null?void 0:u.routeId;if(!y)return null;const g=u!=null&&u.tabKey?i.find(N=>N.tabKey===u.tabKey):a?i.find(N=>N.tabKey===a):null;return(g==null?void 0:g.routeId)===y?g:_t(i,y)},[i,u,a]),S=o.useMemo(()=>{if(v)return c.find(y=>y.id===v.routeId)},[c,v]);o.useEffect(()=>{f&&(m({routeId:f.routeId,tabKey:No(f)}),h(f),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,f]);const p=o.useCallback(y=>{y&&(m({routeId:y.routeId,tabKey:No(y)}),h(y))},[]),x=o.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:v,remoteDialogIdeEntry:S,remoteDialogActiveConv:d,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:x}}function Lh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:u,sendDaemonCommand:m}){const{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:v,openRemoteDialog:S,closeRemoteDialog:p}=Ah({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[x,y]=o.useState(!1),[g,N]=o.useState(null),M=o.useCallback(async k=>{const j=k||u;!j||!Ze(j)&&!Ge(j)||(N(j),y(!0))},[u]),w=o.useCallback(()=>{y(!1),N(null)},[]),I=o.useCallback(async k=>{const j=g||u;if(!j||!Ze(j)&&!Ge(j)){w();return}y(!1);try{const b=$t(j),B=j.routeId||j.daemonId||"";await m(B,"stop_cli",{cliType:b,targetSessionId:j.sessionId,mode:k})}catch(b){console.error("Stop CLI failed:",b)}finally{N(null)}},[u,w,g,m]);return{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:v,openRemoteDialog:S,closeRemoteDialog:p,cliStopDialogOpen:x,cliStopTargetConv:g,requestCliStop:M,cancelCliStop:w,confirmCliStop:I}}function Qc(){return"select_session"}function Rh(){return"open_panel"}function _h({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Ph(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function qo(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Yo(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function qa(e){return e instanceof Error?e.message:String(e||"")}function Xo(e){const t=qa(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Jo(e,t){const r=qa(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,i]=o.useState(!1),[c,l]=o.useState(!1),[u,m]=o.useState(null),d=o.useRef(!1),h=o.useRef(null);o.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const f=o.useCallback(async x=>{if(!t)return!1;const y=x.trim(),g=Ra(t);if(_h({hasMessage:!!y,blockedMessage:g,sendInFlight:d.current}))return g&&m(g),!1;const N=Date.now(),M={tabKey:t.tabKey,message:y,timestamp:N};if(Ph(h.current,M))return m(null),!0;d.current=!0,l(!0),m(null),h.current=M;try{const w=sr(t);if(!w)return h.current=qo(h.current,M),m("Unable to send message right now."),!1;const I=await e(w,"send_chat",{message:y,...ws(t)}),k=Yo(I);if(k!=null&&k.deduplicated)return m(null),!0;if((k==null?void 0:k.sent)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");if((k==null?void 0:k.success)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");return m(null),!0}catch(w){const I=qa(w);return I.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",I):console.warn("Send blocked/failed",w),h.current=qo(h.current,M),m(Km(w)),!1}finally{d.current=!1,l(!1)}},[t,e]),v=o.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(x){console.error("Relaunch failed",x)}},[t,e]),S=o.useCallback(async x=>{if(t)try{const g=(t.modalButtons||[]).indexOf(x),N=x.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),M=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),w=sr(t);if(!w)return;const I=await e(w,"resolve_action",{button:x,action:M?"approve":"reject",...g>=0&&{buttonIndex:g},...ws(t)}),k=Yo(I);k.success||r(j=>[...j,{routeId:t.tabKey,text:Jo(x,k==null?void 0:k.error),timestamp:Date.now()}])}catch(y){Xo(y)||console.error("[ModalButton] Error:",y),r(g=>[...g,{routeId:t.tabKey,text:Xo(y)?Jo(x,y):`❌ **${x}** error`,timestamp:Date.now()}])}},[t,e,r]),p=o.useCallback(async()=>{if(!(!t||a)){i(!0);try{await e(t.routeId,Rh(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(x){console.error("Focus agent failed",x)}finally{i(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:u,isFocusingAgent:a,handleSendChat:f,handleRelaunch:v,handleModalButton:S,handleFocusAgent:p}}function In(e,t=!0){return(e??!0)&&t}const Ya=o.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d=null,handleFocusAgent:h,isFocusingAgent:f,actionLogs:v,userName:S,scrollToBottomRequestNonce:p,isInputActive:x=!0,isVisible:y=!0}){const g=n,N=!n,M=In(y,g),w=In(y,N),I=In(y),k=Oc(t),j=k.status||k.modalMessage||k.modalButtons?{...t,...k.status?{status:k.status}:{},...k.modalMessage!==void 0?{modalMessage:k.modalMessage}:{},...k.modalButtons!==void 0?{modalButtons:k.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Ui,{activeConv:j,onModalButton:c}),j.transport!=="pty"&&j.transport!=="acp"&&j.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(Zs,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:l,children:"Relaunch with CDP"})]})}):null,j.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:g?"visible":"hidden",pointerEvents:g?"auto":"none"},children:s.jsx(yf,{activeConv:j,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,isVisible:M,isInputActive:x&&M})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:N?"visible":"hidden",pointerEvents:N?"auto":"none"},children:s.jsx(ia,{activeConv:j,ideEntry:a,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:f,actionLogs:v,userName:S,scrollToBottomRequestNonce:p,isInputActive:x&&w,isVisible:w})})]}):s.jsx(ia,{activeConv:j,ideEntry:a,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:f,actionLogs:v,userName:S,scrollToBottomRequestNonce:p,isInputActive:x&&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 Dh({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:m,onOpenNativeConversation:d,onOpenMachine:h,onOpenHistory:f,onOpenRemote:v,onHideConversation:S,onStopCli:p,cliViewMode:x,onSetCliViewMode:y,handleSendChat:g,handleFocusAgent:N,handleModalButton:M,handleRelaunch:w}){const I=o.useRef(null),k=Ze(e)&&!t,j=k&&x==="terminal",b=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 ${b} 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(ya,{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:ot(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(dc,{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:[k&&x&&s.jsx(Da,{mode:x,onChange:y,compact:!0}),k&&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(vt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(va,{size:14})}),!t&&!k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),type:"button",children:s.jsx(St,{size:14})}),S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Close chat",children:s.jsx(vt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(Ya,{activeConv:e,clearToken:0,isCliTerminal:j,ideEntry:n,terminalRef:I,handleModalButton:M,handleRelaunch:w,handleSendChat:g,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:N,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const An={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 Eh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Zc(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(Eh())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(An[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!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:An[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:An[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 el({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:St},{key:"chats",label:"Chats",icon:Wt}];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:i})=>{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(i,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function wr({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 ps({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 Os({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 jr({item:e,type:t,getAvatarText:r,onOpenConversation:n}){const a=t==="needs_attention"||t==="task_complete",i=t==="working",c=t==="earlier",l=t==="task_complete",{isReconnecting:u,isConnecting:m}=As(e.conversation),d=ot(e.conversation),h=ls(e.conversation),f=gc(e.conversation,{requiresAction:t==="needs_attention"}),v=a?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",S=a?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"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",p=c?"text-text-secondary":"text-text-primary",x=c?"text-text-muted":"text-text-secondary",y=c?"text-text-secondary opacity-80":"text-text-muted",g=c?"text-text-muted opacity-80":"text-text-muted",N=!i&&!l,M="text-[color:var(--status-warning)]";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] ${v}`,onClick:()=>n(e.conversation),type:"button",children:[a||i?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 ${S}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(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 truncate tracking-tight ${p}`,children:d}),N&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${g}`,children:Fi(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${x}`,children:[h,u?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${M} animate-pulse`,children:"Reconnecting…"})]}):m?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):f==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:M,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,children:e.preview})]}),a&&!l&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&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"}),i&&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 Qo({size:e=32,label:t}){return s.jsxs("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}}),t&&s.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:t})]})}function $h({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:m,onShowAllHidden:d,onOpenNewSession:h,onOpenMachine:f,onOpenSettings:v,onSectionChange:S,wsStatus:p="connected",isStandalone:x=!1}){const y=p==="disconnected"||p==="reconnecting"||p==="offline"||p==="auth_failed",g=c.length>0,N=t.length>0||r.length>0||n.length>0||a.length>0,M=e==="machines"?"Machines":"Chats",w=x?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",I=x?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";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 ${w}`,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:M}),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(Jr,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:v,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(Xr,{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] ${I}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:y?s.jsx(Os,{icon:s.jsx(Qo,{label:"Reconnecting…"}),title:p==="offline"?"Network offline":p==="auth_failed"?"Session expired":"Reconnecting",subtitle:p==="offline"?"Waiting for network…":p==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(Os,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:x?"Waiting for your daemon":"Connect your machines",subtitle:x?"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:!x&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Zc,{})})}):s.jsx(ps,{children:c.map((k,j)=>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] ${j>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(k.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(k.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:k.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:k.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[k.unread," new"]}):k.total>0?`${k.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:k.subtitle}),k.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[k.total," chat",k.total!==1?"s":"",k.unread>0?` · ${k.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},k.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(wr,{title:"Needs attention",className:"mb-0"}),s.jsx(ps,{children:t.map((k,j)=>s.jsx("div",{className:j>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},k.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(wr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(ps,{children:r.map((k,j)=>s.jsx("div",{className:j>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"task_complete",getAvatarText:l,onOpenConversation:u})},k.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(wr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(ps,{children:n.map((k,j)=>s.jsx("div",{className:j>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"working",getAvatarText:l,onOpenConversation:u})},k.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(wr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(ps,{children:a.map((k,j)=>s.jsx("div",{className:j>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"earlier",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))}):N?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):y?s.jsx(Os,{icon:s.jsx(Qo,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):g?s.jsx(Os,{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(Wt,{size:20})}),title:"No conversations yet",subtitle:wc,children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"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(Os,{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"&&i.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:d,children:"Restore all"})]}),s.jsx(ps,{className:"bg-bg-secondary/25",children:i.map((k,j)=>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 ${j>0?"border-t border-border-subtle/70":""}`,onClick:()=>m(k),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(ot(k))}),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:ot(k)}),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:ls(k)}),s.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},k.tabKey))})]})]}),e==="chats"&&h&&N&&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:h,"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(el,{section:e,onSectionChange:S})]})}function Bh(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 tl(e){const t=[e.workspace||"Workspace unknown"],r=cs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Bh(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function cn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:m}){const[d,h]=o.useState(r);o.useEffect(()=>{h(r)},[r]);const f=bh(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(vt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!f||a||u(f)},disabled:!f||a,children:[s.jsx(ya,{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:S=>h(S.target.value),onKeyDown:S=>{S.key!=="Enter"||!v||a||(S.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…"}):i?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):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(S=>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(S.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(Ss,{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:S.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:S.path})]})]},S.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 Xa({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:m,argsValue:d,onArgsChange:h,showModelInput:f,modelValue:v,onModelChange:S,historyProviderNode:p,onConfirm:x,onCancel:y}){const g=n==null?void 0:n.find(N=>N.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:y,"aria-label":"Close launch confirmation",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&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:N=>i(N.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(N=>s.jsx("option",{value:N.key,children:N.label},N.key))}),(g==null?void 0:g.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:g.description})]}),p,r.map(N=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:N.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${N.value}`)),f&&S&&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:N=>S(N.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:N=>h(N.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:y,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:x,disabled:u,children:[s.jsx(ja,{size:14}),u?l:c]})]})]})})}function Zo(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ns(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${Zo(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&&i.push({key:`custom:${c}`,label:Zo(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(m=>m.key===u))return{options:i,selectedKey:u}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Kh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Oh(e){return[Kh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Wh(e){return e.lastLaunchedAt?Qr(e.lastLaunchedAt):""}function sl(e){return{metaText:Oh(e),updatedLabel:Wh(e)}}function Ln(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Hh({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var Ve,ht,ut,ft;const c=ir(),[l,u]=o.useState(!1),m=(((Ve=e.detectedIdes)==null?void 0:Ve.length)||0)>0,d=o.useMemo(()=>(e.workspaces||[]).map(Ce=>({id:Ce.id,path:Ce.path,label:Ce.label})),[e]),h=e.defaultWorkspaceId||null,[f,v]=o.useState(h||((ht=d[0])==null?void 0:ht.id)||""),[S,p]=o.useState(""),[x,y]=o.useState(""),[g,N]=o.useState([]),[M,w]=o.useState(!1),[I,k]=o.useState(""),[j,b]=o.useState(!1),[B,R]=o.useState(Ln(m,t.length,r.length)),P=o.useRef(null),[F,U]=o.useState(null),W=o.useRef("__home__"),[T,L]=o.useState("__home__"),[z,$]=o.useState(""),[E,V]=o.useState(""),[q,ve]=o.useState(""),[ne,pe]=o.useState([]),[ie,ge]=o.useState(()=>pt().textQuery),[be,H]=o.useState(()=>pt().workspaceQuery),[Q,re]=o.useState(()=>pt().modelQuery),[he,ue]=o.useState(()=>pt().resumableOnly),[je,ce]=o.useState(()=>pt().sortMode),[xe,Z]=o.useState(!1),[ae,te]=o.useState(!1),Y=o.useRef(null),X=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const le=f==="__custom__"?S.trim():((ut=d.find(Ce=>Ce.id===f))==null?void 0:ut.path)||"",D=f==="__custom__"&&!!le&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),oe=f!=="__custom__"&&((ft=d.find(Ce=>Ce.id===f))==null?void 0:ft.path)||"",J=o.useMemo(()=>(e.recentLaunches||[]).map(Ce=>Ce.workspace),[e]),we=o.useCallback(async Ce=>{w(!0),k("");try{const He=await a(Ce);y(He.path),p(He.path),N(He.directories)}catch(He){k(He instanceof Error?He.message:"Could not load folder")}finally{w(!1)}},[a]),Ne=o.useCallback(()=>{var He;v("__custom__"),b(!0);const Ce=nn(e.platform,rn(S.trim(),oe,J,e.defaultWorkspacePath,(He=d.find(Qe=>Qe.id===h))==null?void 0:He.path,d.map(Qe=>Qe.path)));we(Ce)},[S,h,we,J,oe,e.platform,d]),Ae=o.useCallback(Ce=>{if(Ce!=null&&Ce.workspaceId){v(Ce.workspaceId),p("");return}if(Ce!=null&&Ce.workspacePath){v("__custom__"),p(Ce.workspacePath);return}v(""),p("")},[]),Me=o.useCallback(Ce=>{if(v(Ce),Ce==="__custom__"){Ne();return}p("")},[Ne]),Ue=o.useCallback(Ce=>{v("__custom__"),p(Ce)},[]),We=o.useCallback((Ce,He)=>{P.current=He,W.current=Ce.selectedWorkspaceKey||"__home__",L(Ce.selectedWorkspaceKey||"__home__"),$(Ce.initialArgs||""),V(Ce.initialModel||""),ve(""),pe([]);const Qe=Ce.providerType?`${e.id}:${Ce.providerType}`:null;if(Cf(X.current,Qe)){const nt=pt();ge(nt.textQuery),H(nt.workspaceQuery),re(nt.modelQuery),ue(nt.resumableOnly),ce(nt.sortMode)}X.current=Qe,U(Ce),Ce.providerType&&i&&(Z(!0),i(Ce.providerType).then(nt=>pe(nt||[])).catch(nt=>console.warn("Failed to load saved sessions",nt)).finally(()=>Z(!1)))},[i,e.id]),Be=o.useMemo(()=>jc(ne,{textQuery:ie,workspaceQuery:be,modelQuery:Q,resumableOnly:he,sortMode:je}),[Q,he,ne,je,ie,be]);o.useEffect(()=>{q&&(Be.some(Ce=>Ce.providerSessionId===q)||ve(""))},[Be,q]);const Ye=o.useCallback(()=>{P.current&&(te(!0),P.current().finally(()=>{P.current=null,te(!1),U(null)}))},[]),Xe=o.useCallback(()=>{P.current=null,U(null)},[]),Je=o.useCallback(Ce=>{W.current=Ce,L(Ce)},[]);return o.useEffect(()=>{var Ce;Y.current!==e.id&&(Y.current=e.id,v(h||((Ce=d[0])==null?void 0:Ce.id)||"__custom__"),p(""),y(""),N([]),k(""),b(!1),ge(pt().textQuery),H(pt().workspaceQuery),re(pt().modelQuery),ue(pt().resumableOnly),ce(pt().sortMode),X.current=null,R(Ln(m,t.length,r.length)))},[r.length,t.length,h,m,e.id,d]),o.useEffect(()=>{var Ce;f!=="__custom__"&&(f&&d.some(He=>He.id===f)||v(h||((Ce=d[0])==null?void 0:Ce.id)||"__custom__"))},[h,f,d]),o.useEffect(()=>{B==="ide"&&m||B==="cli"&&t.length>0||B==="acp"&&r.length>0||R(Ln(m,t.length,r.length))},[B,r.length,t.length,m]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:m,workspaceRows:d,defaultWorkspaceId:h,workspaceChoice:f,customWorkspacePath:S,browseCurrentPath:x,browseDirectories:g,browseBusy:M,browseError:I,browseDialogOpen:j,activeLauncherKind:B,launchConfirm:F,launchConfirmWorkspaceKeyRef:W,launchConfirmWorkspaceKey:T,launchConfirmArgs:z,launchConfirmModel:E,launchConfirmResumeId:q,launchConfirmSavedSessions:ne,launchConfirmTextFilter:ie,launchConfirmWorkspaceFilter:be,launchConfirmModelFilter:Q,launchConfirmResumableOnly:he,launchConfirmSortMode:je,filteredLaunchConfirmSavedSessions:Be,launchConfirmSessionsLoading:xe,launchConfirmBusy:ae,resolvedWorkspacePath:le,canCreateMissingWorkspace:D,openBrowseDialog:Ne,loadBrowsePath:we,handleWorkspaceChoiceChange:Me,chooseCustomWorkspacePath:Ue,setCustomWorkspacePath:p,setBrowseDialogOpen:b,setActiveLauncherKind:R,openLaunchConfirm:We,handleConfirmLaunch:Ye,closeLaunchConfirm:Xe,setWorkspaceSelectionFromOption:Ae,setLaunchConfirmWorkspaceKeyAndSync:Je,setLaunchConfirmArgs:$,setLaunchConfirmModel:V,setLaunchConfirmResumeId:ve,setLaunchConfirmTextFilter:ge,setLaunchConfirmWorkspaceFilter:H,setLaunchConfirmModelFilter:re,setLaunchConfirmResumableOnly:ue,setLaunchConfirmSortMode:ce}}function Fh({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:m,showBottomNav:d,onBack:h,onSectionChange:f,onOpenConversation:v,onOpenRecent:S,onOpenMachineDetails:p,onMachineUpgrade:x,onLaunchDetectedIde:y,onAddWorkspace:g,onBrowseDirectory:N,onLaunchWorkspaceProvider:M,onListSavedSessions:w}){const I=T=>T==="ide"?"IDE":T==="cli"?"CLI":"ACP",k=r.slice(0,4),j=t.slice(0,3),b=Hh({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:w}),B=o.useMemo(()=>k.map(T=>{const{metaText:L,updatedLabel:z}=sl(T);return{key:`recent-launch:${T.id}`,primary:T.label,secondary:L,updatedLabel:z,onClick:()=>{const{options:$,selectedKey:E}=ns({machine:{workspaces:b.workspaceRows,defaultWorkspaceId:b.defaultWorkspaceId},currentWorkspacePath:T.workspace});b.openLaunchConfirm({title:T.kind==="ide"?es("restart-ide",T.label):T.providerSessionId?Ba(T.label):es("start-fresh",T.label),description:T.kind==="ide"?ts("restart-ide"):T.providerSessionId?Ka():ts("start-fresh"),confirmLabel:T.kind==="ide"?Cs("restart-ide"):T.providerSessionId?zr(!0):Cs("start-fresh"),busyLabel:T.kind==="ide"?Ts("restart-ide"):T.providerSessionId?Ea(!0):Ts("start-fresh"),workspaceOptions:$,selectedWorkspaceKey:E,details:[{label:"Mode",value:I(T.kind)},...T.providerType?[{label:"Provider",value:T.providerType}]:[]]},async()=>{const V=$.find(q=>q.key===b.launchConfirmWorkspaceKeyRef.current);b.setWorkspaceSelectionFromOption(V),await S({...T,workspace:(V==null?void 0:V.workspacePath)??null})})}}}),[b,S,k]),R=o.useMemo(()=>j.map(T=>({key:`recent-chat:${T.conversation.tabKey}`,primary:ot(T.conversation),secondary:hf(T.conversation,{timestampLabel:T.timestamp?Fi(T.timestamp):null}),unread:T.unread,onClick:()=>v(T.conversation)})),[v,j]),P=b.showAllRecent?B:B.slice(0,4),F=B.length>0,U=R.length>0,W=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 ${W} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:s.jsx(ya,{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:Tt(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[U&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:R.map(T=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${T.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:T.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:T.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:T.secondary})]},T.key))})]}),F&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:P.map(T=>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:T.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:T.primary}),T.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:T.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:T.secondary})]},T.key))}),B.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:()=>b.setShowAllRecent(T=>!T),children:b.showAllRecent?"Show fewer":`Show ${B.length-4} more`})})]}),(b.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:b.workspaceChoice,onChange:T=>b.handleWorkspaceChoiceChange(T.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:b.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[b.workspaceRows.map(T=>s.jsxs("option",{value:T.id,children:[T.id===b.defaultWorkspaceId?"⭐ ":"",en(T.path,T.label)||T.path]},T.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),b.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(Ss,{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:b.resolvedWorkspacePath||b.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:b.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:()=>{b.resolvedWorkspacePath&&g(b.resolvedWorkspacePath)},disabled:!b.resolvedWorkspacePath||b.browseBusy,children:"Save as workspace"})]})]}),b.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:b.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[b.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${b.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:()=>b.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${b.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:()=>b.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${b.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:()=>b.setActiveLauncherKind("acp"),children:"ACP"})]}),b.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:b.activeLauncherKind==="ide"?"Choose an IDE":b.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:b.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(T=>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:L,selectedKey:z}=ns({machine:{workspaces:b.workspaceRows,defaultWorkspaceId:b.defaultWorkspaceId},currentWorkspaceId:b.workspaceChoice!=="__custom__"?b.workspaceChoice:null,currentWorkspacePath:b.resolvedWorkspacePath});b.openLaunchConfirm({title:`Launch ${T.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:L,selectedWorkspaceKey:z,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:T.name}]},async()=>{const $=L.find(E=>E.key===b.launchConfirmWorkspaceKeyRef.current);b.setWorkspaceSelectionFromOption($),y(T.type,{workspacePath:($==null?void 0:$.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:T.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:b.resolvedWorkspacePath||"Use selected workspace"})]},T.type)):(b.activeLauncherKind==="cli"?n:a).map(T=>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 L=b.activeLauncherKind==="cli"?"cli":"acp",{options:z,selectedKey:$}=ns({machine:{workspaces:b.workspaceRows,defaultWorkspaceId:b.defaultWorkspaceId},currentWorkspaceId:b.workspaceChoice!=="__custom__"?b.workspaceChoice:null,currentWorkspacePath:b.resolvedWorkspacePath});b.openLaunchConfirm({title:`Launch ${T.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${L.toUpperCase()}`,workspaceOptions:z,selectedWorkspaceKey:$,details:[{label:"Mode",value:L.toUpperCase()},{label:"Provider",value:T.displayName}],showArgsInput:!0,showModelInput:L==="acp",initialArgs:"",initialModel:"",providerType:T.type},async()=>{const E=z.find(V=>V.key===b.launchConfirmWorkspaceKeyRef.current);b.setWorkspaceSelectionFromOption(E),M(L,T.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.workspacePath)??null,args:b.launchConfirmArgs,model:b.launchConfirmModel,resumeSessionId:b.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[T.icon?`${T.icon} `:"",T.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:b.resolvedWorkspacePath||"Use selected workspace"})]},T.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,b.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:()=>g(b.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:[i&&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:x,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"})]})]})]})]}),b.browseDialogOpen&&s.jsx(cn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:b.browseCurrentPath,directories:b.browseDirectories,busy:b.browseBusy,error:b.browseError,confirmLabel:"Use this folder",onClose:()=>b.setBrowseDialogOpen(!1),onNavigate:T=>{b.loadBrowsePath(T)},onConfirm:T=>{b.chooseCustomWorkspacePath(T),b.setBrowseDialogOpen(!1)}}),b.launchConfirm&&s.jsx(Xa,{title:b.launchConfirm.title,description:b.launchConfirm.description,details:b.launchConfirm.details,workspaceOptions:b.launchConfirm.workspaceOptions,selectedWorkspaceKey:b.launchConfirmWorkspaceKey,onWorkspaceChange:b.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:b.launchConfirm.providerType?zr(!!b.launchConfirmResumeId):b.launchConfirm.confirmLabel,busyLabel:b.launchConfirm.providerType?void 0:b.launchConfirm.busyLabel,busy:b.launchConfirmBusy,showArgsInput:b.launchConfirm.showArgsInput,argsValue:b.launchConfirmArgs,onArgsChange:b.setLaunchConfirmArgs,showModelInput:b.launchConfirm.showModelInput,modelValue:b.launchConfirmModel,onModelChange:b.setLaunchConfirmModel,historyProviderNode:b.launchConfirm.providerType&&(b.launchConfirmSessionsLoading||b.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"}),b.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:$a()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:b.launchConfirmTextFilter,onChange:T=>b.setLaunchConfirmTextFilter(T.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:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:b.launchConfirmWorkspaceFilter,onChange:T=>b.setLaunchConfirmWorkspaceFilter(T.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:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:b.launchConfirmModelFilter,onChange:T=>b.setLaunchConfirmModelFilter(T.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:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),s.jsxs("select",{value:b.launchConfirmSortMode,onChange:T=>b.setLaunchConfirmSortMode(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.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:b.launchConfirmResumableOnly,onChange:T=>b.setLaunchConfirmResumableOnly(T.target.checked),disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:b.launchConfirmResumeId,onChange:T=>b.setLaunchConfirmResumeId(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:If()}),b.filteredLaunchConfirmSavedSessions.map(T=>s.jsxs("option",{value:T.providerSessionId,disabled:!T.canResume,children:[T.title||T.providerSessionId," ",T.canResume?"":"(workspace missing)"]},T.providerSessionId))]}),!b.launchConfirmSessionsLoading&&b.launchConfirmSavedSessions.length>0&&b.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),b.launchConfirmResumeId&&(()=>{const T=b.filteredLaunchConfirmSavedSessions.find(z=>z.providerSessionId===b.launchConfirmResumeId);if(!T)return null;const L=tl(T);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:L.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:L.providerSessionId}),s.jsx("div",{className:"mt-1",children:L.metaLine}),L.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:L.updatedLabel}),L.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:L.preview})]})})()]}),onConfirm:b.handleConfirmLaunch,onCancel:b.closeLaunchConfirm}),d&&s.jsx(el,{section:m,onSectionChange:f})]})}function Rr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Uh(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:Rr(e)}function zh(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 Vh(e,t){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:cs(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,m,d;const a=tr(n)?"cli":gs(n)?"acp":"ide",i=cs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(tr(n)?n.cliName||n.type:gs(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:gs(n)?i||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 Gh(e,t){const r=new Map;for(const n of t){const a=ms(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((h,f)=>f.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=ea(n),u=a.filter(h=>h.unread||h.requiresAction).length,m=zh(n),d=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Tt(n,{fallbackId:n.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?xf(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const i=n.latestTimestamp||n.fallbackActivityAt||0,c=a.latestTimestamp||a.fallbackActivityAt||0;return c!==i?c-i:n.label.localeCompare(a.label)})}function qh(e){return e==="chat"}function kr(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 Yh({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:v,setSelectedTabKey:S,setScreen:p,setSelectedMachineId:x,setSection:y,setMachineBackTarget:g,resetMachineAction:N}){const M=o.useRef(null),w=o.useCallback(I=>{if(!(I!=null&&I.sessionId))return;const k=Or(I,c),j=Math.max(Date.now(),Qt(I),k.lastUpdated||0);kr("mark_read:start",{tabKey:I.tabKey,sessionId:I.sessionId,displayPrimary:ot(I),inboxBucket:k.inboxBucket,unread:k.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:Qt(I),readAt:j}),l(ms(I)||I.routeId,"mark_session_seen",{sessionId:I.sessionId,providerSessionId:I.providerSessionId,seenAt:j,completionMarker:k.completionMarker}).then(b=>{kr("mark_read:result",{tabKey:I.tabKey,sessionId:I.sessionId,result:b})}).catch(b=>{kr("mark_read:error",{tabKey:I.tabKey,sessionId:I.sessionId,error:b instanceof Error?b.message:String(b)})})},[c,l]);return o.useEffect(()=>{var k;if(!n){qh(i)&&p("inbox"),S(((k=e[0])==null?void 0:k.tabKey)||null),M.current=null;return}if(i!=="chat"){M.current=null;return}const I=`${n.tabKey}:${n.sessionId||""}`;M.current!==I&&(M.current=I,w(n))},[e,w,i,n,p,S]),o.useEffect(()=>{if(!u)return;const I=e.find(k=>k.tabKey===u);I&&(S(I.tabKey),p("chat"),m==null||m())},[e,m,u,p,S]),o.useEffect(()=>{if(!d)return;const I=t.find(k=>k.id===d);I&&(x(I.id),N(),y("machines"),g("inbox"),p("machine"),h==null||h())},[t,h,d,N,g,p,y,x]),o.useEffect(()=>{f&&(y(f),p("inbox"),v==null||v())},[v,f,p,y]),o.useEffect(()=>{const I=r.filter(k=>k.inboxBucket==="task_complete"||k.unread);I.length!==0&&kr("inbox_state",{screen:i,selectedTabKey:a,items:I.map(k=>{const j=Or(k.conversation,c);return{liveState:j,tabKey:k.conversation.tabKey,sessionId:k.conversation.sessionId,displayPrimary:ot(k.conversation),serverBucket:j.inboxBucket,computedBucket:k.inboxBucket,serverUnread:j.unread,computedUnread:k.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:Qt(k.conversation)}})})},[r,c,i,a]),{markConversationRead:w}}function Xh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ei(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Jh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Qh({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,m]=o.useState(null),d=o.useCallback(()=>{i("idle"),l(""),m(null)},[]),h=o.useCallback(async(g,N,M)=>{var w;try{i("loading"),l(`Launching ${N}…`);const I={ideType:N,enableCdp:!0};(w=M==null?void 0:M.workspacePath)!=null&&w.trim()&&(I.workspace=M.workspacePath.trim()),await e(g,"launch_ide",I),i("done"),l(`${N} launch requested`)}catch(I){i("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),f=o.useCallback(async(g,N,M)=>{if(N.trim())try{i("loading"),l(M!=null&&M.createIfMissing?"Creating folder…":"Saving workspace…");const w=await e(g,"workspace_add",{path:N.trim(),createIfMissing:(M==null?void 0:M.createIfMissing)===!0});if(w!=null&&w.success){i("done"),l(M!=null&&M.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((w==null?void 0:w.error)||"Could not save workspace")}catch(w){i("error"),l(w instanceof Error?w.message:"Could not save workspace")}},[e]),v=o.useCallback(async g=>{var N,M,w,I,k,j;try{i("loading"),l("Starting daemon upgrade…");const b=await e(g,"daemon_upgrade",{});if((N=b==null?void 0:b.result)!=null&&N.alreadyLatest){i("done"),l(`Already on v${((M=b==null?void 0:b.result)==null?void 0:M.version)||"latest"}.`);return}if((w=b==null?void 0:b.result)!=null&&w.upgraded||(I=b==null?void 0:b.result)!=null&&I.success){i("done"),l(`Upgrade to v${((k=b==null?void 0:b.result)==null?void 0:k.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((j=b==null?void 0:b.result)==null?void 0:j.error)||"Upgrade failed")}catch(b){i("error"),l(b instanceof Error?b.message:"Upgrade failed")}},[e]),S=o.useCallback(async(g,N,M,w)=>{var j,b,B;const I=Date.now(),k={machineId:g,kind:N,providerType:M,workspaceId:(w==null?void 0:w.workspaceId)||null,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:I};try{i("loading"),l(`Launching ${M}…`),m(k);const R={cliType:M};(j=w==null?void 0:w.workspacePath)!=null&&j.trim()?R.dir=w.workspacePath.trim():w!=null&&w.workspaceId&&(R.workspaceId=w.workspaceId),w!=null&&w.resumeSessionId&&(R.resumeSessionId=w.resumeSessionId),(b=w==null?void 0:w.args)!=null&&b.trim()&&(R.cliArgs=w.args.trim().split(/\s+/).filter(Boolean)),(B=w==null?void 0:w.model)!=null&&B.trim()&&(R.initialModel=w.model.trim());const P=await e(g,"launch_cli",R),F=(P==null?void 0:P.result)||P,U=(F==null?void 0:F.sessionId)||(F==null?void 0:F.id);if(P!=null&&P.success&&U){m(null),i("done"),l(`${M} launched`),t(zt(U));return}if(P!=null&&P.success){i("loading"),l(`${M} launch requested — waiting for session…`);return}m(null),i("error"),l((P==null?void 0:P.error)||(F==null?void 0:F.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(R){if(Jh(R)){i("loading"),l(`${M} launch requested — waiting for session…`);return}m(null),i("error"),l(R instanceof Error?R.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),p=o.useCallback(async(g,N)=>{try{const M=await e(g,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),w=(M==null?void 0:M.result)??M;return Array.isArray(w==null?void 0:w.sessions)?w.sessions:[]}catch(M){return console.error("Failed to list saved sessions on mobile:",M),[]}},[e]),x=o.useCallback(async(g,N)=>an(e,g,N),[e]);o.useEffect(()=>{if(!u)return;const g=ei(u.workspacePath),N=r.find(w=>{var R,P,F,U;if(!w||w.type==="adhdev-daemon"||Xh(w.daemonId||w.id)!==u.machineId||(w.transport==="acp"?"acp":w.transport==="pty"?"cli":null)!==u.kind||String(w.agentType||w.type||"")!==u.providerType)return!1;const b=String(w.providerSessionId||"");if(u.resumeSessionId&&b)return b===u.resumeSessionId;if(g){const W=ei(w.workspace||w.runtimeWorkspaceLabel);return W?W===g:!1}return Number(w.lastUpdated||w._lastUpdate||w.timestamp||((U=(F=(P=(R=w.activeChat)==null?void 0:R.messages)==null?void 0:P.at)==null?void 0:F.call(P,-1))==null?void 0:U.timestamp)||0)>=u.startedAt-5e3});if(!N)return;const M=lc({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});M&&(m(null),i("done"),l(`${u.providerType} launched`),t(zt(M)))},[n,r,t,u]),o.useEffect(()=>{if(!u)return;const g=window.setTimeout(()=>{m(N=>!N||N.startedAt!==u.startedAt?N:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(g)},[u]);const y=o.useCallback(async(g,N)=>{if(N.kind==="ide"&&N.providerType){await h(g,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await S(g,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[h,S]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:h,handleAddWorkspace:f,handleMachineUpgrade:v,handleLaunchWorkspaceProvider:S,handleListSavedSessions:p,handleBrowseDirectory:x,handleOpenRecent:y}}function Zh({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:m}){const d=o.useCallback(y=>{i(y.tabKey),c("chat"),n(y)},[n,c,i]),h=o.useCallback(y=>{const g=e.find(N=>N.routeId===y.routeId&&N.streamSource==="native");g&&(i(g.tabKey),c("chat"),n(g))},[e,n,c,i]),f=o.useCallback(()=>{n(t),c("inbox")},[n,t,c]),v=o.useCallback((y,g="inbox")=>{l(y),a(),u("machines"),m(g),c("machine")},[a,m,c,u,l]),S=o.useCallback(y=>{const g=ms(y);g&&v(g,"chat")},[v]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),x=o.useCallback(y=>{u(y),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:h,backFromConversation:f,openMachine:v,openConversationMachine:S,backFromMachine:p,changeMachineSection:x}}function us(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function ex(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function tx({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:v,onOpenHistory:S,onOpenRemote:p,onStopCli:x,wsStatus:y,isConnected:g,onShowHiddenConversation:N,onShowAllHiddenConversations:M,onHideConversation:w,onOpenNewSession:I,liveSessionInboxState:k,setCliViewModeOverrides:j}){const[b,B]=o.useState(()=>{var J;return((J=e[0])==null?void 0:J.tabKey)||null}),[R,P]=o.useState(()=>e[0]?"chat":"inbox"),[F,U]=o.useState("chats"),[W,T]=o.useState(null),[L,z]=o.useState("inbox"),$=o.useRef([]),E=Is(),V="0.9.43",q=o.useMemo(()=>e.find(J=>J.tabKey===b)||e[0]||null,[e,b]),ve=o.useMemo(()=>q?r.find(J=>J.id===q.routeId):void 0,[r,q]),ne=o.useMemo(()=>!q||Ge(q)||!Ze(q)?null:Ls(q),[q]),pe=o.useMemo(()=>r.filter(J=>J.type==="adhdev-daemon").sort(Na),[r]),ie=o.useMemo(()=>pe.find(J=>J.id===W)||null,[pe,W]),ge=on({sendDaemonCommand:a,activeConv:q||void 0,setActionLogs:i,isStandalone:c}),be=Qh({sendDaemonCommand:a,navigate:E,ides:r,conversations:e}),H=o.useMemo(()=>e.map(J=>{const we=R==="chat"&&(q==null?void 0:q.tabKey)===J.tabKey,Ne=Zr(J,k,{hideOpenTaskCompleteUnread:!0,isOpenConversation:we}),Ae=Qt(J),Me=bc(J);return{conversation:J,timestamp:Ae,preview:Me,unread:Ne.unread,requiresAction:Ne.requiresAction,isWorking:Ne.isWorking,inboxBucket:Ne.inboxBucket}}),[e,k,R,q]),{markConversationRead:Q}=Yh({conversations:e,machineEntries:pe,items:H,selectedConversation:q,selectedTabKey:b,screen:R,liveSessionInboxState:k,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:v,setSelectedTabKey:B,setScreen:P,setSelectedMachineId:T,setSection:U,setMachineBackTarget:z,resetMachineAction:be.resetMachineAction}),re=Zh({conversations:e,selectedConversation:q,machineBackTarget:L,markConversationRead:Q,resetMachineAction:be.resetMachineAction,setSelectedTabKey:B,setScreen:P,setSelectedMachineId:T,setSection:U,setMachineBackTarget:z}),he=o.useMemo(()=>Rr(H.filter(J=>J.requiresAction)),[H]),ue=o.useMemo(()=>Rr(H.filter(J=>J.unread&&!J.requiresAction)),[H]),je=o.useMemo(()=>Uh(H.filter(J=>!J.unread&&!J.requiresAction&&J.isWorking),$.current),[H]);o.useEffect(()=>{$.current=je.map(J=>J.conversation.tabKey)},[je]);const ce=o.useMemo(()=>Rr(H.filter(J=>!J.unread&&!J.requiresAction&&!J.isWorking)),[H]),xe=o.useMemo(()=>ie?H.filter(J=>ms(J.conversation)===ie.id):[],[H,ie]),Z=o.useMemo(()=>Vh(ie,r),[r,ie]),ae=(ie==null?void 0:ie.version)||null,te=!!ie&&!!ae&&!0&&ae!==V,Y=o.useMemo(()=>(ie==null?void 0:ie.availableProviders)||[],[ie]),X=o.useMemo(()=>Y.filter(J=>us(J,"cli")).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[Y]),le=o.useMemo(()=>Y.filter(J=>us(J,"acp")).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[Y]),D=o.useMemo(()=>Gh(pe,H),[H,pe]),oe=o.useCallback(async J=>{ie&&await be.handleOpenRecent(ie.id,J)},[be,ie]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:R==="chat"&&q?s.jsx(Dh,{selectedConversation:q,isAcp:Ge(q),isStandalone:c,selectedIdeEntry:ve,actionLogs:n,userName:l,isSendingChat:ge.isSendingChat,sendFeedbackMessage:ge.sendFeedbackMessage,isFocusingAgent:ge.isFocusingAgent,handleModalButton:ge.handleModalButton,handleRelaunch:ge.handleRelaunch,onBack:re.backFromConversation,onOpenNativeConversation:re.openNativeConversation,onOpenMachine:re.openConversationMachine,onHideConversation:w,onOpenHistory:S,onOpenRemote:p,onStopCli:x,cliViewMode:ne,onSetCliViewMode:async J=>{await zc({conversation:q,mode:J,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:j})},handleSendChat:ge.handleSendChat,handleFocusAgent:ge.handleFocusAgent}):R==="machine"&&ie?s.jsx(Fh,{selectedMachineEntry:ie,selectedMachineConversations:xe,selectedMachineRecentLaunches:Z,cliProviders:X,acpProviders:le,selectedMachineNeedsUpgrade:te,appVersion:V,machineAction:be.machineAction,isStandalone:c,section:F,showBottomNav:L==="inbox",onBack:re.backFromMachine,onSectionChange:re.changeMachineSection,onOpenConversation:re.openConversation,onOpenRecent:oe,onOpenMachineDetails:()=>E(`/machines/${ie.id}`),onMachineUpgrade:()=>be.handleMachineUpgrade(ie.id),onLaunchDetectedIde:(J,we)=>be.handleLaunchDetectedIde(ie.id,J,we),onAddWorkspace:(J,we)=>be.handleAddWorkspace(ie.id,J,we),onBrowseDirectory:J=>be.handleBrowseDirectory(ie.id,J),onLaunchWorkspaceProvider:(J,we,Ne)=>be.handleLaunchWorkspaceProvider(ie.id,J,we,Ne),onListSavedSessions:J=>be.handleListSavedSessions(ie.id,J)}):s.jsx($h,{section:F,attentionItems:he,unreadItems:ue,workingItems:je,completedItems:ce,hiddenConversations:t,machineCards:D,getAvatarText:ex,onOpenConversation:re.openConversation,onShowConversation:N,onShowAllHidden:M,onOpenNewSession:I,onOpenMachine:re.openMachine,onOpenSettings:()=>E("/settings"),onSectionChange:U,wsStatus:y,isConnected:g,isStandalone:c})})}function Rn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function sx({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[m,d]=o.useState(null),h=o.useCallback(()=>{c.current=0,u(!1),d(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const f=o.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),v=o.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!Rn(t,r)){d("merge");return}const y=x.currentTarget.getBoundingClientRect(),g=x.clientX-y.left,N=y.width/3;g<N?d("split-left"):g>N*2?d("split-right"):d("merge")},[t,r]),S=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),d(null))},[]),p=o.useCallback(x=>{c.current=0,u(!1);const y=x.dataTransfer.getData("text/tab-key"),g=y?e.some(M=>M.tabKey===y):!1,N=m;if(d(null),i(),!!y){if(x.preventDefault(),N==="split-left"&&Rn(t,r)){r==null||r(y,"split-left");return}if(N==="split-right"&&Rn(t,r)){r==null||r(y,"split-right");return}if(g){a(y);return}n==null||n(y)}},[e,m,t,r,n,a,i]);return{dragOver:l,dropAction:m,resetDragState:h,handleDragEnter:f,handleDragOver:v,handleDragLeave:S,handleDrop:p}}function rx(e,t){const r=new Set(t.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=t.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function nx({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(t??null),[l,u]=o.useState(r??[]),[m,d]=o.useState(null),h=o.useRef(null),f=o.useRef(null),v=o.useRef(n),S=o.useRef(a);o.useEffect(()=>{v.current=n},[n]),o.useEffect(()=>{S.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{u(k=>{const j=rx(k,e);return j.length===k.length&&j.every((b,B)=>b===k[B])?k:j})},[e]);const p=o.useMemo(()=>{const k=m??l;if(k.length===0)return e;const j=new Map(k.map((b,B)=>[b,B]));return[...e].sort((b,B)=>{const R=j.get(b.tabKey)??999,P=j.get(B.tabKey)??999;return R-P})},[e,m,l]);o.useEffect(()=>{var j,b;if(p.length===0){i!==null&&(c(null),(j=v.current)==null||j.call(v,null));return}if(i&&p.some(B=>B.tabKey===i))return;const k=p[0].tabKey;k!==i&&(c(k),(b=v.current)==null||b.call(v,k))},[p,i]);const x=o.useMemo(()=>p.find(k=>k.tabKey===i),[p,i]),y=o.useCallback(k=>{var j;c(k),(j=v.current)==null||j.call(v,k)},[]),g=o.useCallback((k,j,b)=>{u(B=>{var U;const R=B.filter(W=>W!==k),P=R.indexOf(j);if(P<0)return B;const F=b==="left"?P:P+1;return R.splice(F,0,k),(U=S.current)==null||U.call(S,R),R}),d(null)},[]),N=o.useCallback((k,j,b)=>{const R=(l.length>0?l:e.map(U=>U.tabKey)).filter(U=>U!==k),P=R.indexOf(j);if(P<0)return;const F=b==="left"?P:P+1;R.splice(F,0,k),h.current=R,d(R)},[l,e]),M=o.useCallback(()=>{var j;const k=h.current;k&&(u(k),(j=S.current)==null||j.call(S,k))},[]),w=o.useCallback(()=>{h.current=null,d(null)},[]),I=o.useCallback(k=>{u(j=>{var B;const b=j.filter(R=>R!==k);return b.push(k),(B=S.current)==null||B.call(S,b),b})},[]);return{activeTabId:i,activeConv:x,sortedConversations:p,previewOrderRef:h,draggingTabRef:f,selectTab:y,handleTabReorder:g,updatePreviewOrder:N,commitPreviewOrder:M,clearPreviewOrder:w,moveTabToEnd:I,setDraggingTabKey:k=>{f.current=k}}}function ax({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 Ja({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:i}){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&&!!i,u=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?wc: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:i,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Dt,"aria-label":Dt,children:[s.jsx(Ei,{size:14}),s.jsx("span",{children:Dt})]})}),c&&s.jsx(Zc,{}),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 rl="adhdev-tab-shortcuts";function nl(){try{return JSON.parse(localStorage.getItem(rl)||"{}")}catch{return{}}}function al({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>nl()),[l,u]=o.useState(null),m=o.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=o.useCallback(h=>{c(h);try{localStorage.setItem(rl,JSON.stringify(h))}catch{}},[]);return o.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 S={...i};for(const[p,x]of Object.entries(S))x===v&&delete S[p];S[l]=v,d(S),u(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,i,d,m]),o.useEffect(()=>{if(!e)return;const h=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[v,S]of Object.entries(i))if(t.includes(v)&&m(f)===S){f.preventDefault(),r(),n(v);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,i,t,r,n,m]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const ox=o.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:m,onConversationActivated:d,onPreviewReorder:h,onReorderTab:f,onCommitPreviewOrder:v,onClearPreviewOrder:S,onDragStateReset:p,onDragTabKeyChange:x,onReceiveTab:y,onOpenContextMenu:g,longPressTimer:N,isGroupActive:M}){const w=As(t),I=w.isGenerating?"agent-tab-generating":w.isWaiting?"agent-tab-waiting":"",k=w.isReconnecting,j=o.useCallback(L=>{l.current=t.tabKey,x(t.tabKey),L.dataTransfer.setData("text/tab-key",t.tabKey),L.dataTransfer.effectAllowed="move"},[t.tabKey,l,x]),b=o.useCallback(()=>{l.current=null,x(null),v(),S(),p()},[l,x,v,S,p]),B=o.useCallback(L=>{const z=l.current;if(!(!z||z===t.tabKey)&&L.dataTransfer.types.includes("text/tab-key")){L.preventDefault(),L.stopPropagation();const $=L.currentTarget.getBoundingClientRect(),E=L.clientX<$.left+$.width/2?"left":"right";h(z,t.tabKey,E)}},[t.tabKey,l,h]),R=o.useCallback(L=>{L.preventDefault(),L.stopPropagation();const z=L.dataTransfer.getData("text/tab-key");if(z&&z!==t.tabKey){const $=L.currentTarget.getBoundingClientRect(),E=L.clientX<$.left+$.width/2?"left":"right";c.includes(z)?f(z,t.tabKey,E):y&&y(z)}S()},[t.tabKey,c,f,y,S]),P=o.useCallback(L=>{L.stopPropagation(),u(),m(t.tabKey),d(t)},[t,d,u,m]),F=o.useCallback(L=>{L.preventDefault(),g(L.clientX,L.clientY,t.tabKey)},[t.tabKey,g]),U=o.useCallback(L=>{const z=L.touches[0];N.current=setTimeout(()=>{g(z.clientX,z.clientY,t.tabKey)},600)},[t.tabKey,N,g]),W=o.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),T=["adhdev-dockview-tab",I,r&&"is-active",M&&"is-group-active",k&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:T,draggable:!0,onDragStart:j,onDragEnd:b,onDragOver:B,onDrop:R,onClick:P,onContextMenu:F,onTouchStart:U,onTouchEnd:W,onTouchMove:W,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:w.isGenerating?s.jsx("div",{className:"tab-spinner"}):w.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):k?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):w.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:ot(t),children:ot(t)}),s.jsx("span",{className:"adhdev-dockview-tab-meta",children:k?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Zt(t)}):w.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[Zt(t),s.jsx("span",{className:"connecting-dots"})]}):Zt(t)})]}),i&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(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 ix({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:v,onReceiveTab:S,onHideTab:p,isGroupActive:x,allowTabShortcuts:y=!0}){const[g,N]=o.useState(null),M=o.useRef(null),w=o.useRef(null),I=o.useMemo(()=>e.map(F=>F.tabKey),[e]);ar("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(g==null?void 0:g.tabKey)||null});const{isMac:k,tabShortcuts:j,shortcutListening:b,setShortcutListening:B,saveShortcuts:R}=al({enabled:y,sortedTabKeys:e.map(F=>F.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!g)return;const F=U=>{const W=document.querySelector("[data-pane-context-menu]");W&&W.contains(U.target)||N(null)};return window.addEventListener("mousedown",F,!0),()=>window.removeEventListener("mousedown",F,!0)},[g]),o.useEffect(()=>{const F=w.current;if(!F)return;const U=W=>{Math.abs(W.deltaY)<=Math.abs(W.deltaX)||(W.preventDefault(),F.scrollLeft+=W.deltaY)};return F.addEventListener("wheel",U,{passive:!1}),()=>F.removeEventListener("wheel",U)},[]);const P=o.useCallback((F,U,W)=>{N({x:F,y:U,tabKey:W})},[]);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:w,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(F=>s.jsx(ox,{conv:F,isActive:t===F.tabKey,isDraggedTab:a.current===F.tabKey,isTaskCompleteUnread:n.has(F.tabKey),shortcut:y?j[F.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:v,onReceiveTab:S,onOpenContextMenu:P,longPressTimer:M,isGroupActive:x},F.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),g&&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:g.x,top:g.y},children:[y&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:F=>{F.stopPropagation(),B(g.tabKey),N(null)},children:["⌨ ",j[g.tabKey]?`Change shortcut (${j[g.tabKey]})`:"Set shortcut"]}),j[g.tabKey]&&s.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const F={...j};delete F[g.tabKey],R(F),N(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[y&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{p(g.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&b&&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:()=>B(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:F=>F.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",k?"⌘+1":"Ctrl+1",", ",k?"⌥+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 cx({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:u,groupIndex:m,onFocus:d,isSplitMode:h,numGroups:f,onMoveTab:v,onReceiveTab:S,style:p,onActiveTabChange:x,initialActiveTabId:y,initialTabOrder:g,onTabOrderChange:N,onHideTab:M,isFocused:w,allowTabShortcuts:I=!0,onOpenNewSession:k,liveSessionInboxState:j}){const{sendCommand:b}=wt(),B=o.useRef(null),{activeTabId:R,activeConv:P,sortedConversations:F,draggingTabRef:U,selectTab:W,handleTabReorder:T,updatePreviewOrder:L,commitPreviewOrder:z,clearPreviewOrder:$,moveTabToEnd:E,setDraggingTabKey:V}=nx({conversations:e,initialActiveTabId:y,initialTabOrder:g,onActiveTabChange:x,onTabOrderChange:N}),q=on({sendDaemonCommand:a,activeConv:P,setActionLogs:i,isStandalone:c}),{dragOver:ve,dropAction:ne,resetDragState:pe,handleDragEnter:ie,handleDragOver:ge,handleDragLeave:be,handleDrop:H}=sx({conversations:e,numGroups:f,onMoveTab:v,onReceiveTab:S,onOwnTabDrop:E,onClearPreviewOrder:$}),Q=P&&!Ge(P)&&Ls(P)==="terminal",re=o.useMemo(()=>P?t.find(ce=>ce.id===P.routeId):void 0,[t,P]),he=o.useMemo(()=>P?n.filter(ce=>ce.routeId===P.tabKey):[],[n,P]),ue=o.useMemo(()=>new Set(F.filter(ce=>Nu(ce,j,{isOpenConversation:ce.tabKey===R})).map(ce=>ce.tabKey)),[R,j,F]);ar("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:R,dragOver:ve});const je=o.useCallback(ce=>{ce.streamSource==="agent-stream"&&ce.agentType&&b(ce.routeId,Qc(),{agentType:ce.agentType,...ce.sessionId&&{targetSessionId:ce.sessionId}}).catch(()=>{})},[b]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...p,outline:ve?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(ix,{conversations:F,activeTabId:R,groupIndex:m,numGroups:f,unreadTabKeys:ue,draggingTabRef:U,onFocus:d,onSelectTab:W,onConversationActivated:je,onPreviewReorder:L,onReorderTab:T,onCommitPreviewOrder:z,onClearPreviewOrder:$,onDragStateReset:pe,onDragTabKeyChange:V,onMoveTab:v,onReceiveTab:S,onHideTab:M,isGroupActive:w??!1,allowTabShortcuts:I}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ie,onDragOver:ge,onDragLeave:be,onDrop:H,children:[ve&&s.jsx(ax,{dropAction:ne,canSplit:!!(f<4&&v)}),P?s.jsx(Ya,{activeConv:P,clearToken:r[P.tabKey]||0,isCliTerminal:!!Q,ideEntry:re,terminalRef:B,handleModalButton:q.handleModalButton,handleRelaunch:q.handleRelaunch,handleSendChat:q.handleSendChat,isSendingChat:q.isSendingChat,sendFeedbackMessage:q.sendFeedbackMessage,handleFocusAgent:q.handleFocusAgent,isFocusingAgent:q.isFocusingAgent,actionLogs:he,userName:u,isInputActive:!h||!!w}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Ja,{conversationsCount:e.length,isSplitMode:h,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:k})})]})]})}function lx({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:m,isStandalone:d,hasRegisteredMachines:h,userName:f,focusedGroup:v,focusGroup:S,moveTabToGroup:p,splitTabRelative:x,closeGroup:y,handleResizeStart:g,groupActiveTabIds:N,setGroupActiveTab:M,groupTabOrders:w,setGroupTabOrder:I,toggleHiddenTab:k,onOpenNewSession:j,allowTabShortcuts:b=!0,liveSessionInboxState:B}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((R,P)=>{const F=t&&n.length===r?`${n[P]}%`:void 0;return s.jsxs(jt.Fragment,{children:[t&&P>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=>g(P-1,U),onDoubleClick:()=>y(P),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(cx,{style:t?{flexBasis:F??`${100/r}%`,flexGrow:F?0:1,flexShrink:F?0:1}:void 0,conversations:R,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:m,isStandalone:d,hasRegisteredMachines:h,userName:f,groupIndex:P,isFocused:t&&v===P,onFocus:()=>S(P),isSplitMode:t,numGroups:r,onMoveTab:(U,W)=>{W==="left"&&P>0?p(U,P-1):W==="right"&&P<r-1?p(U,P+1):W==="split-left"&&r<4?x(U,P,"left"):W==="split-right"&&r<4&&x(U,P,"right")},onReceiveTab:U=>p(U,P),onActiveTabChange:U=>M(P,U),initialActiveTabId:N[P],initialTabOrder:w[P],onTabOrderChange:U=>I(P,U),onHideTab:k,onOpenNewSession:j,allowTabShortcuts:b,liveSessionInboxState:B})]},P)})})}function ol({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?lt.onScreenshot("ide-page",(d,h)=>{if(d!==e)return;const f=new FileReader;f.onload=()=>i(f.result),f.readAsDataURL(h)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.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]),o.useEffect(()=>{i(null)},[e,t]),o.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=o.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 il="adhdev-dashboard-action-shortcuts",dx=1200,ux={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function mx(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function st(e,t){switch(e){case"openShortcutHelp":return"?";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+Alt+\\";case"splitActiveTabDown":return t?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return t?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return t?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return t?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return t?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return t?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return t?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return t?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return t?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";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+Alt+[";case"selectNextGroupTab":return t?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function cl(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:st("openShortcutHelp",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 ma(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(cl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(il)||"{}"),n={...t,...r};for(const[a,i]of Object.entries(ux))n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function ll(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function fx({enabled:e=!0,onTrigger:t}){const r=mx(),[n,a]=o.useState(()=>qr(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),m=o.useRef({parts:[],timer:null}),d=o.useCallback(p=>{const x=[];return p.metaKey&&x.push(r?"⌘":"Meta"),p.ctrlKey&&x.push("Ctrl"),p.altKey&&x.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&x.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(x.push(ll(p.key)),x.join("+"))},[r]),h=o.useCallback(p=>{a(p);try{localStorage.setItem(il,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=qr(r),x=Object.entries(n),y=Object.entries(p);x.length===y.length&&x.every(([g,N])=>p[g]===N)||h(p)},[n,r,h]);const f=o.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),v=o.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},dx))},[]);o.useEffect(()=>{if(!i)return;const p=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){c(null),u([]);return}const y=d(x);if(!y)return;const N=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(y);if(l.length===0&&N){u([y]);return}const w=[...l,y].slice(0,2).join(" "),I={...n};for(const[k,j]of Object.entries(I))j===w&&delete I[k];I[i]=w,h(I),c(null),u([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,d,h,i,l]),o.useEffect(()=>{if(!e||i)return;const p=x=>{if(x.defaultPrevented)return;const y=d(x);if(!y)return;const g=x.metaKey||x.ctrlKey||x.altKey;if(ma(x.target)&&!g)return;const N=m.current.parts,M=g?[y]:[...N.slice(-1),y].slice(-2),w=M.join(" "),I=M[M.length-1],k=Object.entries(n).filter(([,P])=>!!P),j=k.find(([,P])=>P===w);if(j){x.preventDefault(),f(),t(j[0]);return}if(k.some(([,P])=>P.startsWith(`${w} `))){x.preventDefault(),m.current.parts=M,v();return}const B=k.find(([,P])=>P===I);if(B){x.preventDefault(),f(),t(B[0]);return}if(k.some(([,P])=>P.startsWith(`${I} `))){x.preventDefault(),m.current.parts=[I],v();return}f()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,v,e,d,t,f,i]),o.useEffect(()=>()=>f(),[f]);const S=o.useMemo(()=>cl(r),[r]);return{isMac:r,actionDefinitions:S,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:h}}function px({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 dl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function ti({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!dl(n):!0}function hx({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:dl(r)}const ul=500;function xx({detachDelayMs:e=ul,onDetach:t,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:n=globalThis.clearTimeout.bind(globalThis)}){let a=null,i=null,c=null,l=!1;const u=()=>{c!=null&&(n(c),c=null)},m=()=>{u(),a=null,i=null,l=!1},d=()=>{!a||!i||l||c!=null||(c=r(()=>{c=null,!(!a||!i||l)&&(l=!0,t({panelId:a,clientX:i.clientX,clientY:i.clientY}))},e))};return{startDrag:h=>{u(),a=h.panelId,i={clientX:h.clientX,clientY:h.clientY},l=!1},markNoDropTarget:h=>{!a||l||(i={clientX:h.clientX,clientY:h.clientY},d())},markDockTarget:h=>{!a||l||(h&&(i={clientX:h.clientX,clientY:h.clientY}),u())},endDrag:m,isDragging:()=>a!=null,hasDetached:()=>l,dispose:m}}function bx(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}const ml=o.createContext(null);function ln(){const e=o.useContext(ml);if(!e)throw new Error("DashboardDockviewContext missing");return e}function _r(e){return ot(e)||e.tabKey}function gx(e){return`remote:${e}`}function At(e){return e.startsWith("remote:")}function si(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function _n(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 Pn(e,t){e.classList.remove(Gn.className,qn.className),e.classList.add(t==="light"?Gn.className:qn.className)}function ri(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 yx(e){const[,t]=o.useState(0);o.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 vx(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 ni(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 ai(e,t,r){var u,m;const n=r?gx(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 i=e.getPanel(n),c=vc(a);if(i){i.title!==c&&i.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 wx({params:e,api:t}){var h;const r=ln(),n=o.useRef(null),[a,i]=o.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=on({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(t.isActive);const f=[t.onDidActiveChange(v=>i(v.isActive)),t.onDidActiveGroupChange(v=>{if(!t.isActive&&!v.isActive){i(!1);return}i(t.isActive)})];return()=>{for(const v of f)v.dispose()}},[t]);const u=o.useMemo(()=>c?r.ides.find(f=>f.id===c.routeId):void 0,[r.ides,c]),m=o.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(Ja,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const d=!Ge(c)&&Ls(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Ya,{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 jx({params:e}){var u;const t=ln(),r=o.useMemo(()=>_t([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=o.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:i,screenshotUsage:c,handleRemoteAction:l}=ol({doId:a,targetSessionId:r?ac(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(Hi,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,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 kx(){const e=ln();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Ja,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Sx(e){var v,S;yx(e);const t=ln(),r=o.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),x=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,y=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${x?" is-active":""}${y?" 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=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,i=e.api.isGroupActive,c=Zr(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":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:ot(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var x;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((x=p.target)==null?void 0:x.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:ot(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Zt(n)}):u?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Zt(n)}):s.jsx("span",{children:Zt(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 Nx({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:u,userName:m,toggleHiddenTab:d,actionShortcuts:h,registerActionHandlers:f,onActiveTabChange:v,onOpenNewSession:S,onRequestScrollToBottom:p,requestedActiveTabKey:x,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:g,scrollToBottomRequest:N,liveSessionInboxState:M,layoutProfile:w}){var Qe,nt,mt;const{theme:I}=Ha(),{sendCommand:k}=wt(),j=o.useRef(null),b=o.useRef(null),B=o.useRef(null),R=o.useRef(!1),P=o.useRef(!1),F=o.useRef(!1),U=o.useRef(null),W=o.useRef([]),[T,L]=o.useState(null),[z,$]=o.useState(0),E=o.useRef(typeof window>"u"?{}:Yp(w)),V=o.useMemo(()=>new Map(e.map(A=>[A.tabKey,A])),[e]),q=o.useMemo(()=>{const A=j.current;return A?A.groups.some(C=>{try{const _=C.model.location.type;return _!=="floating"&&_!=="popout"?!1:C.panels.some(O=>V.has(O.id))}catch{return!1}}):!1},[V,z,e]),ve=o.useCallback(()=>{var A;(A=j.current)==null||A.focus()},[]),ne=o.useCallback((A,C)=>{p==null||p(A,C)},[p]),pe=o.useCallback(A=>{const C=document,_=A.document;for(const ye of C.querySelectorAll('link[rel="stylesheet"]')){const Se=_.createElement("link");Se.rel="stylesheet",Se.href=ye.href,ye.crossOrigin&&(Se.crossOrigin=ye.crossOrigin),_.head.appendChild(Se)}for(const ye of C.querySelectorAll("style")){const Se=_.createElement("style");Se.textContent=ye.textContent,_.head.appendChild(Se)}const O=[];for(const ye of C.styleSheets)try{for(const Se of ye.cssRules)Se instanceof CSSStyleRule&&(Se.selectorText===":root"||Se.selectorText==="html")&&O.push(Se.cssText)}catch{}if(O.length>0){const ye=_.createElement("style");ye.textContent=O.join(`
43
- `),_.head.appendChild(ye)}const G=C.documentElement.getAttribute("data-theme");G&&_.documentElement.setAttribute("data-theme",G),_.documentElement.style.colorScheme=G==="light"?"light":"dark",_.body.className=C.body.className;const ee=C.documentElement.getAttribute("style");ee&&_.documentElement.setAttribute("style",ee);const de=_.getElementById("dv-popout-window");de instanceof HTMLElement&&(de.classList.add("adhdev-dockview"),Pn(de,I))},[I]),ie=o.useCallback(()=>{var C;const A=j.current;if(A)for(const _ of A.groups)try{const O=(C=_.element)==null?void 0:C.ownerDocument;if(!O||O===document)continue;const G=O.getElementById("dv-popout-window");G instanceof HTMLElement&&(G.classList.add("adhdev-dockview"),Pn(G,I));const ee=document.documentElement.getAttribute("data-theme");ee&&O.documentElement.setAttribute("data-theme",ee),O.documentElement.style.colorScheme=ee==="light"?"light":"dark",O.body.className=document.body.className;const de=document.documentElement.getAttribute("style");de?O.documentElement.setAttribute("style",de):O.documentElement.removeAttribute("style")}catch{}},[I]),ge=o.useCallback(A=>{const C=j.current;if(!C)return;const _=C.getPanel(A);_&&C.addPopoutGroup(_,{popoutUrl:"/popout.html",onDidOpen:({window:O})=>{pe(O),xe();const G=V.get(A);O.document.title=G?`${ot(G)} — ADHDev`:"ADHDev — Popout"}})},[V,pe]),be=o.useCallback(A=>{const C=j.current,_=C==null?void 0:C.getPanel(A);if(!C||!_)return;const O=C.groups.filter(G=>{var ee;try{return((ee=G.element)==null?void 0:ee.ownerDocument)===document}catch{return!0}});O.length>0?_.api.moveTo({group:O[0],position:"center"}):_.api.moveTo({position:"center"}),_.api.setActive()},[]),H=o.useCallback(A=>{var O;const C=j.current;if(!C)return!1;const _=C.getPanel(A);if(!_)return!1;try{return((O=_.group.element)==null?void 0:O.ownerDocument)!==document}catch{return!1}},[]),Q=o.useCallback(A=>{H(A)&&be(A),d(A)},[H,be,d]),re=o.useCallback(A=>{const C=j.current,_=C==null?void 0:C.getPanel(A);!C||!_||C.addFloatingGroup(_,{width:600,height:500})},[]),he=o.useCallback(A=>{var _;const C=(_=j.current)==null?void 0:_.getPanel(A);if(!C)return!1;try{return C.group.model.location.type==="floating"}catch{return!1}},[]),ue=o.useCallback(()=>{var C,_;const A=(_=(C=j.current)==null?void 0:C.activePanel)==null?void 0:_.id;return!A||At(A)?null:V.has(A)?A:null},[V]),je=o.useCallback(A=>{const C=j.current,_=C==null?void 0:C.getPanel(A);if(!C||!_)return;const O=C.groups.filter(G=>{try{return G.model.location.type==="grid"}catch{return!0}});O.length>0?_.api.moveTo({group:O[0],position:"center"}):_.api.moveTo({position:"center"}),_.api.setActive()},[]),ce=o.useCallback(()=>{var ee;const A=j.current;if(!A)return;const _=A.groups.filter(de=>{var ye;try{return((ye=de.element)==null?void 0:ye.ownerDocument)===document&&de.model.location.type==="grid"}catch{return!1}})[0]||null,O=[...A.panels];for(const de of O){const ye=(ee=de.group.element)==null?void 0:ee.ownerDocument,Se=de.group.model.location.type;ye===document&&Se==="grid"||(_&&_.id!==de.group.id?de.api.moveTo({group:_,position:"center"}):de.api.moveTo({position:"center"}))}const G=A.activePanel;G&&(G.group.model.openPanel(G),G.api.setActive()),_n(document)},[]),xe=o.useCallback(()=>{var C,_;const A=j.current;if(A)for(const O of A.groups){const G=(C=O.element)==null?void 0:C.ownerDocument;if(!G||G===document)continue;const ee=G.getElementById("dv-popout-window");if(!(ee instanceof HTMLElement))continue;let de=null,ye=G.title||"ADHDev",Se="Popout workspace";const Re=O.activePanel;if(Re)if(de=Re.id,At(Re.id)){const Ie=((_=Re.params)==null?void 0:_.routeId)||Re.id.slice(7),qe=_t([...V.values()],Ie);ye=vc(qe),Se=qe!=null&&qe.machineName?`Remote view · ${qe.machineName}`:"Remote view"}else{const Ie=V.get(Re.id);ye=Ie?ot(Ie):Re.title||Re.id,Se=Ie?Zt(Ie):"Dockview panel"}G.title=`${ye} — ADHDev`;const ke=Array.from(G.querySelectorAll("#adhdev-popout-header"));for(const Ie of ke)Ie.remove();const Ee=G.createElement("div");Ee.id="adhdev-popout-header",G.body.appendChild(Ee),Ee.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(";")),Ee.innerHTML=`
44
- <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
45
- <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
46
- <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${si(ye)}</div>
47
- <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${si(Se)}</div>
48
- </div>
49
- <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
50
- <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>
51
- <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>
52
- </div>
53
- `,ee.style.top="52px",ee.style.height="calc(100% - 52px)";const Ke=Ee.querySelector("[data-adhdev-popout-focus]");Ke&&(Ke.onclick=()=>{window.focus()});const $e=Ee.querySelector("[data-adhdev-popout-dock]");$e&&($e.disabled=!de,$e.style.opacity=de?"1":"0.5",$e.style.cursor=de?"pointer":"default",$e.onclick=()=>{var Ie;de&&be(de),(Ie=G.defaultView)==null||Ie.focus()})}},[V,be]),Z=o.useCallback(A=>{var O;const C=j.current,_=C==null?void 0:C.getPanel(A);if(!(!C||!_)){_.group.model.openPanel(_),_.api.setActive(),ne(A,"dockview-shortcut");try{const G=_.group.model.location;G.type==="popout"?G.getWindow().focus():_n((O=_.group.element)==null?void 0:O.ownerDocument)}catch{}}},[ne]),ae=o.useCallback(A=>{const C=j.current,_=C==null?void 0:C.activePanel,O=(C==null?void 0:C.activeGroup)||(_==null?void 0:_.group);if(!C||!_||!O)return;const G=O.panels||[];if(G.length<=1)return;const ee=G.findIndex(Se=>Se.id===_.id);if(ee<0)return;const de=(ee+A+G.length)%G.length,ye=G[de];ye&&(ye.group.model.openPanel(ye),ye.api.setActive(),At(ye.id)||ne(ye.id,"dockview-shortcut"))},[ne]),te=o.useCallback(A=>{var Ke;const C=j.current,_=(C==null?void 0:C.activeGroup)||((Ke=C==null?void 0:C.activePanel)==null?void 0:Ke.group);if(!C||!_)return;const O=C.groups||[],G=O.find($e=>$e.id===_.id);if(!G)return;const ee=G.element.getBoundingClientRect(),de=ee.left+ee.width/2,ye=ee.top+ee.height/2,Se=($e,Ie,qe,ct)=>Math.max(0,Math.min(Ie,ct)-Math.max($e,qe)),Re=$e=>{const Ie=$e.element.getBoundingClientRect(),qe=Ie.left+Ie.width/2,ct=Ie.top+Ie.height/2;let me=0,Le=0,et=0,at=!1;if(A==="left"?(at=qe<de,me=Math.max(0,ee.left-Ie.right),Le=Math.abs(ct-ye),et=Se(ee.top,ee.bottom,Ie.top,Ie.bottom)):A==="right"?(at=qe>de,me=Math.max(0,Ie.left-ee.right),Le=Math.abs(ct-ye),et=Se(ee.top,ee.bottom,Ie.top,Ie.bottom)):A==="above"?(at=ct<ye,me=Math.max(0,ee.top-Ie.bottom),Le=Math.abs(qe-de),et=Se(ee.left,ee.right,Ie.left,Ie.right)):(at=ct>ye,me=Math.max(0,Ie.top-ee.bottom),Le=Math.abs(qe-de),et=Se(ee.left,ee.right,Ie.left,Ie.right)),!at)return Number.POSITIVE_INFINITY;const Oe=et>0?0:120;return me*3+Le+Oe};let ke=null,Ee=Number.POSITIVE_INFINITY;for(const $e of O){if($e.id===G.id)continue;const Ie=Re($e);Number.isFinite(Ie)&&(Ie>=Ee||(Ee=Ie,ke=$e))}return ke||void 0},[]),Y=o.useCallback(A=>{var O;const C=te(A);if(!C)return;const _=C.activePanel||C.panels[0];_&&(C.model.openPanel(_),_.api.setActive(),At(_.id)||ne(_.id,"dockview-focus"),_n((O=C.element)==null?void 0:O.ownerDocument))},[te,ne]),X=o.useCallback((A,C)=>{const _=j.current,O=_==null?void 0:_.activePanel,G=(_==null?void 0:_.activeGroup)||(O==null?void 0:O.group);if(!_||!O||!G)return;let ee=te(A);!ee&&(C!=null&&C.createGroupIfMissing)&&(ee=_.addGroup({referenceGroup:G,direction:A})),ee&&(O.api.moveTo({group:ee,position:"center"}),O.group.model.openPanel(O),O.api.setActive(),At(O.id)||ne(O.id,C!=null&&C.createGroupIfMissing?"dockview-split":"dockview-move"))},[te,ne]),{isMac:le,tabShortcuts:D,shortcutListening:oe,setShortcutListening:J,saveShortcuts:we}=al({sortedTabKeys:e.map(A=>A.tabKey),onFocus:ve,onSelectTab:Z}),Ne=o.useCallback(()=>{var _;const A=j.current;if(!A)return;const C=A.activePanel;if(C){if(At(C.id)){const O=((_=C.params)==null?void 0:_.routeId)||C.id.slice(7),G=_t(e,O);G!=null&&G.tabKey&&J(G.tabKey);return}V.has(C.id)&&J(C.id)}},[V,Z,J,e]),Ae=o.useCallback(A=>{const C=[];return A.metaKey&&C.push(le?"⌘":"Meta"),A.ctrlKey&&C.push("Ctrl"),A.altKey&&C.push(le?"⌥":"Alt"),A.shiftKey&&A.key.length!==1&&C.push(le?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(A.key)?null:(C.push(ll(A.key)),C.join("+"))},[le]),Me=o.useCallback(A=>{var C,_;switch(A){case"splitActiveTabRight":X("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":X("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const O=ue();O&&re(O);return}case"popoutActiveTab":{const O=ue();O&&ge(O);return}case"dockActiveTab":{const O=ue();if(!O)return;H(O)?be(O):he(O)&&je(O);return}case"focusLeftPane":Y("left");return;case"focusRightPane":Y("right");return;case"focusUpPane":Y("above");return;case"focusDownPane":Y("below");return;case"moveActiveTabToLeftPane":X("left");return;case"moveActiveTabToRightPane":X("right");return;case"moveActiveTabToUpPane":X("above");return;case"moveActiveTabToDownPane":X("below");return;case"selectPreviousGroupTab":ae(-1);return;case"selectNextGroupTab":ae(1);return;case"setActiveTabShortcut":Ne();return;case"hideCurrentTab":{const O=(_=(C=j.current)==null?void 0:C.activePanel)==null?void 0:_.id;O&&!At(O)&&Q(O);return}default:return}},[ae,je,Y,re,ue,Q,he,H,be,X,ge,Ne]);o.useEffect(()=>{if(!T)return;const A=T.sourceDocument,C=A.defaultView??window,_=O=>{const G=A.querySelector("[data-dockview-tab-context-menu]");G&&G.contains(O.target)||L(null)};return C.addEventListener("mousedown",_,!0),C!==window&&window.addEventListener("mousedown",()=>L(null),!0),()=>{C.removeEventListener("mousedown",_,!0),C!==window&&window.removeEventListener("mousedown",()=>L(null),!0)}},[T]);const Ue=o.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:V,hasDetachedConversationPanels:q,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:S,liveSessionInboxState:M,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:Q,userName:m,scrollToBottomRequest:N,tabShortcuts:D,openTabContextMenu:({x:A,y:C,tabKey:_,sourceDocument:O})=>L({x:A,y:C,tabKey:_,sourceDocument:O??document}),popoutTab:ge,moveTabBackToMain:be,isTabInPopout:H,floatTab:re,isTabFloating:he}),[n,t,V,q,r,c,l,S,M,a,i,Q,m,N,D,ge,be,H,re,he]),We=T?px({isTabInPopout:H(T.tabKey),isTabFloating:he(T.tabKey),tabShortcut:D[T.tabKey],actionShortcuts:h}):[],Be=o.useCallback(A=>{var O;const C=j.current;if((((O=C==null?void 0:C.activePanel)==null?void 0:O.id)??null)===A.id){A.group.model.openPanel(A);return}A.group.model.openPanel(A),A.api.setActive()},[]),Ye=o.useCallback((A,C="requested-tab")=>{if(!A)return!1;const _=j.current;if(!_)return!1;const O=_.getPanel(A);return O?(Be(O),ne(A,C),g==null||g(),!0):!1},[Be,g,ne]),Xe=o.useCallback(()=>{if(F.current)return!1;const A=Ye(U.current,"stored-layout-restore");return A&&(F.current=!0),A},[Ye]),Je=o.useCallback(()=>{var C;const A=j.current;A&&qp(w,{activeTabId:((C=A.activePanel)==null?void 0:C.id)??null,layout:A.toJSON()})},[w]),Ve=o.useCallback(()=>{Xp(w,E.current)},[w]),ht=o.useCallback(A=>{var O,G,ee,de;const C=j.current;if(!C)return{kind:"grid"};const _=C.toJSON();for(const ye of _.floatingGroups||[])if((G=(O=ye.data)==null?void 0:O.views)!=null&&G.includes(A)&&ye.position)return{kind:"floating",position:ye.position};for(const ye of _.popoutGroups||[])if((de=(ee=ye.data)==null?void 0:ee.views)!=null&&de.includes(A))return{kind:"popout",position:ye.position,popoutUrl:ye.url};return{kind:"grid"}},[]),ut=o.useCallback(A=>{const C=j.current;if(!C)return;const _=C.getPanel(A),O=E.current[A];if(!_||!O||O.kind==="grid")return;if(_.group.model.location.type===O.kind){delete E.current[A],Ve();return}if(O.kind==="floating"){C.addFloatingGroup(_,{x:O.position.left??24,y:O.position.top??24,width:O.position.width,height:O.position.height}),delete E.current[A],Ve();return}delete E.current[A],Ve()},[Ve]);o.useEffect(()=>(f==null||f({setShortcutForActiveTab:Ne,restoreHiddenTabToSavedLocation:ut,activateConversationTab:Z,resetAllPanelsToMain:ce,activatePreviousTabInGroup:()=>ae(-1),activateNextTabInGroup:()=>ae(1),floatActiveTab:()=>{const A=ue();A&&re(A)},popoutActiveTab:()=>{const A=ue();A&&ge(A)},dockActiveTab:()=>{const A=ue();A&&(H(A)?be(A):he(A)&&je(A))},splitActiveTabRight:()=>X("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>X("below",{createGroupIfMissing:!0}),focusLeftPane:()=>Y("left"),focusRightPane:()=>Y("right"),focusUpPane:()=>Y("above"),focusDownPane:()=>Y("below"),moveActiveTabToLeftPane:()=>X("left"),moveActiveTabToRightPane:()=>X("right"),moveActiveTabToUpPane:()=>X("above"),moveActiveTabToDownPane:()=>X("below")}),()=>f==null?void 0:f(null)),[ae,je,re,Y,ue,he,H,X,be,ge,f,ce,ut,Z,Ne]),o.useEffect(()=>()=>{var A;(A=B.current)==null||A.call(B),B.current=null},[]);const ft=o.useCallback(A=>{var _,O;j.current=A.api,(_=B.current)==null||_.call(B),B.current=null;const C=Gp(w);if(U.current=(C==null?void 0:C.activeTabId)??null,C!=null&&C.layout&&A.api.fromJSON(C.layout,{reuseExistingPanels:!1}),P.current=ti({hasStoredLayout:!!(C!=null&&C.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:r}),P.current||(ni(A.api,e),ai(A.api,e,y)),A.api.totalPanels===0&&e.length>0){const G=vx(A.api,e,x);if(G){const ee=A.api.getPanel(G);ee&&Be(ee)}}else!P.current&&!Ye(x)&&Xe();if(R.current=!0,A.api.onDidActivePanelChange(G=>{var de;if(U.current=(G==null?void 0:G.id)??null,F.current=!0,xe(),G&&At(G.id)){const ye=((de=G.params)==null?void 0:de.routeId)||G.id.slice(7),Se=_t(e,ye);v((Se==null?void 0:Se.tabKey)??null),Je();return}if(v((G==null?void 0:G.id)??null),Je(),!G)return;const ee=V.get(G.id);(ee==null?void 0:ee.streamSource)==="agent-stream"&&ee.agentType&&k(ee.routeId,Qc(),{agentType:ee.agentType,...ee.sessionId&&{targetSessionId:ee.sessionId}}).catch(()=>{})}),A.api.onDidLayoutChange(()=>{Je(),xe(),$(G=>G+1)}),bx()){const G=ke=>({clientX:ke.clientX,clientY:ke.clientY}),ee=ke=>{var Ke;const Ee=(Ke=b.current)==null?void 0:Ke.getBoundingClientRect();return Ee?ke.clientX<Ee.left||ke.clientX>Ee.right||ke.clientY<Ee.top||ke.clientY>Ee.bottom:!1},de=xx({detachDelayMs:ul,onDetach:({panelId:ke,clientX:Ee,clientY:Ke})=>{var Le,et;const $e=A.api.getPanel(ke);if(!$e)return;try{if($e.group.model.location.type!=="grid")return}catch{return}const Ie=(Le=b.current)==null?void 0:Le.getBoundingClientRect(),qe=(et=$e.group.element)==null?void 0:et.getBoundingClientRect(),ct=Math.round(Math.min(Math.max((qe==null?void 0:qe.width)??600,360),720)),me=Math.round(Math.min(Math.max((qe==null?void 0:qe.height)??500,260),640));A.api.addFloatingGroup($e,{x:Ie?Math.max(0,Ee-Ie.left-32):void 0,y:Ie?Math.max(0,Ke-Ie.top-18):void 0,width:ct,height:me}),$e.api.setActive(),Je(),xe(),$(at=>at+1)}}),ye=[A.api.onWillDragPanel(ke=>{if(!(ke.nativeEvent.defaultPrevented||ke.nativeEvent.shiftKey)){try{if(ke.panel.group.model.location.type!=="grid")return}catch{return}de.startDrag({panelId:ke.panel.id,...G(ke.nativeEvent)})}}),A.api.onWillShowOverlay(ke=>{if(de.hasDetached()){ke.preventDefault();return}de.markDockTarget(G(ke.nativeEvent))}),A.api.onWillDrop(ke=>{if(de.hasDetached()){ke.preventDefault(),de.endDrag();return}de.markDockTarget(G(ke.nativeEvent))}),A.api.onDidDrop(()=>de.endDrag()),A.api.onUnhandledDragOverEvent(ke=>{de.isDragging()&&de.markNoDropTarget(G(ke.nativeEvent))})],Se=ke=>{if(!de.isDragging())return;const Ee=G(ke);ee(Ee)&&de.markNoDropTarget(Ee)},Re=()=>de.endDrag();window.addEventListener("dragover",Se,!0),window.addEventListener("drop",Re,!0),window.addEventListener("dragend",Re,!0),B.current=()=>{de.dispose();for(const ke of ye)ke.dispose();window.removeEventListener("dragover",Se,!0),window.removeEventListener("drop",Re,!0),window.removeEventListener("dragend",Re,!0)}}A.api.onDidAddGroup(G=>{requestAnimationFrame(()=>{var ee,de;try{const ye=(ee=G.element)==null?void 0:ee.ownerDocument;if(!ye||ye===document)return;(de=ye.getElementById("dv-popout-window"))==null||de.classList.add("adhdev-dockview");const Se=document.documentElement.getAttribute("data-theme");Se&&ye.documentElement.setAttribute("data-theme",Se),ye.body.className=document.body.className;const Re=document.documentElement.getAttribute("style");Re&&ye.documentElement.setAttribute("style",Re)}catch{}xe(),$(ye=>ye+1)})}),v(((O=A.api.activePanel)==null?void 0:O.id)??null)},[Be,Ye,V,r,u,w,v,Je,x,y,k,xe,e]);o.useLayoutEffect(()=>{const A=j.current;if(!A||!R.current||P.current&&ti({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:r}))return;P.current&&(P.current=!1);const C=W.current,_=new Set(C),O=e.map(ke=>ke.tabKey),G=new Set(O),ee=hx({previousVisibleConversationCount:C.length,visibleConversationCount:e.length,ides:r});let de=!1;for(const ke of C)G.has(ke)||ee||(E.current[ke]=ht(ke),de=!0);de&&Ve(),ee||(ni(A,e),ai(A,e,y));const ye=O.filter(ke=>!_.has(ke));let Se=!1;for(const ke of ye){const Ee=A.getPanel(ke),Ke=E.current[ke];if(!Ee||!Ke||Ke.kind==="grid")continue;if(Ee.group.model.location.type===Ke.kind){delete E.current[ke],Se=!0;continue}if(Ke.kind==="floating"){A.addFloatingGroup(Ee,{x:Ke.position.left??24,y:Ke.position.top??24,width:Ke.position.width,height:Ke.position.height}),delete E.current[ke],Se=!0;continue}}if(Se&&Ve(),W.current=O,x&&Ye(x))return;!A.activePanel&&A.panels[0]&&Be(A.panels[0]),!!(A.activePanel&&A.getPanel(A.activePanel.id))||Xe()},[Be,Ye,Xe,r,u,Ve,ht,x,y,e]),o.useEffect(()=>{R.current&&Ye(x)},[Ye,x]),o.useEffect(()=>{const A=_=>{const O=_.target;if(!O)return;const G=O.querySelector("[data-tab-key]")||O.closest("[data-tab-key]");if(G){const ee=G.getAttribute("data-tab-key");if(ee&&_.dataTransfer){const de=O.closest(".dv-tab")||G.closest(".dv-tab")||G;_.dataTransfer.effectAllowed="move",_.dataTransfer.setData("text/tab-key",ee),de instanceof HTMLElement&&_.dataTransfer.setDragImage(de,Math.max(12,Math.round(de.clientWidth/2)),Math.max(10,Math.round(de.clientHeight/2)))}}};window.addEventListener("dragstart",A);const C=ri(j.current);for(const _ of C)_.addEventListener("dragstart",A);return()=>{window.removeEventListener("dragstart",A);for(const _ of C)_.removeEventListener("dragstart",A)}},[z]),o.useEffect(()=>{var C;const A=(C=b.current)==null?void 0:C.querySelector(".adhdev-dockview");A instanceof HTMLElement&&Pn(A,I),ie(),xe()},[xe,ie,I]),o.useEffect(()=>{xe()},[xe]),o.useEffect(()=>{const A=C=>{if(C.defaultPrevented||oe)return;const _=Ae(C);if(!_)return;const O=C.metaKey||C.ctrlKey||C.altKey;ma(C.target)&&!O||qr(le).setActiveTabShortcut!==_||(C.preventDefault(),C.stopPropagation(),Ne())};return window.addEventListener("keydown",A,!0),()=>window.removeEventListener("keydown",A,!0)},[Ae,le,oe,Ne]),o.useEffect(()=>{const A=b.current;if(!A)return;const C=_=>{var ye,Se;if(!_.isTrusted)return;const O=(Se=(ye=_.target)==null?void 0:ye.closest)==null?void 0:Se.call(ye,".dv-scrollable");if(!O)return;_.preventDefault(),_.stopPropagation();const G=Math.abs(_.deltaX),ee=Math.abs(_.deltaY),de=G>ee?_.deltaX:_.deltaY;O.dispatchEvent(new WheelEvent("wheel",{deltaY:de,deltaMode:_.deltaMode,bubbles:!1,cancelable:!0}))};return A.addEventListener("wheel",C,{passive:!1,capture:!0}),()=>A.removeEventListener("wheel",C,{capture:!0})},[]),o.useEffect(()=>{const A=ri(j.current);if(A.length===0)return;const C=A.map(_=>{let O=[],G=null;const ee=()=>{G!=null&&_.clearTimeout(G),G=null,O=[]},de=()=>{G!=null&&_.clearTimeout(G),G=_.setTimeout(()=>{G=null,O=[]},1200)},ye=Re=>{if(!Re.ctrlKey&&!Re.metaKey&&!Re.altKey)return;const ke=Ae(Re);if(!ke)return;const Ee=nl();for(const[Ke,$e]of Object.entries(Ee))if(e.some(Ie=>Ie.tabKey===Ke)&&$e===ke){Re.preventDefault(),Z(Ke);return}},Se=Re=>{if(Re.defaultPrevented||oe)return;const ke=Ae(Re);if(!ke)return;const Ee=Re.metaKey||Re.ctrlKey||Re.altKey;if(ma(Re.target)&&!Ee)return;const Ke=qr(le),$e=Object.entries(Ke).filter(([Oe,Mt])=>!!Mt&&(Oe==="splitActiveTabRight"||Oe==="splitActiveTabDown"||Oe==="floatActiveTab"||Oe==="popoutActiveTab"||Oe==="dockActiveTab"||Oe==="focusLeftPane"||Oe==="focusRightPane"||Oe==="focusUpPane"||Oe==="focusDownPane"||Oe==="moveActiveTabToLeftPane"||Oe==="moveActiveTabToRightPane"||Oe==="moveActiveTabToUpPane"||Oe==="moveActiveTabToDownPane"||Oe==="selectPreviousGroupTab"||Oe==="selectNextGroupTab"||Oe==="setActiveTabShortcut"||Oe==="hideCurrentTab")),Ie=Ee?[ke]:[...O.slice(-1),ke].slice(-2),qe=Ie.join(" "),ct=Ie[Ie.length-1],me=$e.find(([,Oe])=>Oe===qe);if(me){Re.preventDefault(),ee(),Me(me[0]);return}if($e.some(([,Oe])=>Oe.startsWith(`${qe} `))){Re.preventDefault(),O=Ie,de();return}const et=$e.find(([,Oe])=>Oe===ct);if(et){Re.preventDefault(),ee(),Me(et[0]);return}if($e.some(([,Oe])=>Oe.startsWith(`${ct} `))){Re.preventDefault(),O=[ct],de();return}ee()};return _.addEventListener("keydown",ye),_.addEventListener("keydown",Se),()=>{ee(),_.removeEventListener("keydown",ye),_.removeEventListener("keydown",Se)}});return()=>{for(const _ of C)_()}},[Ae,le,z,Z,oe,Me,e]);const Ce=I==="light"?Gn:qn,He=((mt=(nt=(Qe=j.current)==null?void 0:Qe.activePanel)==null?void 0:nt.group.element)==null?void 0:mt.ownerDocument)??document;return s.jsxs(ml.Provider,{value:Ue,children:[s.jsx("div",{ref:b,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(rd,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:wx,remote:jx},defaultTabComponent:Sx,watermarkComponent:kx,onReady:ft,singleTabMode:"default",tabAnimation:"smooth",theme:Ce,popoutUrl:"/popout.html"})}),T&&Js.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:T.x,top:T.y},children:We.map(A=>{if(A.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},A.id);let C=s.jsx(Jd,{size:13,className:"shrink-0 opacity-70"}),_=()=>{};switch(A.id){case"dockInWindow":case"dockBackToGrid":C=s.jsx(Zd,{size:13,className:"shrink-0 opacity-70"}),_=()=>{je(T.tabKey),L(null)};break;case"moveBackToMain":C=s.jsx(Xd,{size:13,className:"shrink-0 opacity-70"}),_=()=>{be(T.tabKey),L(null)};break;case"floatAsPanel":C=s.jsx(Qd,{size:13,className:"shrink-0 opacity-70"}),_=()=>{re(T.tabKey),L(null)};break;case"openInNewWindow":C=s.jsx(Yd,{size:13,className:"shrink-0 opacity-70"}),_=()=>{ge(T.tabKey),L(null)};break;case"setShortcut":_=O=>{O.stopPropagation(),J(T.tabKey),L(null)};break;case"removeShortcut":C=s.jsx(vt,{size:13,className:"shrink-0 opacity-70"}),_=()=>{const O={...D};delete O[T.tabKey],we(O),L(null)};break;case"hideTab":C=s.jsx(Pi,{size:13,className:"shrink-0 opacity-70"}),_=()=>{Q(T.tabKey),L(null)};break}return s.jsxs("button",{className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${A.tone==="muted"?"text-text-muted":""}`,onClick:_,children:[C,s.jsx("span",{className:"flex-1 min-w-0",children:A.label}),A.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:A.shortcut}):null]},A.id)})}),T.sourceDocument.body),oe&&Js.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:()=>J(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:A=>A.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",le?"⌘+1":"Ctrl+1",", ",le?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),He.body)]})}const fl="adhdev-recent-launch-args-v1",Cx=8;function Tx(e){return String(e||"").trim().replace(/\s+/g," ")}function pl(e,t){return`${e.trim()}::${t.trim()}`}function hl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(fl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Mx(e){if(!(typeof window>"u"))try{window.localStorage.setItem(fl,JSON.stringify(e))}catch{}}function xl(e,t){var i;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((i=hl().byKey[pl(r,n)])==null?void 0:i.items)||[]}function bl(e,t,r){var d;const n=String(e||"").trim(),a=String(t||"").trim(),i=Tx(r);if(!n||!a||!i)return;const c=hl(),l=pl(n,a),u=((d=c.byKey[l])==null?void 0:d.items)||[],m=[i,...u.filter(h=>h!==i)].slice(0,Cx);c.byKey[l]={items:m},Mx(c)}function gl(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Pr({title:e,description:t,action:r,children:n,className:a="",contentClassName:i=""}){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 ${i}`.trim():i,children:n}):null]})}function yl({busy:e,savedSessionsLoading:t,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?tl(n):null;return s.jsxs(Pr,{title:"Saved history",description:$a(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:a,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:i,children:Lf()})]}),children:[l?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:l.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:l.providerSessionId}),s.jsx("div",{className:"mt-1",children:l.metaLine}),l.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:l.updatedLabel}),l.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:l.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:c,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted",children:"Start fresh, or open saved history when you want continuity."}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function Dn(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>us(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>us(a,"acp"))?"acp":null}function Sr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ix({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:c,onListSavedSessions:l}){var mt,A;const u=ir(),m=o.useMemo(()=>[...e].sort(Na),[e]),[d,h]=o.useState(((mt=m[0])==null?void 0:mt.id)||""),f=o.useMemo(()=>m.find(C=>C.id===d)||m[0],[d,m]),v=o.useMemo(()=>((f==null?void 0:f.workspaces)||[]).map(C=>({id:C.id,path:C.path,label:C.label})),[f]),S=(f==null?void 0:f.defaultWorkspaceId)||null,[p,x]=o.useState(""),[y,g]=o.useState(""),[N,M]=o.useState(Dn(m[0])),[w,I]=o.useState(""),[k,j]=o.useState(""),[b,B]=o.useState([]),[R,P]=o.useState(""),[F,U]=o.useState([]),[W,T]=o.useState(!1),[L,z]=o.useState(!1),[$,E]=o.useState(""),[V,q]=o.useState(!1),[ve,ne]=o.useState(()=>pt()),[pe,ie]=o.useState(null),[ge,be]=o.useState(!1),[H,Q]=o.useState(""),[re,he]=o.useState(!1),[ue,je]=o.useState(""),[ce,xe]=o.useState([]),[Z,ae]=o.useState(!1),[te,Y]=o.useState(""),[X,le]=o.useState(!1),D=o.useRef(null),oe=o.useRef(0);o.useEffect(()=>{var C;!d&&((C=m[0])!=null&&C.id)&&h(m[0].id)},[d,m]),o.useEffect(()=>{!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||u(f.id,{minFreshMs:3e4}).catch(()=>{})},[u,f]);const J=o.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(C=>us(C,"cli")),[f]),we=o.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(C=>us(C,"acp")),[f]),Ne=o.useMemo(()=>((f==null?void 0:f.detectedIdes)||[]).map(C=>({id:C.type,label:C.name||C.type,meta:C.running?"Detected locally":"Available to open"})),[f]),Ae=o.useMemo(()=>N==="cli"?J.map(C=>({id:C.type,label:C.displayName||C.type,meta:"CLI provider"})):N==="acp"?we.map(C=>({id:C.type,label:C.displayName||C.type,meta:"ACP provider"})):Ne,[we,N,J,Ne]);o.useEffect(()=>{var _;if(!f)return;if(D.current!==f.id){D.current=f.id,x(S||((_=v[0])==null?void 0:_.id)||"__home__"),g(""),M(Dn(f)),I(""),j(""),P(""),U([]),z(!1),E(""),ne(pt()),Q("");return}x(O=>{var G;return O==="__custom__"||O==="__home__"||v.some(ee=>ee.id===O)?O:S||((G=v[0])==null?void 0:G.id)||"__home__"}),M(O=>O==="ide"&&Ne.length>0||O==="cli"&&J.length>0||O==="acp"&&we.length>0?O:Dn(f))},[we.length,J.length,S,Ne.length,f,v]),o.useEffect(()=>{var C;N&&(Ae.some(_=>_.id===w)||I(((C=Ae[0])==null?void 0:C.id)||""))},[N,Ae,w]);const Me=o.useCallback(async(C,_)=>{const O=oe.current+1;return oe.current=O,T(!0),E(""),l(C,_).then(G=>{oe.current===O&&U(G)}).catch(G=>{oe.current===O&&(U([]),E(G instanceof Error?G.message:"Could not load saved sessions"))}).finally(()=>{oe.current===O&&(T(!1),z(!0))})},[l]),Ue=o.useCallback((C,_)=>{B(xl(C,_))},[]);o.useEffect(()=>{oe.current+=1,P(""),ne(pt()),!f||!w||N==="ide"?B([]):Ue(f.id,w),z(!1),U([]),E(""),T(!1)},[N,Ue,Me,f,w]),o.useEffect(()=>{if(!R)return;const C=F.find(_=>_.providerSessionId===R);C!=null&&C.canResume||P("")},[F,R]);const We=p==="__custom__"?y.trim():p==="__home__"?"":((A=v.find(C=>C.id===p))==null?void 0:A.path)||"",Be=o.useMemo(()=>f?t.filter(C=>C.id!==f.id&&C.daemonId===f.id).map(C=>C.workspace):[],[t,f]),Ye=o.useMemo(()=>((f==null?void 0:f.recentLaunches)||[]).map(C=>C.workspace),[f]),Xe=o.useCallback(C=>{const _=String(C.workspace||"").trim();if(!_)return;const O=v.find(G=>Sr(G.path)===Sr(_));if(O){x(O.id),g("");return}x("__custom__"),g(_)},[v]),Je=o.useCallback(C=>{const _=String(C.workspace||"").trim();if(!_)return{workspaceId:null,workspacePath:null};const O=v.find(G=>Sr(G.path)===Sr(_));return O?{workspaceId:O.id,workspacePath:null}:{workspaceId:null,workspacePath:_}},[v]),Ve=o.useMemo(()=>F.find(C=>C.providerSessionId===R)||null,[F,R]),ht=o.useMemo(()=>{var _;if(N!=="cli"||!f||!w)return null;const C=((_=J.find(O=>O.type===w))==null?void 0:_.displayName)||w;return{routeId:f.id,daemonId:f.id,providerSessionId:R||void 0,transport:"pty",mode:"chat",agentName:C,agentType:w,status:"idle",title:C,messages:[],ideType:w,workspaceName:We,displayPrimary:C,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${f.id}:${w}`,machineName:Tt(f,{fallbackId:f.id})}},[N,J,We,f,R,w]),ut=o.useCallback(()=>{var _;if(!f)return;x("__custom__"),he(!0),Y("");const C=nn(f.platform,rn(y.trim(),We,Be,Ye,f.defaultWorkspacePath,(_=v.find(O=>O.id===S))==null?void 0:_.path,v.map(O=>O.path)));ae(!0),n(f.id,C).then(O=>{je(O.path),g(O.path),xe(O.directories)}).catch(O=>{Y(O instanceof Error?O.message:"Could not load folder")}).finally(()=>ae(!1))},[y,S,Ye,Be,n,We,f,v]),ft=o.useCallback(C=>{f&&(ae(!0),Y(""),n(f.id,C).then(_=>{je(_.path),g(_.path),xe(_.directories)}).catch(_=>{Y(_ instanceof Error?_.message:"Could not load folder")}).finally(()=>ae(!1)))},[n,f]),Ce=o.useCallback(async()=>{if(!f||!We)return;le(!0),Q("");const C=await a(f.id,We);if(le(!1),!C.ok){Q(C.error||"Could not save workspace");return}Q("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,We,f]),He=o.useCallback(async()=>{if(!f||!N||!w)return;be(!0),Q("");const C=k.trim()?k.trim().split(/\s+/).filter(Boolean):[],_=N==="ide"?await i(f.id,w,{workspacePath:We||null}):await c(f.id,N,w,{workspaceId:p!=="__home__"&&p!=="__custom__"?p:null,workspacePath:p==="__custom__"&&We||null,resumeSessionId:N==="cli"&&R?R:null,cliArgs:C});if(be(!1),!_.ok){Q(_.error||"Could not start session");return}N!=="ide"&&k.trim()&&(bl(f.id,w,k),Ue(f.id,w)),r()},[N,k,Ue,r,i,c,We,f,R,w,p]),Qe=N?kc(N,N==="cli"&&!!R):"Start",nt=N?Sc(N,N==="cli"&&!!R):"Starting…";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(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[s.jsx(Pr,{title:"Machine",children:s.jsx("select",{value:f.id,onChange:C=>h(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ge,children:m.map(C=>s.jsx("option",{value:C.id,children:Tt(C,{fallbackId:C.id})},C.id))})}),s.jsxs(Pr,{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:ut,disabled:ge,children:"Browse…"}),children:[s.jsxs("select",{value:p,onChange:C=>{const _=C.target.value;x(_),_==="__custom__"?ut():Q("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ge,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),v.map(C=>s.jsxs("option",{value:C.id,children:[C.id===S?"⭐ ":"",en(C.path,C.label)||C.path]},C.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.":We||"Select a workspace folder."}),p==="__custom__"&&We&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ut,disabled:ge,children:[s.jsx(Ss,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ce,disabled:ge||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:J.length>0},{id:"ide",label:"IDE",enabled:Ne.length>0},{id:"acp",label:"ACP",enabled:we.length>0}].map(C=>s.jsx("button",{type:"button",className:`btn btn-sm ${N===C.id?"btn-primary":"btn-secondary"}`,onClick:()=>M(C.id),disabled:!C.enabled||ge,children:C.label},C.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:N==="ide"?"Choose IDE":N==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Ae.map(C=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${w===C.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>I(C.id),disabled:ge,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:C.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:C.meta})]},C.id)),Ae.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."})]})]}),N!=="ide"&&s.jsxs(Pr,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:k,onChange:C=>j(C.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:ge}),b.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:b.map(C=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>j(C),disabled:ge,title:C,children:C},C))})]}),N==="cli"&&s.jsx(yl,{busy:ge,savedSessionsLoading:W,savedSessionsError:$,selectedSession:Ve,onRefresh:()=>{!f||!w||Me(f.id,w)},onOpenHistory:()=>{!f||!w||(q(!0),gl({hasLoadedInitialResults:L,isLoading:W})&&Me(f.id,w))},onClearSelection:()=>P("")}),H&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${H.includes("saved")||H.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:H})]}),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:ge,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:He,disabled:ge||!N||!w||p==="__custom__"&&!We,children:[s.jsx(ja,{size:14}),ge?nt:Qe]})]})]})}),re&&s.jsx(cn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:ue,directories:ce,busy:Z,error:te,onClose:()=>he(!1),onNavigate:ft,onConfirm:C=>{g(C),je(C),x("__custom__"),he(!1)}}),V&&ht&&s.jsx(Oa,{activeConv:ht,ides:[],isCreatingChat:!1,isRefreshingHistory:W,savedSessions:F,isSavedSessionsLoading:W,isResumingSavedSessionId:pe,savedHistoryFilters:ve,onSavedHistoryFiltersChange:ne,onClose:()=>q(!1),onNewChat:()=>{P(""),q(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!f||!w||Me(f.id,w)},onResumeSavedSession:C=>{if(!f||!w||pe||!C.canResume)return;const _=Je(C);P(C.providerSessionId),Xe(C),ie(C.providerSessionId),q(!1),be(!0),Q(""),c(f.id,"cli",w,{workspaceId:_.workspaceId,workspacePath:_.workspacePath,resumeSessionId:C.providerSessionId}).then(O=>{if(!O.ok){Q(O.error||"Could not resume session");return}r()}).finally(()=>{be(!1),ie(O=>O===C.providerSessionId?null:O)})}})]}):null}function Ax({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=o.useState(!1),[i,c]=o.useState(!1),[l,u]=o.useState(!1),[m,d]=o.useState(!1),[h,f]=o.useState(!1),[v,S]=o.useState("quickstart"),[p,x]=o.useState("workspace"),y=o.useMemo(()=>!t&&!e,[t,e]),g=o.useCallback(j=>{a(j),j&&c(!1)},[]),N=o.useCallback(j=>{c(j),j&&a(!1)},[]),M=o.useCallback(()=>{S(r===0?"quickstart":"shortcuts"),x("workspace"),u(!0),a(!1),c(!1)},[r]),w=o.useCallback(()=>{u(!1)},[]),I=o.useCallback(()=>{d(!0)},[]),k=o.useCallback(()=>{d(!1)},[]);return o.useEffect(()=>{if(!y){f(!1);return}f(!0);const j=window.setTimeout(()=>{f(!1)},1e4);return()=>window.clearTimeout(j)},[y]),{inboxOpen:n,hiddenOpen:i,shortcutHelpOpen:l,newSessionOpen:m,guideNudgeVisible:h,guideTab:v,shortcutSection:p,isDesktopDashboard:y,setGuideTab:S,setShortcutSection:x,handleInboxOpenChange:g,handleHiddenOpenChange:N,handleOpenShortcutHelp:M,closeShortcutHelp:w,openNewSession:I,closeNewSession:k}}function Lx(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 Rx(e){return e instanceof Error?e.message:String(e||"")}function _x(e){const t=Rx(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Px({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetActiveCliViewMode:m,mobileChatConversations:d,hiddenConversations:h,ides:f,actionLogs:v,sendDaemonCommand:S,setActionLogs:p,setCliViewModeOverrides:x,isStandalone:y,initialDataLoaded:g,userName:N,requestedMobileTabKey:M,onRequestedMobileTabConsumed:w,requestedMachineId:I,onRequestedMachineConsumed:k,requestedMobileSection:j,onRequestedMobileSectionConsumed:b,containerRef:B,isSplitMode:R,numGroups:P,groupSizes:F,groupedConvs:U,clearedTabs:W,focusedGroup:T,focusGroup:L,moveTabToGroup:z,splitTabRelative:$,closeGroup:E,handleResizeStart:V,groupActiveTabIds:q,setGroupActiveTab:ve,groupTabOrders:ne,setGroupTabOrder:pe,toggleHiddenTab:ie,visibleConversations:ge,requestedDesktopTabKey:be,onRequestedDesktopTabConsumed:H,onDesktopActiveTabChange:Q,onRequestScrollToBottom:re,onHideConversation:he,onShowHiddenConversation:ue,onShowAllHiddenConversations:je,scrollToBottomRequest:ce,machineEntries:xe,layoutProfile:Z,onBrowseMachineDirectory:ae,onSaveMachineWorkspace:te,onLaunchMachineIde:Y,onLaunchMachineProvider:X,onListMachineSavedSessions:le,notifications:D,notificationUnreadCount:oe,liveSessionInboxState:J,onMarkNotificationRead:we,onMarkNotificationUnread:Ne,onDeleteNotification:Ae}){const Me=jt.useRef(null),{inboxOpen:Ue,hiddenOpen:We,shortcutHelpOpen:Be,newSessionOpen:Ye,guideNudgeVisible:Xe,guideTab:Je,shortcutSection:Ve,isDesktopDashboard:ht,setGuideTab:ut,setShortcutSection:ft,handleInboxOpenChange:Ce,handleHiddenOpenChange:He,handleOpenShortcutHelp:Qe,closeShortcutHelp:nt,openNewSession:mt,closeNewSession:A}=Ax({isMobile:t,showMobileChatMode:e,visibleConversationCount:ge.length}),C=jt.useCallback(me=>{var Le;Js.flushSync(()=>{ue(me)}),(Le=Me.current)==null||Le.restoreHiddenTabToSavedLocation(me.tabKey)},[ue]),_=jt.useCallback(me=>{var et;const Le=d.find(at=>sa(at,me))||h.find(at=>sa(at,me));Le&&(h.some(at=>at.tabKey===Le.tabKey)&&C(Le),Q(Le.tabKey),(et=Me.current)==null||et.activateConversationTab(Le.tabKey),re(Le.tabKey,"notification-open")),we(me.id),Ce(!1)},[C,h,d,Q,we,re]),O=jt.useCallback(()=>{var Le;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Le=Me.current)==null||Le.resetAllPanelsToMain(),He(!1))},[He]),G=jt.useCallback(async me=>{var Mt;if(!r)return;const Le=(Mt=r.modalButtons)==null?void 0:Mt[me];if(!Le)return;const et=sr(r);if(!et)return;const at=Le.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Oe=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(at);try{await S(et,"resolve_action",{button:Le,action:Oe?"approve":"reject",buttonIndex:me,...ws(r)})}catch(K){_x(K)||console.error("[Shortcut approval] Failed:",K)}},[r,S]),{isMac:ee,actionDefinitions:de,actionShortcuts:ye,shortcutListening:Se,shortcutListeningDraft:Re,setShortcutListening:ke,setShortcutListeningDraft:Ee,saveShortcuts:Ke}=fx({enabled:ht&&!Be,onTrigger:me=>{var Le,et,at,Oe,Mt,K,se,fe,Pe,Te,_e,tt,yt,dt,Ht,lr;if(me==="openShortcutHelp"){Qe();return}if(me==="hideCurrentTab"){r&&he(r);return}if(me==="toggleHiddenTabs"){He(!We);return}if(me==="openHistoryForActiveTab"){r&&!Ge(r)&&i(r);return}if(me==="openRemoteForActiveTab"){r&&!Ze(r)&&!Ge(r)&&c(r);return}if(me==="splitActiveTabRight"){(Le=Me.current)==null||Le.splitActiveTabRight();return}if(me==="splitActiveTabDown"){(et=Me.current)==null||et.splitActiveTabDown();return}if(me==="floatActiveTab"){(at=Me.current)==null||at.floatActiveTab();return}if(me==="popoutActiveTab"){(Oe=Me.current)==null||Oe.popoutActiveTab();return}if(me==="dockActiveTab"){(Mt=Me.current)==null||Mt.dockActiveTab();return}if(me==="focusLeftPane"){(K=Me.current)==null||K.focusLeftPane();return}if(me==="focusRightPane"){(se=Me.current)==null||se.focusRightPane();return}if(me==="focusUpPane"){(fe=Me.current)==null||fe.focusUpPane();return}if(me==="focusDownPane"){(Pe=Me.current)==null||Pe.focusDownPane();return}if(me==="moveActiveTabToLeftPane"){(Te=Me.current)==null||Te.moveActiveTabToLeftPane();return}if(me==="moveActiveTabToRightPane"){(_e=Me.current)==null||_e.moveActiveTabToRightPane();return}if(me==="moveActiveTabToUpPane"){(tt=Me.current)==null||tt.moveActiveTabToUpPane();return}if(me==="moveActiveTabToDownPane"){(yt=Me.current)==null||yt.moveActiveTabToDownPane();return}if(me==="triggerPrimaryApprovalAction"){G(0);return}if(me==="triggerSecondaryApprovalAction"){G(1);return}if(me==="triggerTertiaryApprovalAction"){G(2);return}if(me==="setActiveTabShortcut"){(dt=Me.current)==null||dt.setShortcutForActiveTab();return}if(me==="selectPreviousGroupTab"){(Ht=Me.current)==null||Ht.activatePreviousTabInGroup();return}if(me==="selectNextGroupTab"){(lr=Me.current)==null||lr.activateNextTabInGroup();return}!r||!Ze(r)||Ge(r)||me==="toggleCliView"&&m(u==="chat"?"terminal":"chat")}}),$e=jt.useCallback(()=>{nt(),ke(null),Ee([])},[nt,ke,Ee]),Ie=jt.useMemo(()=>Ve==="all"?de:de.filter(me=>Lx(me)===Ve),[de,Ve]),qe=jt.useCallback(()=>{const me=Object.fromEntries(de.map(Le=>[Le.id,""]));Ke(me)},[de,Ke]),ct=jt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const me=Object.fromEntries(de.map(Le=>[Le.id,Le.defaultShortcut]));Ke(me)},[de,Ke]);return jt.useEffect(()=>{const me=Le=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Le.metaKey&&Le.key.toLowerCase()==="w":Le.ctrlKey&&Le.key.toLowerCase()==="w")&&(Le.preventDefault(),r&&he&&he(r))};return window.addEventListener("keydown",me),()=>window.removeEventListener("keydown",me)},[r,he]),jt.useEffect(()=>{if(!Be||Se)return;const me=Le=>{Le.key==="Escape"&&(Le.preventDefault(),$e())};return window.addEventListener("keydown",me,!0),()=>window.removeEventListener("keydown",me,!0)},[$e,Be,Se]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Nf,{activeConv:r,wsStatus:n,isConnected:a,conversations:ge,hiddenConversations:h,onOpenHistory:i,onHideConversation:he,onShowConversation:C,onShowAllHidden:je,onResetPanelsToMain:O,notifications:D,notificationUnreadCount:oe,onOpenNotification:_,onMarkNotificationRead:we,onMarkNotificationUnread:Ne,onDeleteNotification:Ae,inboxOpen:Ue,onInboxOpenChange:Ce,hiddenOpen:We,onHiddenOpenChange:He,onOpenNewSession:t?void 0:mt,actionShortcuts:ye,onOpenRemote:()=>{!r||Ze(r)||Ge(r)||c(r)},onStopCli:l,activeCliViewMode:u,onSetCliViewMode:m}),e?s.jsx(tx,{conversations:d,hiddenConversations:h,ides:f,actionLogs:v,sendDaemonCommand:S,setActionLogs:p,setCliViewModeOverrides:x,isStandalone:y,userName:N,requestedActiveTabKey:M,onRequestedActiveTabConsumed:w,requestedMachineId:I,onRequestedMachineConsumed:k,requestedMobileSection:j,onRequestedMobileSectionConsumed:b,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowHiddenConversation:C,onShowAllHiddenConversations:je,onOpenNewSession:mt,liveSessionInboxState:J}):t?s.jsx(lx,{containerRef:B,isSplitMode:R,numGroups:P,groupSizes:F,groupedConvs:U,clearedTabs:W,ides:f,actionLogs:v,sendDaemonCommand:S,setActionLogs:p,isStandalone:y,hasRegisteredMachines:xe.length>0,userName:N,focusedGroup:T,focusGroup:L,moveTabToGroup:z,splitTabRelative:$,closeGroup:E,handleResizeStart:V,groupActiveTabIds:q,setGroupActiveTab:ve,groupTabOrders:ne,setGroupTabOrder:pe,toggleHiddenTab:ie,onOpenNewSession:mt,allowTabShortcuts:!1,liveSessionInboxState:J}):s.jsx(Nx,{visibleConversations:ge,clearedTabs:W,ides:f,actionLogs:v,sendDaemonCommand:S,setActionLogs:p,isStandalone:y,hasRegisteredMachines:xe.length>0,initialDataLoaded:g,userName:N,toggleHiddenTab:ie,actionShortcuts:ye,registerActionHandlers:me=>{Me.current=me},onActiveTabChange:Q,requestedActiveTabKey:be,onRequestedActiveTabConsumed:H,onRequestScrollToBottom:re,scrollToBottomRequest:ce,onOpenNewSession:mt,liveSessionInboxState:J,layoutProfile:Z}),Ye&&s.jsx(Ix,{machines:xe,ides:f,onClose:A,onBrowseDirectory:ae,onSaveWorkspace:te,onLaunchIde:Y,onLaunchProvider:X,onListSavedSessions:le}),Be&&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:$e,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:me=>me.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:$e,"aria-label":"Close dashboard guide",children:s.jsx(vt,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(me=>s.jsx("button",{type:"button",className:`btn btn-sm ${Je===me.id?"btn-primary":"btn-secondary"}`,onClick:()=>ut(me.id),children:me.label},me.id))}),Je==="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 ",ee?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Je==="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."]})]})]})]}),Je==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(me=>s.jsx("button",{type:"button",className:`btn btn-sm ${Ve===me.id?"btn-primary":"btn-secondary"}`,onClick:()=>ft(me.id),children:me.label},me.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:qe,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:ct,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Ie.map(me=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Se===me.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:me.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:me.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:me.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:Se===me.id?Re.length>0?`${Re.join(" ")} ...`:"Listening...":ye[me.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{ke(me.id),Ee([])},children:Se===me.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Le={...ye};Le[me.id]="",Ke(Le)},children:"Disable"})]})]})},me.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",ee?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&s.jsxs("button",{type:"button",onClick:Qe,className:`fixed right-4 bottom-24 z-40 hidden md:inline-flex items-center rounded-full border border-border-subtle bg-bg-primary/88 backdrop-blur py-2 text-xs text-text-secondary hover:text-text-primary transition-all ${Xe?"gap-2 px-2.5":"justify-center w-10 px-0"}`,style:{boxShadow:"0 6px 18px rgba(0,0,0,0.12)"},title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"inline-flex items-center justify-center w-5 h-5 rounded-full bg-bg-secondary text-[11px] font-semibold text-text-primary shrink-0",children:"?"}),Xe&&s.jsx("span",{children:"Guide"})]})]})}const En=[{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 Dx({onClose:e}){const[t,r]=o.useState(0),n=En[t],a=t===En.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:i=>{i.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(vt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:En.map((i,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(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
54
- @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
55
- @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
56
- `})]})}function Ex({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(i=>{const c=r===i.tabKey,l=i.status==="waiting_approval",u=i.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(i.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"}}),i.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:"!"})]},i.tabKey)})]}):null}function $x({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,c]=o.useState(()=>a||"native"),l=o.useMemo(()=>Cc(t),[t]),u=o.useMemo(()=>e?Wa(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),m=o.useMemo(()=>u.find(p=>p.streamSource==="native"),[u]),d=o.useMemo(()=>u.filter(p=>p.streamSource==="agent-stream"),[u]),h=o.useMemo(()=>e?_t(u,e.id):null,[u,e]);o.useEffect(()=>{a&&c(a)},[a]),o.useEffect(()=>{if(a||!h)return;const p=h.streamSource==="native"?"native":h.tabKey;!p||i===p||i==="native"&&c(p)},[i,h,a]),o.useEffect(()=>{var p;i!=="native"&&(d.some(x=>x.tabKey===i)||c(((p=d[0])==null?void 0:p.tabKey)||"native"))},[i,d]),o.useEffect(()=>{i==="native"&&(m||d[0]&&c(d[0].tabKey))},[i,m,d]);const f=o.useMemo(()=>i==="native"&&m?m:d.find(p=>p.tabKey===i)||h||m||d[0],[i,m,h,d]),v=o.useMemo(()=>d.map(p=>({tabKey:p.tabKey,title:yc(p)||n,status:p.status})),[d,n]),S=o.useCallback(p=>{if(p)return u.find(x=>sa(x,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[u]);return{activeChatTab:i,setActiveChatTab:c,activeConv:f,conversations:u,extensionTabs:v,hasExtensions:v.length>0,resolveConversationByTarget:S}}function Bx({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:i,setActionLogs:c,isStandalone:l,userName:u,onOpenHistory:m,onConversationChange:d,onClose:h}){const[f,v]=o.useState("split"),[S,p]=o.useState(()=>Ut(e)?"native":e.tabKey),x=o.useRef(null),y=o.useMemo(()=>t||r.find(L=>L.id===e.routeId),[e.routeId,t,r]),g=o.useMemo(()=>rt((y==null?void 0:y.type)||""),[y==null?void 0:y.type]),{conversations:N,extensionTabs:M,hasExtensions:w}=$x({ideData:y,allIdes:r,connectionStates:n,ideName:g||"IDE",preferredTabKey:Ut(e)?void 0:e.tabKey}),I=o.useMemo(()=>y?_t(N,y.id):null,[y,N]);o.useEffect(()=>{const L=x.current,z={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(x.current=z,!(L&&L.routeId===z.routeId&&L.tabKey===z.tabKey&&L.streamSource===z.streamSource)){if(Ut(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(S==="native"){if(N.some(L=>L.streamSource==="native"))return;(I==null?void 0:I.streamSource)==="agent-stream"&&p(I.tabKey);return}if(!N.some(L=>L.tabKey===S)){if((I==null?void 0:I.streamSource)==="agent-stream"){p(I.tabKey);return}p("native")}},[N,S,I]);const k=o.useMemo(()=>S==="native"?N.find(L=>L.streamSource==="native")||e:N.find(L=>L.tabKey===S)||e,[e,N,S]),j=Oc(k),b=o.useMemo(()=>j.status||j.modalMessage||j.modalButtons?{...k,...j.status?{status:j.status}:{},...j.modalMessage!==void 0?{modalMessage:j.modalMessage}:{},...j.modalButtons!==void 0?{modalButtons:j.modalButtons}:{}}:k,[k,j]),B=Rs(b),R=on({sendDaemonCommand:i,activeConv:b,setActionLogs:c,isStandalone:l}),{connScreenshot:P,screenshotUsage:F,handleRemoteAction:U}=ol({doId:B,targetSessionId:ac(b),connState:b.connectionState||"new",viewMode:f}),W=o.useMemo(()=>a.filter(L=>L.routeId===b.tabKey),[a,b.tabKey]);o.useEffect(()=>{d==null||d(b)},[b,d]),o.useEffect(()=>{const L=z=>{z.key==="Escape"&&h()};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[h]);const T=o.useCallback(L=>{L.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:T,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(St,{size:16})}),s.jsx("span",{className:"truncate",children:Ma(k)||"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(L=>{const z=f===L;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(L),title:L==="split"?"Split view":"Remote only",children:L==="split"?s.jsx($d,{size:15}):s.jsx(St,{size:15})},L)})}),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(k),title:"Chat History",children:[s.jsx(va,{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(Ex,{hasExtensions:w,ideName:g||"IDE",activeChatTab:S,extensionTabs:M,onSelectTab:p}),s.jsx(Ui,{activeConv:b,onModalButton:R.handleModalButton}),s.jsx(ia,{activeConv:b,ideEntry:y,showMetaChips:!1,handleSendChat:R.handleSendChat,isSendingChat:R.isSendingChat,sendFeedbackMessage:R.sendFeedbackMessage,handleFocusAgent:R.handleFocusAgent,isFocusingAgent:R.isFocusingAgent,actionLogs:W,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(Hi,{addLog:()=>{},connState:b.connectionState||"new",connScreenshot:P,screenshotUsage:F,transportType:b.transport,onAction:U})})]})]})})}function Kx({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=gf(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 ",i,"?"]}),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 Ox({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){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(Oa,{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(Bx,{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)||Ge(r.targetConv))&&s.jsx(Kx,{activeConv:r.targetConv,canSaveAndStop:Ze(r.targetConv)&&!Ge(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(Nc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&s.jsx(Dx,{onClose:i.onClose})]})}function Wx({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:i}){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(nr,{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=Tt(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:i,title:"Dismiss",children:s.jsx(vt,{size:16})})]})}function Hx(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Fx(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 Ux(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>Fx(t)).map(t=>t.id)}}function zx(){var no,ao,oo,io;const{sendCommand:e}=wt(),t=ir(),r=Kc(),n=ba(),a=Is(),[i,c]=nd(),l=i.get("activeTab"),u=((no=n.state)==null?void 0:no.openRemoteForTabKey)||null,m=((ao=n.state)==null?void 0:ao.openMachineId)||null,d=((oo=n.state)==null?void 0:oo.mobileSection)||null,h=hc(),f=h.ides||[],v=h.initialLoaded??!0,{updateRouteChats:S,setToasts:p}=h,[x,y]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),g=h.toasts||[],N=h.wsStatus||"connected",M=h.isConnected??!0,w=h.connectionStates||{},I=h.showReconnected||!1,{layoutProfile:k,groupAssignments:j,updateGroupAssignments:b,focusedGroup:B,updateFocusedGroup:R,focusGroup:P,groupActiveTabIds:F,updateGroupActiveTabIds:U,setGroupActiveTab:W,groupTabOrders:T,updateGroupTabOrders:L,setGroupTabOrder:z,groupSizes:$,updateGroupSizes:E,isMobile:V,hasHydratedStoredLayout:q,hydrateStoredLayout:ve,focusConversationTab:ne}=Zp(),[pe,ie]=o.useState(()=>za());o.useEffect(()=>bp(ie),[]);const ge=o.useMemo(()=>Hx({isMobile:V,mobileViewMode:pe}),[V,pe]),[be,H]=o.useState([]),[Q,re]=o.useState({}),[he,ue]=o.useState({});ar("Dashboard",{ideCount:f.length,toastCount:g.length,focusedGroup:B,groupCount:Object.keys(j).length,actionLogCount:be.length});const je=o.useMemo(()=>f.filter(Fe=>Fe.type==="adhdev-daemon").sort(Na),[f]),ce=je[0],xe=!!ce;o.useEffect(()=>{const{metadataDaemonIds:Fe,runtimeDaemonIds:It}=Ux(je);for(const _s of Fe)t(_s,{minFreshMs:3e4}).catch(()=>{});for(const _s of It)r(_s,{minFreshMs:3e4}).catch(()=>{})},[t,r,je]);const Z=(ce==null?void 0:ce.terminalBackend)||null,ae=ce?Tt(ce,{fallbackId:ce.id}):null,te=(ce==null?void 0:ce.id)||null,Y=o.useMemo(()=>Mp(f,Q),[f,Q]),{hiddenTabs:X,hideTarget:le,toggleTarget:D,showTarget:oe,showAllTabs:J}=Tp(),{conversations:we,visibleConversations:Ne,visibleTabKeys:Ae,resolveConversationBySessionId:Me,resolveConversationByTarget:Ue}=Bp({ides:Y,connectionStates:w,clearedTabs:he,hiddenTabs:X}),We=o.useMemo(()=>new Map(we.map(Fe=>[Fe.tabKey,Fe])),[we]),Be=ef(Ne,ge),Ye=o.useMemo(()=>Ro(we,Be),[we,Be]),Xe=o.useMemo(()=>Ro(Ne,Be),[Ne,Be]);o.useEffect(()=>{Object.keys(Q).length!==0&&re(Fe=>Ip(Fe,f))},[f,Q]);const Je=o.useMemo(()=>Su(f),[f]),{notifications:Ve,unreadCount:ht}=ph({conversations:Ye,liveSessionInboxState:Je}),{handleMarkDashboardNotificationRead:ut,handleMarkDashboardNotificationUnread:ft,handleDeleteDashboardNotification:Ce}=hh({notifications:Ve,sendDaemonCommand:e}),{containerRef:He,normalizedGroupAssignments:Qe,numGroups:nt,isSplitMode:mt,groupedConvs:A,moveTabToGroup:C,closeGroup:_,handleResizeStart:O,splitTabRelative:G}=oh({groupAssignments:j,updateGroupAssignments:b,updateFocusedGroup:R,updateGroupActiveTabIds:U,updateGroupTabOrders:L,groupSizes:$,updateGroupSizes:E,isMobile:V,visibleConversations:Xe,visibleTabKeys:Ae}),{activeConv:ee,openDesktopConversation:de,requestScrollToBottom:ye,scrollToBottomRequest:Se,setDesktopActiveTab:Re}=Nh({isMobile:V,conversations:Ye,visibleConversations:Xe,groupActiveTabIds:F,focusedGroup:B,groupedConvs:A,setSearchParams:c});Mh({activeConv:ee,isMobile:V,liveSessionInboxState:Je,sendDaemonCommand:e});const{requestedDesktopTabKey:ke,requestedMobileTabKey:Ee,consumeRequestedActiveTab:Ke}=Kp({isMobile:V,urlActiveTab:l,resolveConversationBySessionId:Me,setSearchParams:c}),{remoteDialogConv:$e,remoteDialogIdeEntry:Ie,remoteDialogActiveConv:qe,setRemoteDialogActiveConv:ct,openRemoteDialog:me,closeRemoteDialog:Le,cliStopDialogOpen:et,cliStopTargetConv:at,requestCliStop:Oe,cancelCliStop:Mt,confirmCliStop:K}=Lh({isMobile:V,location:n,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:ke,conversations:we,ides:f,resolveConversationByTarget:Ue,activeConv:ee,sendDaemonCommand:e}),{historyModalOpen:se,openHistoryModal:fe,closeHistoryModal:Pe,historyTargetConv:Te,isSavedSessionHistoryTarget:_e,isHistoryCreatingChat:tt,isHistoryRefreshingHistory:yt,handleHistorySwitchSession:dt,handleHistoryNewChat:Ht,handleHistoryRefresh:lr,savedHistorySessions:Sl,savedHistoryFilters:Nl,setSavedHistoryFilters:Cl,isSavedHistoryLoading:Tl,resumingSavedHistorySessionId:Ml,handleRefreshSavedHistory:Il,handleResumeSavedHistorySession:Al}=Ih({activeConv:ee,remoteDialogConv:$e,remoteDialogActiveConv:qe,ides:f,sendDaemonCommand:e,updateRouteChats:S,setToasts:p,setClearedTabs:ue,setSearchParams:c}),Ll=o.useMemo(()=>Xe,[Xe]),dr=V&&pe==="chat",Rl=o.useMemo(()=>Ye.filter(Fe=>Va(X,Fe)),[Ye,X]),to=o.useCallback(Fe=>{const It=new URLSearchParams(i);It.set("activeTab",Fe),c(It,{replace:!0})},[i,c]),{trackPendingLaunch:_l}=wh({ides:f,conversations:we,onOpenSession:to}),{handleBrowseMachineDirectory:Pl,handleSaveMachineWorkspace:Dl,handleLaunchMachineIde:El,handleLaunchMachineProvider:$l,handleListMachineSavedSessions:Bl,setActiveCliViewMode:Kl}=jh({sendDaemonCommand:e,trackPendingLaunch:_l,onOpenSession:to,activeConv:ee,ides:f,setCliViewModeOverrides:re});Ap({visibleConversations:Ne,clearedTabs:he,setClearedTabs:ue,setActionLogs:H}),Op({ides:f,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Ue});const{isRefreshingHistory:Ol,handleRefreshHistory:Wl}=Xc({sendDaemonCommand:e,activeConv:ee,chats:(io=f.find(Fe=>Fe.id===(ee==null?void 0:ee.routeId)))==null?void 0:io.chats,updateRouteChats:S,setToasts:p,setClearedTabs:ue});th({urlActiveTab:V&&!dr?l:null,conversations:we,resolveConversationBySessionId:Me,normalizedGroupAssignments:Qe,hasHydratedStoredLayout:V&&!dr?q:!0,hydrateStoredLayout:V&&!dr?ve:()=>{},focusConversationTab:ne,setSearchParams:c,historyModalOpen:se,activeConv:ee,isRefreshingHistory:Ol,ides:f,handleRefreshHistory:Wl});const Hl=o.useMemo(()=>!ee||!Ze(ee)||Ge(ee)?null:Ls(ee),[ee]),{versionMismatchDaemons:Fl,hasRequiredVersionDaemons:so,appVersion:Ul,versionBannerDismissed:zl,setVersionBannerDismissed:Vl,upgradingDaemons:Gl,handleBannerUpgrade:ql}=ih({ides:f,sendDaemonCommand:e}),ro=o.useCallback(Fe=>{oe(Fe),de(Fe)},[de,oe]),Yl=o.useCallback(Fe=>{le(Fe)},[le]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[s.jsx(kf,{terminalBackend:Z,isStandalone:xe,machineLabel:ae,machineKey:te}),(!zl||so)&&s.jsx(Wx,{daemons:Fl,targetVersion:Ul,required:so,upgradingDaemons:Gl,onUpgrade:ql,onDismiss:()=>Vl(!0)}),s.jsx(Px,{showMobileChatMode:dr,isMobile:V,activeConv:ee,wsStatus:N,isConnected:M,onOpenHistory:Fe=>{Fe&&ct(Fe),fe()},onOpenRemote:me,onStopCli:Oe,activeCliViewMode:Hl,onSetActiveCliViewMode:Kl,mobileChatConversations:Ll,ides:f,actionLogs:be,sendDaemonCommand:e,setActionLogs:H,setCliViewModeOverrides:re,isStandalone:xe,initialDataLoaded:v,userName:h.userName,requestedMobileTabKey:Ee,onRequestedMobileTabConsumed:Ke,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:He,isSplitMode:mt,numGroups:nt,groupSizes:$,groupedConvs:A,clearedTabs:he,focusedGroup:B,focusGroup:P,moveTabToGroup:C,splitTabRelative:G,closeGroup:_,handleResizeStart:O,groupActiveTabIds:F,setGroupActiveTab:W,groupTabOrders:T,setGroupTabOrder:z,toggleHiddenTab:Fe=>D(We.get(Fe)||{tabKey:Fe}),visibleConversations:Xe,hiddenConversations:Rl,requestedDesktopTabKey:ke,onRequestedDesktopTabConsumed:Ke,onDesktopActiveTabChange:Re,onRequestScrollToBottom:ye,onHideConversation:Yl,onShowHiddenConversation:ro,onShowAllHiddenConversations:J,scrollToBottomRequest:Se,machineEntries:je,layoutProfile:k,onBrowseMachineDirectory:Pl,onSaveMachineWorkspace:Dl,onLaunchMachineIde:El,onLaunchMachineProvider:$l,onListMachineSavedSessions:Bl,notifications:Ve,notificationUnreadCount:ht,liveSessionInboxState:Je,onMarkNotificationRead:ut,onMarkNotificationUnread:ft,onDeleteNotification:Ce}),s.jsx("style",{children:`
57
- body { overflow: hidden; overscroll-behavior: none; }
58
- `}),s.jsx(Ox,{historyModal:{open:se,targetConv:Te,ides:f,isCreatingChat:tt,isRefreshingHistory:_e?!1:yt,savedSessions:Sl,savedHistoryFilters:Nl,onSavedHistoryFiltersChange:Cl,isSavedSessionsLoading:Tl,isResumingSavedSessionId:Ml,onClose:Pe,onNewChat:Ht,onSwitchSession:dt,onRefreshHistory:_e?Il:lr,onResumeSavedSession:Al},remoteDialog:{conversation:$e,ideEntry:Ie,ides:f,connectionStates:w,actionLogs:be,sendDaemonCommand:e,setActionLogs:H,isStandalone:xe,userName:h.userName,onOpenHistory:Fe=>{Fe&&ct(Fe),fe()},onConversationChange:ct,onClose:Le},cliStopDialog:{open:et,targetConv:at,onCancel:Mt,onStopNow:async()=>{await K("hard")},onSaveAndStop:async()=>{await K("save")}},connectionBanner:{wsStatus:N,showReconnected:I,loginUrl:h.connectionLoginUrl,onReconnect:h.retryServerConnection},toastOverlay:{toasts:g,onDismiss:Fe=>p(It=>It.filter(_s=>_s.id!==Fe)),onClick:Fe=>{if(Fe.targetKey){const It=Ue(Fe.targetKey);It&&(ne(It.tabKey,Qe),ro(It),ye(It.tabKey,"toast-open"))}}},onboarding:{open:x,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}y(!1)}}})]})}function Vx({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,u]=o.useState(null),[m,d]=o.useState(null),[h,f]=o.useState(!1),[v,S]=o.useState(null),[p,x]=o.useState(!1),[y,g]=o.useState(""),N=o.useRef(null),M=o.useCallback($=>{N.current=$},[]),w=o.useCallback(($,E,V=!1)=>{c(q=>[...q.slice(-100),{timestamp:Date.now(),level:$,message:E}]),setTimeout(()=>{var q;return(q=a.current)==null?void 0:q.scrollIntoView({behavior:"smooth"})},100),V&&it.showToast(E,$==="error"||$==="warn"?"warning":"success")},[a]),I=o.useCallback($=>{const E=$ instanceof Error?$.message:String($||"");return E.includes("P2P command timeout")||E.includes("P2P not connected")||E.includes("P2P not available")},[]),k=o.useCallback(async($,E)=>{var V;if(!e||l)return!1;u($),w("info",`Launching ${rt($)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const q={ideType:$,enableCdp:!0};(V=E==null?void 0:E.workspace)!=null&&V.trim()?q.workspace=E.workspace.trim():E!=null&&E.useDefaultWorkspace&&(q.useDefaultWorkspace=!0);const ve=await r(e,"launch_ide",q);return w(ve!=null&&ve.success?"info":"error",ve!=null&&ve.success?`${rt($)} launched`:`Failed: ${ve==null?void 0:ve.error}`,!0),!!(ve!=null&&ve.success)}catch(q){return w("error",`Launch error: ${q.message}`,!0),!1}finally{u(null)}},[e,l,w,r]),j=o.useCallback(async $=>{if(!e)return{success:!1};const{cliType:E,dir:V,workspaceId:q,useDefaultWorkspace:ve,useHome:ne,argsStr:pe,model:ie,resumeSessionId:ge}=$;if(!E)return w("warn","Select a CLI or ACP provider first",!0),{success:!1};const be=pe?pe.split(/\s+/).filter(Boolean):void 0,H=(V==null?void 0:V.trim())||(q?"(saved id)":ve?"(default workspace)":ne?"(home)":"");w("info",`Launching ${E}${H?` in ${H}`:""}${ie?` (model: ${ie})`:""}...`),d(E);try{const Q={cliType:E,cliArgs:be,initialModel:ie||void 0};V!=null&&V.trim()?Q.dir=V.trim():q?Q.workspaceId=q:ve?Q.useDefaultWorkspace=!0:ne&&(Q.useHome=!0),ge&&(Q.resumeSessionId=ge);const re=await r(e,"launch_cli",Q),he=(re==null?void 0:re.result)||re;return re!=null&&re.success?(w("info",`${E} launched`,!0),(he==null?void 0:he.launchSource)==="home"?w("info","📂 Running in home directory (explicit choice)"):(he==null?void 0:he.launchSource)==="defaultWorkspace"&&w("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:he==null?void 0:he.sessionId}):(w("error",`Failed: ${(re==null?void 0:re.error)||(he==null?void 0:he.error)}`,!0),(re==null?void 0:re.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&S({cliType:E,argsStr:pe,model:ie}),{success:!1,sessionId:he==null?void 0:he.sessionId})}catch(Q){return I(Q)?(w("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(w("error",`Launch error: ${Q.message}`,!0),{success:!1})}finally{d(null)}},[e,w,I,r]),b=o.useCallback(async($,E,V,q)=>e?$?E.trim()?j({cliType:$,dir:E,argsStr:V,model:q}):(S({cliType:$,argsStr:V,model:q}),{success:!1}):(w("warn","Select a provider",!0),{success:!1}):{success:!1},[e,w,j]),B=o.useCallback(async($,E,V)=>{if(e&&window.confirm(`Stop ${$}?
59
- This will terminate the process.`))try{const q=await r(e,"stop_cli",{cliType:$,dir:E,targetSessionId:V});q!=null&&q.success?w("info",`${$} stopped`,!0):w("error",`Stop failed: ${(q==null?void 0:q.error)||"Unknown error"}`,!0)}catch(q){w("error",`Stop failed: ${q.message}`,!0)}},[e,w,r]),R=o.useCallback(async $=>{try{await r($.daemonId,"restart_ide",{ideType:$.type}),w("info",`${rt($.type)} restart initiated`,!0)}catch(E){w("error",`Restart failed: ${E.message}`,!0)}},[w,r]),P=o.useCallback(async $=>{if(window.confirm(`Stop ${rt($.type)}?
60
- This will disconnect CDP and optionally kill the process.`))try{const E=await r($.daemonId,"stop_ide",{ideType:$.type,killProcess:!0});E!=null&&E.success?w("info",`${rt($.type)} stopped`,!0):w("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){w("error",`Stop failed: ${E.message}`,!0)}},[w,r]),F=o.useCallback(async()=>{if(e)try{const $=await r(e,"detect_ides",{});w("info",`Found ${(($==null?void 0:$.result)||[]).length} IDE(s)`,!0)}catch($){w("error",`Detection failed: ${$.message}`,!0)}},[e,w,r]),U=o.useCallback(async $=>{if(!e||!$.trim())return!1;f(!0);try{const E=await r(e,"workspace_add",{path:$.trim()});return E!=null&&E.success?(w("info",`Workspace added: ${$.trim()}`),!0):(w("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return w("error",E.message),!1}finally{f(!1)}},[e,w,r]),W=o.useCallback(async $=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){f(!0);try{const E=await r(e,"workspace_remove",{id:$});E!=null&&E.success?w("info","Workspace removed",!0):w("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){w("error",E.message,!0)}finally{f(!1)}}},[e,w,r]),T=o.useCallback(async $=>{var E;if(e){f(!0);try{const V=await r(e,"workspace_set_default",$===null?{clear:!0}:{id:$});if(V!=null&&V.success){w("info",$?"Default workspace updated":"Default workspace cleared",!0);const q=typeof V.defaultWorkspacePath=="string"?V.defaultWorkspacePath:"";q&&((E=N.current)==null||E.call(N,q))}else w("error",(V==null?void 0:V.error)||"workspace_set_default failed",!0)}catch(V){w("error",V.message,!0)}finally{f(!1)}}},[e,w,r]),L=o.useCallback(async $=>{var V;if(!e||!$.trim())return;const E=$.trim();f(!0);try{const q=await r(e,"workspace_set_default",{path:E});q!=null&&q.success?(w("info","Default workspace set from history"),(V=N.current)==null||V.call(N,E)):w("error",(q==null?void 0:q.error)||"Could not set default (path missing on disk?)")}catch(q){w("error",q.message)}finally{f(!1)}},[e,w,r]),z=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:y})}catch($){w("warn",`Live nickname updated, but account sync failed: ${$.message}`)}w("info",`Nickname set to "${y||"(cleared)"}"`),x(!1)}catch($){w("error",`Failed: ${$.message}`)}},[e,y,t,w,n,r]);return{logs:i,launchingIde:l,launchingAgentType:m,workspaceBusy:h,launchPick:v,setLaunchPick:S,editingNickname:p,setEditingNickname:x,nicknameInput:y,setNicknameInput:g,addLog:w,handleLaunchIde:k,runLaunchCliCore:j,handleLaunchCli:b,handleStopCli:B,handleRestartIde:R,handleStopIde:P,handleDetectIdes:F,handleWorkspaceAdd:U,handleWorkspaceRemove:W,handleWorkspaceSetDefault:T,handleWorkspaceResumePath:L,handleSaveNickname:z,setOnDefaultWorkspaceChanged:M}}function Gx({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var R;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:m,handleWorkspaceSetDefault:d}=i,[h,f]=o.useState(!1),[v,S]=o.useState(""),[p,x]=o.useState([]),[y,g]=o.useState(!1),[N,M]=o.useState(""),w=o.useCallback(async P=>{g(!0),M("");try{const F=await an(c,e,P);S(F.path),x(F.directories)}catch(F){M(F instanceof Error?F.message:"Could not load folder")}finally{g(!1)}},[e,c]),I=o.useCallback(()=>{f(!0);const P=[...r.map(U=>U.workspace),...n.map(U=>U.workspace),...a.map(U=>U.workspace)],F=nn(t.platform,rn(P,t.defaultWorkspacePath,(t.workspaces||[]).map(U=>U.path)));w(F)},[a,n,r,w,t.defaultWorkspacePath,t.platform,t.workspaces]),k=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,j=t.availableMem??t.freeMem??t.totalMem,b=k&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-j)/t.totalMem*100))):0,B=((R=t.loadavg)==null?void 0:R[0])||0;return s.jsxs("div",{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[s.jsx(fr,{icon:s.jsx(Di,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?Mu(t.uptime):"Waiting…"}),s.jsx(fr,{icon:s.jsx(St,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(fr,{icon:s.jsx(wa,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(fr,{icon:s.jsx(Kd,{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(bo,{value:k?Math.min(Math.round(B/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:k?`${B.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(bo,{value:b,max:100,label:"Memory",color:"#3b82f6",detail:k?`${xn(t.totalMem-j)} / ${xn(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${xn(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(Ss,{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:P=>void d(P.target.value===""?null:P.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(P=>s.jsx("option",{value:P.id,children:P.label||P.path},P.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(P=>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:[P.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:en(P.path,P.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:P.path,children:P.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void m(P.id),children:"Remove"})]},P.id))})]}),h&&s.jsx(cn,{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:y,error:N,confirmLabel:"Add workspace",onClose:()=>f(!1),onNavigate:P=>{w(P)},onConfirm:P=>{(async()=>{if(!P)return;await u(P)&&f(!1)})()}})]})}function qx(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 Yx(e,t,r){const n=[];for(const[a,i]of Object.entries(e.settings)){const c=r!=null&&r.filterSchema?r.filterSchema(i):i;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 $n(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 oi(e){if(!e||typeof e!="object")return null;if($n(e))return e;const t=e,r=t.result;return $n(r)?r:$n(t.sourceConfig)?t.sourceConfig:null}function Xx(e){const t=e.trim();return t||null}const ii=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Jx=[{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 Qx({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[u,m]=o.useState([]),[d,h]=o.useState(""),[f,v]=o.useState([]),[S,p]=o.useState(""),x=o.useRef(null),y=o.useRef(null),g=j=>{m(b=>b.includes(j)?b.filter(B=>B!==j):[...b,j])},N=()=>m([...ii]),M=()=>m([]);o.useEffect(()=>{var j;(j=x.current)==null||j.scrollIntoView({behavior:"smooth"})},[f]),o.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const w=o.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const j=await r(e,"provider_auto_fix_status",{providerType:t.type});(j==null?void 0:j.running)===!1&&a==="running"&&(i("done"),v(b=>[...b,`
61
- ✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[e,t.type,r,a]),I=async()=>{if(u.length!==0){i("running"),v(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,d?`💬 Comment: ${d}`:"",""]),p("");try{const j=await r(e,"provider_auto_fix",{providerType:t.type,functions:u,agent:c,...d?{comment:d}:{}});j!=null&&j.success&&(j!=null&&j.started||j!=null&&j.running)?(v(b=>[...b,"✅ Agent started. Monitoring progress..."]),w()):(i("error"),p((j==null?void 0:j.error)||"Failed to start auto-fix"))}catch(j){i("error"),p((j==null?void 0:j.message)||"Connection failed")}}},k=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),v(j=>[...j,`
62
- ⚠️ Auto-fix cancelled.`]),i("done"),y.current&&clearInterval(y.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:j=>j.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:Jx.map(j=>s.jsxs("button",{onClick:()=>l(j.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===j.value?j.color+"66":"var(--border-subtle)",background:c===j.value?j.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===j.value?j.color:"var(--text-primary)"},children:j.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:j.desc})]},j.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:N,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:M,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:ii.map(j=>s.jsxs("button",{onClick:()=>g(j),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(j)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(j)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(j)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(j)?"☑ ":"☐ ",j]},j))})]}),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:j=>h(j.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((j,b)=>s.jsx("div",{className:j.startsWith("✅")?"text-green-400":"",style:j.startsWith("❌")||j.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:j},b)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:x})]}),S&&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:S})]})]}),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:k,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:()=>{i("config"),v([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Zx({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var w;const i=t.filter(I=>I.category==="ide"),[c,l]=o.useState(((w=i[0])==null?void 0:w.type)||""),[u,m]=o.useState(""),[d,h]=o.useState(""),[f,v]=o.useState(!1),[S,p]=o.useState(""),[x,y]=o.useState(!1),g=I=>{const k=I.toLowerCase().replace(/[^a-z0-9-]/g,"");m(k),(!d||d===N(u))&&h(N(k))},N=I=>I.split("-").map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(" "),M=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?(y(!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:x?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:i.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=>g(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"})]}),S&&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:S})]})}),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:x?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:M,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 ci(e){return e==="cli"||e==="acp"}function eb(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 tb(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 li(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 sb({machineId:e,providers:t,sendDaemonCommand:r}){var U;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[m,d]=o.useState("all"),[h,f]=o.useState(null),[v,S]=o.useState(!1),[p,x]=o.useState(null),[y,g]=o.useState("normal"),[N,M]=o.useState(""),[w,I]=o.useState(!1),k=o.useCallback(async()=>{if(e)try{const W=await r(e,"get_provider_source_config",{}),T=oi(W);T&&(x(T),g(T.sourceMode),M(T.explicitProviderDir||""))}catch{}},[e,r]),j=o.useCallback(async()=>{if(e){c(!0);try{const W=await r(e,"get_provider_settings",{}),T=qx(W);if(T){const L=Yx(T,t,{filterSchema:z=>z.filter($=>$.key!=="enabled")});L.sort((z,$)=>z.category.localeCompare($.category)||z.displayName.localeCompare($.displayName)),a(L)}}catch{}c(!1)}},[e,t,r]);o.useEffect(()=>{n.length===0&&j(),p||k()},[]);const b=async(W,T,L)=>{u(`${W}.${T}`),a(z=>z.map($=>$.type===W?{...$,values:{...$.values,[T]:L}}:$));try{const z=await r(e,"set_provider_setting",{providerType:W,key:T,value:L});z!=null&&z.success||j()}catch{j()}u(null)},B=async(W,T)=>{await b(W,"enabled",T),await j()},R=async W=>{u(`${W}.detect`);try{await r(e,"detect_provider",{providerType:W})}finally{await j(),u(null)}},P=async W=>{await b(W,"executablePath",""),await b(W,"executableArgs",""),await j()},F=async()=>{I(!0);try{const W=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:Xx(N)}),T=oi(W);T?(x(T),g(T.sourceMode),M(T.explicitProviderDir||"")):await k(),await j()}catch{await k()}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(W=>s.jsx("button",{onClick:()=>d(W),className:`machine-btn text-[10px] px-2 py-0.5 ${m===W?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:W.toUpperCase()},W))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>S(!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:j,disabled:i,className:"machine-btn",children:i?"⏳ 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. Existing running sessions may need restart."})]}),s.jsx("button",{onClick:k,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:y,onChange:W=>g(W.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:N,onChange:W=>M(W.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void F(),disabled:w,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:w?"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(W=>W.category===m).length>1&&(()=>{const W=n.filter($=>$.category===m),T=new Map;for(const $ of W)for(const E of $.schema){if(E.type!=="boolean")continue;const V=T.get(E.key),q=!!($.values[E.key]??E.default);V?(V.onCount+=q?1:0,V.total+=1):T.set(E.key,{label:E.label||E.key,onCount:q?1:0,total:1})}const L=[...T.entries()].filter(([,$])=>$.total===W.length);if(L.length===0)return null;const z=async($,E)=>{for(const V of W)await b(V.type,$,E)};return s.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[s.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",W.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:L.map(([$,E])=>{const V=E.onCount===E.total,q=E.onCount===0;return s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:E.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",E.onCount,"/",E.total,")"]}),s.jsx("button",{onClick:()=>void 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:q,className:`machine-btn text-[9px] px-1.5 py-px ${q?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},$)})})]})})(),i&&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(W=>m==="all"||W.category===m).map(W=>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:W.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:W.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:W.category==="acp"?"rgba(139,92,246,0.08)":W.category==="cli"?"rgba(59,130,246,0.08)":W.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:W.category==="acp"?"#a78bfa":W.category==="cli"?"#60a5fa":W.category==="ide"?"#86efac":"var(--status-warning)"},children:W.category}),ci(W.category)&&(()=>{const T=t.find($=>$.type===W.type),L=(T==null?void 0:T.enabled)===!0||W.values.enabled===!0,z=(T==null?void 0:T.machineStatus)||(L?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${tb(z)}`,children:eb(z)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void B(W.type,!L),disabled:l===`${W.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${L?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:L?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void R(W.type),disabled:!L||l===`${W.type}.detect`,title:L?"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 ${L?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void P(W.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),W.category==="ide"&&s.jsx("button",{onClick:()=>f(t.find(T=>T.type===W.type)||{type:W.type,name:W.displayName,displayName:W.displayName,icon:W.icon,category:W.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),ci(W.category)&&(()=>{const T=t.find(L=>L.type===W.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:"})," ",li(T==null?void 0:T.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",li(T==null?void 0:T.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:W.schema.map(T=>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:[T.label||T.key,l===`${W.type}.${T.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),T.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:T.description})]}),s.jsx("div",{className:"shrink-0",children:T.type==="boolean"?s.jsx("button",{onClick:()=>b(W.type,T.key,!(W.values[T.key]??T.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:W.values[T.key]??T.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:W.values[T.key]??T.default?21:3}})}):T.type==="number"?s.jsx("input",{type:"number",value:Number(W.values[T.key]??T.default??0)||0,min:T.min,max:T.max,onChange:L=>{const z=parseInt(L.target.value)||0;T.min!==void 0&&z<T.min||T.max!==void 0&&z>T.max||b(W.type,T.key,z)},className:"machine-input w-20 text-center text-[11px]"}):T.type==="select"&&T.options?s.jsx("select",{value:String(W.values[T.key]??T.default??""),onChange:L=>b(W.type,T.key,L.target.value),className:"machine-input text-[11px]",children:T.options.map(L=>s.jsx("option",{value:L,children:L},L))}):s.jsx("input",{type:"text",value:String(W.values[T.key]??T.default??""),onBlur:L=>b(W.type,T.key,L.target.value),className:"machine-input w-[120px] text-[11px]"})})]},T.key))})]},W.type))}),h&&s.jsx(Qx,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>f(null)}),v&&s.jsx(Zx,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>S(!1),onCreated:()=>{S(!1),j()}})]})}const rb=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function nb({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function ab(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function ob(e){return e.trim().toLowerCase()}function dn(e,t){const r=ob(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Qa(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Ms(e,t=220){const r=Qa(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function ib(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 cb(e,t){return e.filter(r=>dn([r.level,r.message],t))}function di(e){return`${e.timestamp}:${e.level}:${e.message}`}function lb(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const c of e.entries)n.set(di(c),c);for(const c of t.entries)n.set(di(c),c);const a=Array.from(n.values()).sort((c,l)=>c.timestamp-l.timestamp).slice(-r),i=a.reduce((c,l)=>Math.max(c,Number(l.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:i}}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 db(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,i)=>a.ts-i.ts).slice(-r)}function ub(e,t){return e.split(`
63
- `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>dn([r],t))}function mb(e,t){return e.filter(r=>dn([r.level,r.category,r.stage,r.interactionId,Qa(r.payload)],t))}function fb(e,t){return e.filter(r=>dn([r.kind,r.topic,r.interactionId,Qa(r.payload)],t))}function ui(e){return e==="warn"||e==="error"}function pb({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=>ui(a.level)).length+r.filter(a=>ui(a.level)).length}}function hb({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(i=>`${new Date(i.timestamp).toISOString()} ${i.level.toUpperCase()} ${i.message}`)].join(`
64
- `)):t.length>0&&a.push(["[daemon logs]",...t].join(`
65
- `)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${Ms(i.payload,500)}`.trim())].join(`
66
- `)),n.length>0&&a.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${Ms(i.payload,500)}`.trim())].join(`
67
- `)),a.join(`
68
-
69
- `)}function xb({machineId:e,sendDaemonCommand:t}){const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[u,m]=o.useState([]),[d,h]=o.useState([]),[f,v]=o.useState(null),[S,p]=o.useState(!0),[x,y]=o.useState("info"),[g,N]=o.useState("all"),[M,w]=o.useState(!0),[I,k]=o.useState(!0),[j,b]=o.useState(""),[B,R]=o.useState(""),[P,F]=o.useState(0),U=o.useRef(0),W=o.useRef(0),T=o.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),L=o.useRef([]),z=o.useCallback(()=>{const pe={entries:[],kind:"empty",rawText:"",lastTs:0};T.current=pe,U.current=0,n([]),l(""),i("empty"),w(!0)},[]),$=o.useCallback(()=>{L.current=[],W.current=0,m([]),k(!0)},[]),E=o.useCallback(pe=>{pe!==x&&(z(),y(pe))},[x,z]),V=o.useCallback(pe=>{N(ie=>ie===pe?ie:pe)},[]),q=o.useCallback(()=>{z(),$(),h([]),v(null),b(""),R(""),js.clear()},[z,$]),ve=o.useCallback(()=>{F(pe=>pe+1)},[]),ne=o.useCallback(async()=>{if(!e)return;const pe=U.current,ie=W.current,[ge,be]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:x,since:pe}),t(e,"get_debug_trace",nb({count:120,since:ie,category:g}))]);if(ge.status==="fulfilled"){const H=ge.value,Q=(H==null?void 0:H.result)||H,re=ib(Q),he=lb(T.current,re,300);T.current=he,U.current=he.lastTs,w(!1),b((H==null?void 0:H.success)===!1?String((H==null?void 0:H.error)||"Could not load daemon logs"):""),i(he.kind),l(he.rawText),n(he.entries)}else w(!1),b(ge.reason instanceof Error?ge.reason.message:"Could not load daemon logs");if(be.status==="fulfilled"){const H=be.value,Q=(H==null?void 0:H.result)||H;if((H==null?void 0:H.success)===!1)R(String((H==null?void 0:H.error)||"Could not load daemon trace"));else if(Array.isArray(Q==null?void 0:Q.trace)){const re=Q.trace,he=db(L.current,re,120),ue=re.reduce((je,ce)=>Math.max(je,Number(ce.ts||0)),ie);L.current=he,ue>ie&&(W.current=ue),R(""),m(he)}else R("");k(!1)}else k(!1),R(be.reason instanceof Error?be.reason.message:"Could not load daemon trace");h(js.list({limit:120})),v(Date.now())},[x,e,t,g]);return o.useEffect(()=>{$()},[$,g]),o.useEffect(()=>{if(!e||(ne(),!S))return;const pe=setInterval(()=>{ne()},3e3);return()=>clearInterval(pe)},[S,ne,e,P]),{daemonLogs:r,daemonLogKind:a,daemonRawText:c,debugTrace:u,webEvents:d,lastUpdatedAt:f,autoRefresh:S,logLevel:x,traceCategory:g,daemonLoading:M,traceLoading:I,daemonFetchError:j,traceFetchError:B,setAutoRefresh:p,setLogLevel:E,setTraceCategory:V,refresh:ve,clear:q}}function bb({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:i,daemonRawLineCount:c,traceCount:l,webEventCount:u}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":i>0||c>0?"ok":"empty",detail:r||(a==="text"?`${c} raw file-fallback line(s)`:`${i} 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 mi(e){return e==="warn"||e==="error"}function gb(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 yb(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 fi(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function vb(e){const t=Ms(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function wb(e){const t=Ms(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function jb({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.forEach((i,c)=>{a.push({id:`daemon-log-${i.timestamp}-${c}`,source:"daemon_log",ts:Number(i.timestamp||0),severity:i.level,message:i.message,raw:i.message})}),n.forEach(i=>{a.push({id:`browser-event-${i.id}`,source:"browser_event",ts:Number(i.ts||0),severity:"info",message:wb(i),topic:i.topic,interactionId:i.interactionId,payload:i.payload})}),r.forEach(i=>{a.push({id:`daemon-trace-${i.id}`,source:"daemon_trace",ts:Number(i.ts||0),severity:i.level,message:vb(i),category:i.category,stage:i.stage,interactionId:i.interactionId,payload:i.payload})}),t.forEach((i,c)=>{a.push({id:`raw-file-${c}`,source:"raw_file",ts:yb(i,c),severity:gb(i),message:i,raw:i})}),a.sort((i,c)=>i.ts!==c.ts?i.ts-c.ts:fi(i.source)-fi(c.source))}function kb(e){return`${e.source}:${e.severity}:${e.message}`}function Sb(e){const t=e.filter(n=>mi(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!mi(n.severity))continue;const a=kb(n),i=r.get(a);i?(i.count+=1,i.firstTs=Math.min(i.firstTs,n.ts),i.lastTs=Math.max(i.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 Nb(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function pi(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${Nb(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function Cb({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
70
- `)),a.push(["[source status]",...r.map(c=>`${c.label}: ${c.status} - ${c.detail}`)].join(`
71
- `)),t.latestIssue&&a.push(["[latest issue]",pi(t.latestIssue)].join(`
72
- `)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(c=>`${c.count}x ${c.severity.toUpperCase()} ${c.source} ${c.message}`)].join(`
73
- `));const i=e.slice(-n);return a.push(["[timeline]",...i.length>0?i.map(pi):["No diagnostic events captured."]].join(`
74
- `)),a.join(`
75
-
76
- `)}function Tb(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Mb(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Ib({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:i,quickFilter:c,searchQuery:l,daemonLoading:u,traceLoading:m,daemonFetchError:d,traceFetchError:h}){const f=ab(n,i),v=cb(e,l),S=ub(t,l),p=mb(f,l),x=fb(a,l),y=Tb(v,c),g=c==="all"?S:[],N=Mb(p,c),M=c==="issues"?[]:x,w=pb({daemonLogs:v,daemonRawLines:S,trace:p,webEvents:x}),I=jb({daemonLogs:y,daemonRawLines:g,trace:N,webEvents:M}),k=Sb(I),j=bb({daemonLoading:u,traceLoading:m,daemonFetchError:d,traceFetchError:h,daemonLogKind:r,daemonLogsCount:v.length,daemonRawLineCount:S.length,traceCount:p.length,webEventCount:x.length});return{filteredDaemonLogs:v,filteredDaemonRawLines:S,filteredTraceEntries:p,filteredWebEvents:x,visibleDaemonLogs:y,visibleDaemonRawLines:g,visibleTraceEntries:N,visibleWebEvents:M,quickFilterCounts:w,diagnosticEvents:I,diagnosticsSummary:k,sourceStates:j}}function Ab(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function vl(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function fa(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 Bn(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 Za(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function Lb({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${fa(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:vl(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Za(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 Rb({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:i,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=>i(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 _b({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:rb.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 Pb({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:i,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":i?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Bn(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 ${Bn(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:[Za(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:vl(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 ${Bn(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":i?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",Ab(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 Db({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()," · ",Za(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function Eb({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:i,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(Lb,{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"?`${i.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&&i.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"&&i.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"&&i.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 ${fa(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 ${fa(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:Ms(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:Ms(d.payload,360)||"No payload"})]},d.id))]})]})]})}function $b({machineId:e,sendDaemonCommand:t}){const r=xb({machineId:e,sendDaemonCommand:t}),[n,a]=o.useState("info"),[i,c]=o.useState(""),[l,u]=o.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=o.useRef(null),d=o.useRef(!1),h=o.useMemo(()=>Ib({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:i,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,i,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);o.useEffect(()=>{if(r.autoRefresh&&h.diagnosticEvents.length>0){const S=d.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:S}),d.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const f=o.useCallback(async()=>{var p;const S=hb({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!S.trim()){it.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(S)),it.showToast("Copied visible logs to clipboard.","success")}catch(x){it.showToast(x instanceof Error?x.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),v=o.useCallback(async()=>{var p;const S=Cb({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(S)),it.showToast("Copied diagnostic bundle to clipboard.","success")}catch(x){it.showToast(x instanceof Error?x.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(Rb,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:i,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{v()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>r.setAutoRefresh(S=>!S),onRefresh:r.refresh,onClear:r.clear}),s.jsx(_b,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(Pb,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:i,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(Db,{patterns:h.diagnosticsSummary.repeatedPatterns}),s.jsx(Eb,{streams:r,sectionsOpen:l,setSectionsOpen:u,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:i}),s.jsx("div",{ref:m})]})}function Bb(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 wl(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 Kb(e){var a;const t=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=wl((i==null?void 0:i.meta)||void 0),u=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?t.push(i):(c==="stopped"||c==="failed")&&(u||l)?r.push(i):n.push(i)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function Ob(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Kn(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 On(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Wn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function hi(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 Wb(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Hb(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 Fb(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 i=`${n.providerType}::${n.workspace}::${a}`;t.set(i,(t.get(i)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function Ub({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),m=Sp(e,{enabled:!!e,includeSessions:!0,limit:To,intervalMs:Dm}),d=m.diagnostics,h=m.loading,f=m.applyDiagnostics,v=o.useMemo(()=>Bb({diagnostics:d,loading:h,refreshing:l,error:n}),[d,h,l,n]),S=o.useMemo(()=>new Map(t.map(R=>[R.sessionId||R.id,R])),[t]),p=o.useCallback(async()=>{if(e){u(!0);try{const R=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:To}),P=On(R);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Could not load hosted runtime diagnostics");f(P.diagnostics||P.result||null),a("")}catch(R){const P=R instanceof Error?R.message:"Could not load hosted runtime diagnostics";a(P)}finally{u(!1)}}},[f,e,r]);o.useEffect(()=>{!e||d||h||l||p()},[d,h,e,p,l]);const x=o.useCallback(async(R,P)=>{const F=`${R}:${P.sessionId}`;if(!(R==="session_host_stop_session"&&!window.confirm(`Stop ${P.displayName}?
77
- This will terminate the hosted runtime.`))){c(F);try{const U=await r(e,R,{sessionId:P.sessionId}),W=On(U);if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Session host action failed");const T=R==="session_host_resume_session"?"resumed":R==="session_host_restart_session"?"restarted":"stopped";it.showToast(`Session host ${T}: ${P.displayName}`,"success"),await p()}catch(U){const W=U instanceof Error?U.message:"Session host action failed";it.showToast(W,"warning"),a(W)}finally{c(U=>U===F?null:U)}}},[e,p,r]),y=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
78
- 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 P=await r(e,"session_host_prune_duplicate_sessions",{}),F=On(P);if(!(F!=null&&F.success))throw new Error((F==null?void 0:F.error)||"Duplicate prune failed");const U=F.result||{},W=Array.isArray(U.prunedSessionIds)?U.prunedSessionIds.length:0,T=typeof U.duplicateGroupCount=="number"?U.duplicateGroupCount:0;it.showToast(`Pruned ${W} duplicate runtime(s) across ${T} group(s)`,"success"),await p()}catch(P){const F=P instanceof Error?P.message:"Duplicate prune failed";it.showToast(F,"warning"),a(F)}finally{c(P=>P==="session_host_prune_duplicate_sessions"?null:P)}}},[e,p,r]),g=o.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((R,P)=>(P.lastActivityAt||0)-(R.lastActivityAt||0)),[d==null?void 0:d.sessions]),N=o.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)||[]}:Kb(g),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,g]),M=N.liveRuntimes,w=N.recoverySnapshots,I=N.inactiveRecords,k=o.useMemo(()=>Fb(M),[M]),j=o.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),b=o.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(R=>R.level==="warn"||R.level==="error")||null,[d==null?void 0:d.recentLogs]),B=(R,P)=>{var V;const F=i===`session_host_resume_session:${R.sessionId}`,U=i===`session_host_restart_session:${R.sessionId}`,W=i===`session_host_stop_session:${R.sessionId}`,T=wl(R.meta),L=S.get(R.sessionId),z=R.attachedClients.length===1?"1 client":`${R.attachedClients.length} clients`,$=P==="recovery"?"Recover":"Resume",E=Ob(P);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:R.displayName||(L==null?void 0:L.cliName)||R.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Hb(R.lifecycle)}`,children:R.lifecycle}),T&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:T})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:R.workspaceLabel||(L==null?void 0:L.runtimeWorkspaceLabel)||R.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:R.runtimeKey}),R.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",R.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((V=R.writeOwner)==null?void 0:V.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Wb(R.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(Ai,{size:11})," ",z]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",hi(R.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[P==="recovery"&&(R.lifecycle==="interrupted"||R.lifecycle==="failed"||R.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_resume_session",R)},children:F?`${$}ing…`:$}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_restart_session",R)},children:U?"Restarting…":"Restart"}),P==="live"&&(R.lifecycle==="running"||R.lifecycle==="starting"||R.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{x("session_host_stop_session",R)},children:W?"Stopping…":"Stop"})]})]})},R.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(is,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Af()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[k>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${k})`}),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(nr,{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(Zs,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:w.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:hi(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Wn(d.hostStartedAt)})]})]}),b&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(Zs,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:b.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Wn(b.timestamp),b.sessionId?` · ${b.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(wa,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Kn("live")}),M.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:M.map(R=>B(R,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(is,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Kn("recovery")}),w.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:w.map(R=>B(R,"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:Kn("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:I.map(R=>B(R,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),j.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:j.map(R=>{var F;const P=g.find(U=>U.sessionId===R.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(P==null?void 0:P.displayName)||((F=S.get(R.sessionId))==null?void 0:F.cliName)||R.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[R.action,R.lifecycle?` · ${R.lifecycle}`:"",R.detail?` · ${R.detail}`:"",R.error?` · ${R.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${R.success===!1?"text-red-300":"text-text-secondary"}`,children:Wn(R.timestamp)})]},`${R.sessionId}:${R.timestamp}:${R.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function zb({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(i=>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:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.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 Hn({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 Fn({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 Vb({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),d=qs(e,"0.9.43");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(Hn,{icon:s.jsx(Wt,{size:13}),children:"Current Chats"}),s.jsx(Fn,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const f=ra(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:ot(h)}),f>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Qr(f)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ls(h)})]},h.tabKey)})})})]}),u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Hn,{icon:s.jsx(Di,{size:13}),children:"Recent Launches"}),s.jsx(Fn,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:f,updatedLabel:v}=sl(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:()=>i(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(Hn,{icon:s.jsx(Zs,{size:13}),children:"Daemon Update"}),s.jsx(Fn,{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(nr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Gb(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function qb({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:i,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(i(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?"⭐ ":"",en(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 Yb={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 Nr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Un({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:m}){const d=Is(),{handleLaunchIde:h,handleStopCli:f,handleRestartIde:v,handleStopIde:S,handleDetectIdes:p,launchingIde:x,launchingAgentType:y,addLog:g}=c,[N,M]=o.useState(null),w=o.useCallback(K=>{K&&d(zt(K))},[d]),I=Yb[e],k=e==="ide",j=e==="acp",b=o.useMemo(()=>n.filter(K=>us(K,e)),[e,n]),B=o.useMemo(()=>new Map(b.map(K=>[K.type,K.displayName||K.type])),[b]),[R,P]=o.useState(""),[F,U]=o.useState(""),[W,T]=o.useState([]),[L,z]=o.useState(""),[$,E]=o.useState(""),[V,q]=o.useState([]),[ve,ne]=o.useState(!1),[pe,ie]=o.useState(!1),[ge,be]=o.useState(""),[H,Q]=o.useState(!1),[re,he]=o.useState(()=>pt()),[ue,je]=o.useState(null),[ce,xe]=o.useState(m?"__custom__":u||t.defaultWorkspaceId||""),[Z,ae]=o.useState(m||""),[te,Y]=o.useState([]),[X,le]=o.useState(!1),[D,oe]=o.useState(""),[J,we]=o.useState([]),[Ne,Ae]=o.useState(!1),[Me,Ue]=o.useState(""),We=o.useRef(null),[Be,Ye]=o.useState(null),Xe=o.useRef("__home__"),[Je,Ve]=o.useState("__home__"),[ht,ut]=o.useState(!1),ft=o.useRef(0),Ce=te.filter(K=>!a.some(se=>se.type===K&&bt(se.status)!=="stopped")),He=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!ce&&xe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(m){xe("__custom__"),ae(m);return}u&&(xe(u),ae(""))},[u,m]),o.useEffect(()=>{k||R&&(b.some(K=>K.type===R)||(P(""),E("")))},[b,k,R]);const Qe=(()=>{if(ce==="__custom__")return Z.trim();if(!ce)return"";const K=(t.workspaces||[]).find(se=>se.id===ce);return(K==null?void 0:K.path)||""})(),nt=o.useCallback(K=>{const se=He.current[K];se&&(clearTimeout(se),delete He.current[K]),Y(fe=>fe.includes(K)?fe.filter(Pe=>Pe!==K):fe)},[]),mt=o.useRef(new Set),A=o.useCallback(async K=>{if(l){Ae(!0),Ue("");try{const se=await an(l,r,K);oe(se.path),ae(se.path),we(se.directories)}catch(se){Ue(se instanceof Error?se.message:"Could not load folder")}finally{Ae(!1)}}},[r,l]),C=o.useCallback(()=>{if(!l)return;xe("__custom__"),le(!0);const K=a.map(fe=>fe.workspace),se=nn(t.platform,rn(Z.trim(),Qe,m,K,t.defaultWorkspacePath,(t.workspaces||[]).map(fe=>fe.path)));A(se)},[Z,m,A,t.defaultWorkspacePath,t.platform,t.workspaces,a,Qe,l]),_=o.useCallback(K=>{const se=String(K.workspace||"").trim();if(!se)return;const fe=(t.workspaces||[]).find(Pe=>Nr(Pe.path)===Nr(se));if(fe){xe(fe.id),ae("");return}xe("__custom__"),ae(se)},[t.workspaces]),O=o.useCallback(K=>{const se=String(K.workspace||"").trim();if(!se)return{workspaceId:null,workspacePath:"",useHome:!0};const fe=(t.workspaces||[]).find(Pe=>Nr(Pe.path)===Nr(se));return fe?{workspaceId:fe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:se,useHome:!1}},[t.workspaces]),G=o.useCallback(async K=>{if(!l||!K||e!=="cli"){q([]),ne(!1),ie(!1),be("");return}const se=ft.current+1;ft.current=se,ne(!0),be("");try{const fe=await l(r,"list_saved_sessions",{providerType:K,kind:"cli",limit:30});if(ft.current!==se)return;const Pe=(fe==null?void 0:fe.result)??fe;q(Array.isArray(Pe==null?void 0:Pe.sessions)?Pe.sessions:[])}catch(fe){if(ft.current!==se)return;q([]),be(fe instanceof Error?fe.message:"Could not load saved sessions")}finally{ft.current===se&&(ne(!1),ie(!0))}},[e,r,l]),ee=o.useMemo(()=>{if(e!=="cli"||!R)return null;const K=B.get(R)||R;return{routeId:r,daemonId:r,providerSessionId:$||void 0,transport:"pty",mode:"chat",agentName:K,agentType:R,status:"idle",title:K,messages:[],ideType:R,workspaceName:Qe,displayPrimary:K,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${R}`}},[e,r,B,Qe,$,R]),de=o.useCallback(K=>{if(e==="ide"||!K){T([]);return}T(xl(r,K))},[e,r]);o.useEffect(()=>{ft.current+=1,E(""),de(R),ie(!1),q([]),be(""),ne(!1)},[e,de,G,R]);const ye=o.useMemo(()=>V.find(K=>K.providerSessionId===$)||null,[V,$]);o.useEffect(()=>{if(!$)return;const K=V.find(se=>se.providerSessionId===$);K!=null&&K.canResume||E("")},[V,$]);const Se=o.useCallback((K,se)=>{We.current=se,Xe.current=K.selectedWorkspaceKey||"__home__",Ve(K.selectedWorkspaceKey||"__home__"),Ye(K)},[]),Re=o.useCallback(()=>{We.current&&(ut(!0),We.current().finally(()=>{We.current=null,ut(!1),Ye(null)}))},[]),ke=o.useCallback(K=>{if(!K)return;Y(fe=>fe.includes(K)?fe:[...fe,K]);const se=He.current[K];se&&clearTimeout(se),He.current[K]=setTimeout(()=>{Y(fe=>fe.includes(K)?fe.filter(Pe=>Pe!==K):fe),delete He.current[K]},2e4)},[]);o.useEffect(()=>{for(const se of a)bt(se.status)!=="stopped"&&(te.includes(se.type)&&!mt.current.has(se.type)&&(mt.current.add(se.type),g("info",`${B.get(se.type)||se.type} launched`,!0)),nt(se.type));const K=new Set(a.filter(se=>bt(se.status)!=="stopped").map(se=>se.type));mt.current.forEach(se=>{!te.includes(se)&&!K.has(se)&&mt.current.delete(se)})},[g,nt,a,te,B]),o.useEffect(()=>()=>{Object.values(He.current).forEach(clearTimeout),He.current={}},[]);const[Ee,Ke]=o.useState({}),[$e,Ie]=o.useState(null);o.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const se=await l(r,"get_ide_extensions",{}),fe=(se==null?void 0:se.result)||se;fe!=null&&fe.success&&(fe!=null&&fe.ideExtensions)&&Ke(fe.ideExtensions)}catch{}})()},[k,r,l]);const qe=K=>k?rt(K.type):e==="cli"?K.cliName:K.acpName,ct=k?t.detectedIdes||[]:[],me=o.useCallback(async K=>{const se=(K==null?void 0:K.type)||R,fe=(K==null?void 0:K.workspacePath)??Qe;if(k){await h(se,fe?{workspace:fe}:void 0)&&ke(se);return}const Pe=await c.runLaunchCliCore({cliType:se,dir:K!=null&&K.workspaceId?void 0:fe||void 0,workspaceId:(K==null?void 0:K.workspaceId)||void 0,useHome:(K==null?void 0:K.useHome)||!(K!=null&&K.workspaceId)&&!fe,argsStr:(K==null?void 0:K.argsStr)??(F||void 0),model:(K==null?void 0:K.model)??(j&&L||void 0),resumeSessionId:(K==null?void 0:K.resumeSessionId)||!j&&e==="cli"&&se===R&&$||void 0});if(Pe.success||Pe.pending){const Te=(K==null?void 0:K.argsStr)??F;!k&&(Te!=null&&Te.trim())&&(bl(r,se,Te),de(se)),ke(se),Pe.success&&Pe.sessionId&&w(Pe.sessionId)}},[c,h,j,k,F,L,de,ke,r,w,Qe,$,R]),Le=kc(k?"ide":j?"acp":"cli",!k&&!j&&!!$),et=Sc(k?"ide":j?"acp":"cli",!k&&!j&&!!$),at=()=>{var Te;const K=k?rt(R):B.get(R)||R,se=!k&&!j&&!!$,{options:fe,selectedKey:Pe}=ns({machine:t,currentWorkspaceId:ce&&ce!=="__custom__"?ce:null,currentWorkspacePath:Qe});Se({title:se?Ba(K):es("start-fresh",K),description:se?Ka():ts("start-fresh"),confirmLabel:Le,busyLabel:et,workspaceOptions:fe,selectedWorkspaceKey:Pe,details:[{label:"Mode",value:I.label},{label:"Provider",value:K},...!k&&e==="cli"&&$?[{label:"Resume",value:((Te=V.find(_e=>_e.providerSessionId===$))==null?void 0:Te.title)||$}]:[],...!k&&F.trim()?[{label:"Arguments",value:F.trim()}]:[],...j&&L.trim()?[{label:"Model",value:L.trim()}]:[]]},async()=>{const _e=fe.find(tt=>tt.key===Xe.current);_e!=null&&_e.workspaceId?(xe(_e.workspaceId),ae("")):_e!=null&&_e.workspacePath?(xe("__custom__"),ae(_e.workspacePath)):(xe(""),ae("")),await me({workspaceId:(_e==null?void 0:_e.workspaceId)??null,workspacePath:(_e==null?void 0:_e.workspacePath)??"",useHome:!(_e!=null&&_e.workspaceId)&&!(_e!=null&&_e.workspacePath)})})},Oe=K=>{k?S(K):f(K.type,K.workspace,K.id)},Mt=o.useCallback(async(K,se,fe=!1)=>{if(K.mode===se){fe&&K.sessionId&&w(K.sessionId);return}if(!l||!K.sessionId){fe&&K.sessionId&&w(K.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:K.sessionId,cliType:K.type,mode:se}),fe&&w(K.sessionId)}catch(Pe){const Te=Uc(Pe);Fc(Pe)?console.warn(Te?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Pe instanceof Error?Pe.message:String(Pe)):console.error("Failed to switch CLI view mode:",Pe)}},[r,w,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:k?ct.length>0?ct.map(K=>{const se=a.find(tt=>(tt.type||"").toLowerCase()===(K.type||"").toLowerCase()&&bt(tt.status)!=="stopped"),fe=K.running||!!se,Pe=!!se&&se.cdpConnected,Te=te.includes(K.type||K.id||""),_e=R===(K.type||"");return s.jsxs("button",{onClick:()=>{if(Pe&&se){const tt=se.sessionId;tt?d(zt(tt),{state:{openRemoteForTabKey:tt}}):d("/dashboard",{state:{openRemoteForTabKey:se.id}});return}Te||P(tt=>tt===(K.type||"")?"":K.type||"")},disabled:!!x||Te,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Pe?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":_e?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:x&&x!==K.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:i(K.type)}),fe&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Pe?"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:K.name||rt(K.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Pe?"text-green-400":Te?"text-orange-400":_e?"text-accent-primary":"text-text-muted"}`,children:Pe?"Open Session":Te?"Starting...":_e?"Configure":"Select"})]})]},K.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(Dd,{size:14})," Scan System"]})]}):b.length>0?b.map(K=>{const se=R===K.type,fe=te.includes(K.type),Te=!!a.find(_e=>_e.type===K.type&&bt(_e.status)!=="stopped");return s.jsxs("button",{onClick:()=>P(_e=>_e===K.type?"":K.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:K.icon}),Te&&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:K.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${fe?"text-orange-400":se?"text-accent-primary":"text-text-muted"}`,children:fe?"Starting...":se?"Configure":"Select"})]})]},K.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."})]})}),R&&(k?ct.find(K=>K.type===R):b.find(K=>K.type===R))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:k?rt(R):B.get(R)||R})]}),s.jsx(qb,{machine:t,selectedWorkspace:ce,resolvedWorkspacePath:Qe,customPath:Z,canBrowse:!!l,onWorkspaceChange:xe,onCustomPathChange:ae,onOpenBrowseDialog:C}),!k&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!j&&e==="cli"&&s.jsx(yl,{busy:!!y||!!x||te.includes(R),savedSessionsLoading:ve,savedSessionsError:ge,selectedSession:ye,onRefresh:()=>void G(R),onOpenHistory:()=>{R&&(Q(!0),gl({hasLoadedInitialResults:pe,isLoading:ve})&&G(R))},onClearSelection:()=>E("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[j&&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:L,onChange:K=>z(K.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:F,onChange:K=>U(K.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"}),W.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:W.map(K=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>U(K),title:K,children:K},K))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:at,disabled:!!y||!!x||te.includes(R),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:y===R||x===R?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+te.filter(K=>!a.some(se=>se.type===K&&bt(se.status)!=="stopped")).length,")"]}),a.length===0&&Ce.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:[Ce.map(K=>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:i(K)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?rt(K):B.get(K)||K}),s.jsx("div",{className:"text-[11px] text-text-muted",children:y===K?"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:${K}`)),a.map(K=>{const se=k?K:null,fe=!k&&!j?K:null,Pe=bt(K.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:i(K.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[qe(K),(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 gap-2",children:[s.jsx("span",{children:K.workspace||"—"}),(fe==null?void 0:fe.mode)&&s.jsx("span",{className:fe.mode==="chat"?"text-violet-400":"text-text-secondary",children:fe.mode==="chat"?"Chat view":"Terminal view"})]}),fe&&(fe.runtimeKey||fe.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[fe.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 ",fe.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 Te;(Te=navigator.clipboard)==null||Te.writeText(`adhdev attach ${fe.runtimeKey}`),M(fe.runtimeKey||null),window.setTimeout(()=>{M(_e=>_e===fe.runtimeKey?null:_e)},1200)},children:N===fe.runtimeKey?"Copied":"Copy"})]}),fe.runtimeWriteOwner&&s.jsx("span",{style:{color:fe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:fe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Gb(fe.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 ${Pe==="stopped"?"bg-red-500/[0.08] text-red-500":Pe==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Pe}),k&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Te=K.sessionId;if(Te){d(zt(Te),{state:{openRemoteForTabKey:Te}});return}d("/dashboard",{state:{openRemoteForTabKey:K.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(St,{size:13})}),s.jsx("button",{onClick:()=>{const Te=K.workspace||"",{options:_e,selectedKey:tt}=ns({machine:t,currentWorkspacePath:Te});Se({title:es("restart-ide",rt(K.type)),description:ts("restart-ide"),confirmLabel:Cs("restart-ide"),busyLabel:Ts("restart-ide"),workspaceOptions:_e,selectedWorkspaceKey:tt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:rt(K.type)}]},async()=>{const yt=_e.find(Ht=>Ht.key===Xe.current),dt=(yt==null?void 0:yt.workspacePath)??"";if(dt&&dt!==Te){await me({type:K.type,workspacePath:dt});return}await v(K)})},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(nr,{size:14})})]}),j&&s.jsx("button",{onClick:()=>{const Te=K.sessionId;Te&&w(Te)},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:!K.sessionId,children:s.jsx(Wt,{size:14})}),fe&&Pe!=="stopped"&&s.jsxs(s.Fragment,{children:[fe.mode&&s.jsx(Da,{mode:fe.mode,onChange:Te=>void Mt(fe,Te,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Te=K.sessionId;Te&&w(Te)},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:!K.sessionId,children:fe.mode==="chat"?s.jsx(Wt,{size:14}):s.jsx(St,{size:13})})]}),Pe==="stopped"?s.jsx("button",{onClick:()=>{const Te=K.workspace||"",_e=k?rt(K.type):qe(K),{options:tt,selectedKey:yt}=ns({machine:t,currentWorkspacePath:Te});Se({title:es("restart-stopped",_e),description:ts("restart-stopped"),confirmLabel:Cs("restart-stopped"),busyLabel:Ts("restart-stopped"),workspaceOptions:tt,selectedWorkspaceKey:yt,details:[{label:"Mode",value:I.label},{label:"Provider",value:_e}]},async()=>{const dt=tt.find(Ht=>Ht.key===Xe.current);await me({type:K.type,workspaceId:(dt==null?void 0:dt.workspaceId)??null,workspacePath:(dt==null?void 0:dt.workspacePath)??"",useHome:!(dt!=null&&dt.workspaceId)&&!(dt!=null&&dt.workspacePath)})})},disabled:te.includes(K.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:te.includes(K.type)?"⏳":s.jsx(ja,{size:14})}):s.jsx("button",{onClick:()=>Oe(K),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(vt,{size:14})})]})]}),se&&se.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:se.aiAgents.map(Te=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Vi(Te.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Te.name," · ",bt(Te.status)]},Te.id))}),se&&(Ee[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:(Ee[se.type]||[]).map(Te=>s.jsxs("button",{disabled:$e===`${se.type}.${Te.type}`,onClick:async()=>{const _e=`${se.type}.${Te.type}`;Ie(_e);try{await l(r,"set_ide_extension",{ideType:se.type,extensionType:Te.type,enabled:!Te.enabled}),Ke(tt=>({...tt,[se.type]:(tt[se.type]||[]).map(yt=>yt.type===Te.type?{...yt,enabled:!yt.enabled}:yt)}))}catch(tt){console.error("Extension toggle failed:",tt)}finally{Ie(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 ${Te.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 ${Te.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Te.name,s.jsx("span",{className:"text-[9px] font-normal",children:Te.enabled?"ON":"OFF"})]},Te.type))})]})]},K.id)})]}),X&&l&&s.jsx(cn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:D,directories:J,busy:Ne,error:Me,confirmLabel:"Use this folder",onClose:()=>le(!1),onNavigate:K=>{A(K)},onConfirm:K=>{ae(K),xe("__custom__"),le(!1)}}),Be&&s.jsx(Xa,{title:Be.title,description:Be.description,details:Be.details,workspaceOptions:Be.workspaceOptions,selectedWorkspaceKey:Je,onWorkspaceChange:K=>{Xe.current=K,Ve(K)},confirmLabel:Be.confirmLabel,busyLabel:Be.busyLabel,busy:ht,onConfirm:Re,onCancel:()=>{We.current=null,Ye(null)}}),H&&ee&&s.jsx(Oa,{activeConv:ee,ides:[],isCreatingChat:!1,isRefreshingHistory:ve,savedSessions:V,isSavedSessionsLoading:ve,isResumingSavedSessionId:ue,savedHistoryFilters:re,onSavedHistoryFiltersChange:he,onClose:()=>Q(!1),onNewChat:()=>{E(""),Q(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{G(R)},onResumeSavedSession:K=>{if(!K.canResume||ue)return;const se=O(K);E(K.providerSessionId),_(K),je(K.providerSessionId),Q(!1),me({type:K.providerType,workspaceId:se.workspaceId,workspacePath:se.workspacePath,useHome:se.useHome,resumeSessionId:K.providerSessionId}).finally(()=>{je(fe=>fe===K.providerSessionId?null:fe)})}})]})}const xi=[{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 Xb({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:m,initialWorkspacePath:d,sendDaemonCommand:h}){var p;const[f,v]=o.useState(u);o.useEffect(()=>{v(u)},[u]);const S=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.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:xi.map(x=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${f===x.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>v(x.id),children:[s.jsx("span",{children:x.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${f===x.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:S[x.id]})]},x.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(p=xi.find(x=>x.id===f))==null?void 0:p.helper})]}),f==="ide"&&s.jsx(Un,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d}),f==="cli"&&s.jsx(Un,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d}),f==="acp"&&s.jsx(Un,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d})]})}function Jb({onNicknameSynced:e}={}){var je,ce,xe,Z,ae,te,Y,X,le;const{id:t}=ad(),r=Is(),n=ba(),{sendCommand:a}=wt(),i=ir(),c=Kc(),l=hc(),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,v]=o.useState("workspace"),[S,p]=o.useState("ide"),x=o.useRef(null),[y,g]=o.useState(null),N=o.useRef("__home__"),[M,w]=o.useState("__home__"),[I,k]=o.useState(!1),j=o.useRef(null);o.useEffect(()=>{!t||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||i(t,{minFreshMs:3e4}).catch(()=>{})},[i,d,t]),o.useEffect(()=>{if(!t||!d||f!=="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(()=>{})},[f,c,d,t]),kp(t&&f==="overview"?[t]:[],{enabled:f==="overview",intervalMs:Lm});const b=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},B=Vx({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:j});o.useEffect(()=>it.onToast(oe=>{l.setToasts(we=>{if(we.some(Me=>Me.message===oe.message&&oe.timestamp-Me.timestamp<3e3))return we;const Ae={id:oe.id,message:oe.message,type:oe.type,timestamp:oe.timestamp,targetKey:oe.targetKey,actions:oe.actions};return[...we.slice(-4),Ae]});const J=oe.duration||5e3;setTimeout(()=>l.setToasts(we=>we.filter(Ne=>Ne.id!==oe.id)),J)}),[l]);const R=(d==null?void 0:d.availableProviders)||[],P={};for(const D of R)P[D.type]=D.icon;const F=D=>P[D]||"",U=d?{id:d.id,hostname:Gi(d,{fallbackId:d.id}),platform:((je=d.machine)==null?void 0:je.platform)||"unknown",arch:((ce=d.machine)==null?void 0:ce.arch)||"",cpus:((xe=d.machine)==null?void 0:xe.cpus)||0,totalMem:((Z=d.machine)==null?void 0:Z.totalMem)||0,freeMem:(ae=d.machine)==null?void 0:ae.freeMem,availableMem:(te=d.machine)==null?void 0:te.availableMem,loadavg:(Y=d.machine)==null?void 0:Y.loadavg,uptime:(X=d.machine)==null?void 0:X.uptime,release:((le=d.machine)==null?void 0:le.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,W=u.filter(D=>D.daemonId===t&&D.type!=="adhdev-daemon").filter(D=>!tr(D)&&!gs(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:Du(D.aiAgents||(D.agents||[]).map(oe=>({id:oe.name,name:oe.name,status:oe.status,version:oe.version}))),activeChat:D.activeChat||null,chats:D.chats||[],childSessions:D.childSessions||[],cdpConnected:D.cdpConnected||!1,daemonId:t})),T=u.filter(D=>D.daemonId===t&&tr(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})),L=u.filter(D=>D.daemonId===t&&gs(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})),z=d?Tt(d,{fallbackId:t}):"",$="workspace",E=n.state,V=E==null?void 0:E.initialMachineTab,q=E==null?void 0:E.initialWorkspaceCategory,ve=E==null?void 0:E.initialWorkspaceId,ne=E==null?void 0:E.initialWorkspacePath,pe=V==="ides"||V==="clis"||V==="acps"?"workspace":V||$,ie=V==="ides"?"ide":V==="clis"?"cli":V==="acps"?"acp":q,ge=[...W.map(D=>{var oe,J,we,Ne,Ae;return{id:`ide:${D.type}:${D.workspace||""}`,label:((oe=D.activeChat)==null?void 0:oe.title)||D.type,kind:"ide",providerType:D.type,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Ae=(Ne=(we=(J=D.activeChat)==null?void 0:J.messages)==null?void 0:we.at)==null?void 0:Ne.call(we,-1))==null?void 0:Ae.timestamp)||0}}),...T.map(D=>{var oe,J,we,Ne,Ae;return{id:`cli:${D.type}:${D.workspace||""}`,label:((oe=D.activeChat)==null?void 0:oe.title)||D.cliName,kind:"cli",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Ae=(Ne=(we=(J=D.activeChat)==null?void 0:J.messages)==null?void 0:we.at)==null?void 0:Ne.call(we,-1))==null?void 0:Ae.timestamp)||0}}),...L.map(D=>{var oe,J,we,Ne,Ae;return{id:`acp:${D.type}:${D.workspace||""}`,label:((oe=D.activeChat)==null?void 0:oe.title)||D.acpName,kind:"acp",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:cs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Ae=(Ne=(we=(J=D.activeChat)==null?void 0:J.messages)==null?void 0:we.at)==null?void 0:Ne.call(we,-1))==null?void 0:Ae.timestamp)||0}})].sort((D,oe)=>(oe.lastLaunchedAt||0)-(D.lastLaunchedAt||0)),be=((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:cs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace,summaryMetadata:D.summaryMetadata,lastLaunchedAt:D.lastLaunchedAt})):ge,H=o.useMemo(()=>{var oe;const D=((oe=l.connectionStates)==null?void 0:oe[t||""])||void 0;return u.filter(J=>J.daemonId===t&&J.type!=="adhdev-daemon").flatMap(J=>Wa(J,{connectionStates:t&&D?{[t]:D}:void 0,defaultConnectionState:D})).filter(J=>!(J.transport==="pty"&&J.mode==="terminal")).sort((J,we)=>ra(we)-ra(J))},[u,l.connectionStates,t]),Q=o.useCallback(D=>{const oe=La(D);oe&&r(zt(oe))},[r]),re=o.useCallback(()=>{x.current&&(k(!0),x.current().finally(()=>{x.current=null,k(!1),g(null)}))},[]),he=o.useCallback(D=>{if(!U)return;const{options:oe,selectedKey:J}=ns({machine:U,currentWorkspacePath:D.workspace}),we=async()=>{p(D.kind),v("workspace")};x.current=async()=>{const Ne=oe.find(Ue=>Ue.key===N.current),Ae=(Ne==null?void 0:Ne.workspacePath)??null,Me=(Ne==null?void 0:Ne.workspaceId)??null;if(D.kind==="ide"&&D.providerType){await B.handleLaunchIde(D.providerType,Ae?{workspace:Ae}:void 0);return}if((D.kind==="cli"||D.kind==="acp")&&D.providerType){await B.runLaunchCliCore({cliType:D.providerType,dir:Me?void 0:Ae||"",workspaceId:Me||void 0,model:D.kind==="acp"&&Yi(D.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:D.providerSessionId});return}await we()},N.current=J,w(J),g({title:D.kind==="ide"?es("restart-ide",D.label):D.providerSessionId?Ba(D.label):es("start-fresh",D.label),description:D.kind==="ide"?ts("restart-ide"):D.providerSessionId?Ka():ts("start-fresh"),confirmLabel:D.kind==="ide"?Cs("restart-ide"):D.providerSessionId?zr(!0):Cs("start-fresh"),busyLabel:D.kind==="ide"?Ts("restart-ide"):D.providerSessionId?Ea(!0):Ts("start-fresh"),workspaceOptions:oe,details:[{label:"Mode",value:D.kind.toUpperCase()},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]})},[B,U]);if(o.useEffect(()=>{v(pe)},[$,pe,t]),o.useEffect(()=>{ie&&p(ie)},[ie,t]),!U)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:b,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 ue=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(St,{size:14})," Workspace"]}),count:W.length+T.length+L.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(is,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xr,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ed,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_d,{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:b,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:[B.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:B.nicknameInput,onChange:D=>B.setNicknameInput(D.target.value),onKeyDown:D=>{D.key==="Enter"&&B.handleSaveNickname(),D.key==="Escape"&&B.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:B.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:()=>B.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:()=>{B.setEditingNickname(!0),B.setNicknameInput(U.machineNickname||"")},title:"Click to set nickname",children:z}),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:[U.platform," · ",U.arch]}),s.jsxs("span",{children:[U.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),U.p2p.available&&s.jsxs("span",{children:["P2P ",U.p2p.state==="connected"?"connected":U.p2p.state]}),U.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:U.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ue.map(D=>s.jsxs("button",{onClick:()=>v(D.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===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 ${f===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:[f==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(Vb,{machineEntry:d,providers:R,recentLaunches:be,currentConversations:H,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:he,onOpenConversation:Q}),s.jsx(Xb,{machine:U,machineId:t,providers:R,ideSessions:W,cliSessions:T,acpSessions:L,actions:B,getIcon:F,initialCategory:S,initialWorkspaceId:ve,initialWorkspacePath:ne,sendDaemonCommand:a})]}),f==="providers"&&s.jsx(sb,{machineId:t,providers:R,sendDaemonCommand:a}),f==="overview"&&s.jsx(Gx,{machineId:t,machine:U,ideSessions:W,cliSessions:T,acpSessions:L,actions:B,sendDaemonCommand:a}),f==="session-host"&&s.jsx(Ub,{machineId:t,cliSessions:T,sendDaemonCommand:a}),f==="logs"&&s.jsx($b,{machineId:t,sendDaemonCommand:a})]})})}),B.launchPick&&U&&s.jsx(zb,{machine:U,launchPick:B.launchPick,actions:B}),y&&s.jsx(Xa,{title:y.title,description:y.description,details:y.details,workspaceOptions:y.workspaceOptions,selectedWorkspaceKey:M,onWorkspaceChange:D=>{N.current=D,w(D)},confirmLabel:y.confirmLabel,busyLabel:y.busyLabel,busy:I,onConfirm:re,onCancel:()=>{x.current=null,g(null)}}),s.jsx(Nc,{toasts:l.toasts||[],onDismiss:D=>l.setToasts(oe=>oe.filter(J=>J.id!==D)),onClickToast:D=>{D.targetKey&&r(zt(D.targetKey))}}),s.jsx("style",{children:`
79
- @keyframes toast-in {
80
- from { opacity: 0; transform: translateX(40px); }
81
- to { opacity: 1; transform: translateX(0); }
82
- }
83
- `})]})}function eo(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Qb(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=eo();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(Qb(e),{credentials:"same-origin",...t})}function jl(){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 Zb{constructor(){ze(this,"adapters",new Map);ze(this,"states",new Map);ze(this,"runtimeListeners",new Map);ze(this,"screenshotCallbacks",new Map);ze(this,"statusCallbacks",new Set)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r)}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,i,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:i,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 i=await Pt(`${a.pathname}${a.search}`);if(!i.ok){let l=`Runtime snapshot unavailable (${i.status})`;try{const u=await i.json();u!=null&&u.error&&(l=u.error)}catch{}return{success:!1,error:l}}const c=await i.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 Bt=new Zb;function eg(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=eo();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Cr=eg(),bi=3e3,tg=3e4;let Lt=null,sg=0;const Yr=new Map;let Yt=null,Xs=null;function gi(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Ws(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function rg(e){return e==="connected"?"connected":e}async function Dr(e,t,r){const n=Mc(e,r||{}),a=Lt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++sg}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{Yr.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);Yr.set(i,{resolve:m=>{clearTimeout(u),c(m)},reject:m=>{clearTimeout(u),l(m)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function pa(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 ng(e,t,r){const n=Lt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Mc(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 ag{constructor(t){ze(this,"daemonId");ze(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 Dr(this.daemonId,t,r)}async sendInput(t,r){return Dr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Yt&&(clearInterval(Yt),Yt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Dr(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(i=>i.blob());Bt.emitScreenshot(this.daemonId,a)}}catch{}};r(),Yt=setInterval(r,2e3)}stopScreenshots(t){Yt&&(clearInterval(Yt),Yt=null)}}let Ct=null;function og(e){return(!Ct||Ct.daemonId!==e)&&(Ct=new ag(e)),Ct}function ig({children:e}){const t=o.useRef(Qs()),r=Qs();t.current=r;const{setUserName:n}=os(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((p,x)=>{l(p),Xs==null||Xs(p,x)},[]),m=o.useRef(null),d=o.useRef(),h=o.useRef(bi),f=o.useRef(!0),v=o.useRef(!1),S=o.useRef("initial_connect");return o.useEffect(()=>{f.current=!0,v.current=!1;function p(){var g,N;if(!f.current||((g=m.current)==null?void 0:g.readyState)===WebSocket.OPEN||((N=m.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Cr}...`),Ws("connect_attempt",{url:Cr,reason:S.current,delayMs:h.current});let y;try{y=new WebSocket(Cr)}catch(M){console.error("[Standalone WS] Failed to create WebSocket:",M),x();return}m.current=y,y.onopen=()=>{if(!f.current){y.close();return}u("connected"),h.current=bi,Ws("open",{url:Cr,reason:S.current}),Vt.resubscribeAll({sendData:pa}),console.log("[Standalone WS] Connected")},Lt=y,y.onmessage=M=>{var w,I;try{const k=JSON.parse(M.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const j=Yr.get(k.requestId);j&&(Yr.delete(k.requestId),k.type==="error"?j.reject(new Error(((w=k.data)==null?void 0:w.message)||"Command failed")):j.resolve(k.data));return}if(k.type==="session_output"){const j=k.sessionId||k.cliId||k.cliType;j&&Bt.emitSessionOutput(j,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){Bt.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated,typeof k.cols=="number"?k.cols:void 0,typeof k.rows=="number"?k.rows:void 0);return}if(k.type==="topic_update"){const j=k.update;j&&Vt.publish(j);return}if(k.type==="status"||k.type==="initial_state"){const j=k.data;if(!j)return;const{injectEntries:b,markLoaded:B,getIdes:R}=t.current,P=j.instanceId||"standalone",F=R().find(T=>T.id===P),U=og(P);Bt.register(P,U),Bt.setState(P,"connected"),u("connected",P),Bt.emitStatus(P,j);const W=Fr(j,{daemonId:P,existingDaemon:F,existingEntries:R()});gi("ws_status",{type:k.type,daemonId:P,sessions:(j.sessions||[]).map(T=>({id:T.id,parentId:T.parentId,providerType:T.providerType,kind:T.kind,transport:T.transport,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,title:T.title})),recentLaunches:(j.recentLaunches||[]).map(T=>({id:T.id,providerType:T.providerType,kind:T.kind,workspace:T.workspace,lastLaunchedAt:T.lastLaunchedAt}))}),gi("entries",{daemonId:P,entries:W.filter(T=>T.type!=="adhdev-daemon").map(T=>({id:T.id,type:T.type,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,sessionId:T.sessionId}))}),W.length>0&&b(W,{authoritativeDaemonIds:[P]}),B(),c.current!==P&&((I=i.current)==null||I.call(i),c.current=P,i.current=Vt.subscribe({sendData:pa},P,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${P}`,params:{includeSessions:!0}},T=>{if(T.topic!=="daemon.metadata")return;const L=t.current.getIdes(),z=L.find(E=>E.id===P),$=Fr(T.status,{daemonId:P,existingDaemon:z,existingEntries:L,timestamp:T.timestamp});$.length>0&&t.current.injectEntries($,{authoritativeDaemonIds:[P]}),T.userName&&a.current&&a.current(T.userName)}))}}catch(k){console.error("[Standalone WS] Parse error:",k)}},y.onclose=M=>{f.current&&(Ct==null||Ct.stopScreenshots(),Ct&&Bt.setState(Ct.daemonId,"disconnected"),u("disconnected"),m.current=null,S.current=`close:${M.code}${M.wasClean?":clean":":unclean"}`,Ws("close",{code:M.code,reason:M.reason||"",wasClean:M.wasClean}),x())},y.onerror=M=>{v.current||!f.current||(S.current="error",Ws("error",{message:M instanceof Event?"event":String(M),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",M))}}function x(){if(!f.current)return;clearTimeout(d.current);const y=h.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),Ws("schedule_reconnect",{reason:S.current,delayMs:y}),d.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,tg),p()},y)}return p(),()=>{var y;f.current=!1,v.current=!0,(y=i.current)==null||y.call(i),i.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),Ct&&(Ct.stopScreenshots(),Bt.unregister(Ct.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function cg({children:e}){const[t,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Xs=(c,l)=>{r(c),l&&a(l)},()=>{Xs=null}),[]);const i=o.useMemo(()=>{const c=t==="connected",l=rg(t),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:t,isConnected:c,connectionStates:u}},[t,n]);return s.jsx(kd,{connectionOverrides:i,children:s.jsx(ig,{children:e})})}const kl="adhdev_standalone_font_preferences",as={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},un=[{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"}],rr=[{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"}],lg=new Set(un.map(e=>e.id)),dg=new Set(rr.map(e=>e.id));function Et(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Er("chat",t.chat),code:Er("code",t.code),terminal:Er("terminal",t.terminal)}}function Er(e,t){const r=as[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?lg:dg).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function $r(e,t){var a;const r=Er(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?un:rr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function ug(e){const t=Et(e),r=$r("chat",t.chat),n=$r("code",t.code),a=$r("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Jt(e,t=document.documentElement){const r=Et(e),n=ug(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function ha(e){const t=Et(e);try{localStorage.setItem(kl,JSON.stringify(t))}catch{}return t}function mg(){try{const e=localStorage.getItem(kl);if(e)return Et(JSON.parse(e))}catch{}return as}function fg(){return Jt(mg())}function Hs(e,t){var n;const r=e==="chat"?un:rr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const pg=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Ii,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(is,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(Xr,{}),label:"Settings"}];function hg({children:e}){const t=Is(),r=ba(),n=o.useMemo(()=>pg.map(i=>({...i,active:r.pathname.startsWith(i.path),onSelect:()=>t(i.path)})),[r.pathname,t]),a=o.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(Li,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Ri,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Yf,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.43"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:i?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const xg=[{icon:s.jsx(is,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Wt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(_i,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(St,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(er,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Li,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],bg=[{icon:s.jsx(Bd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Ii,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Jr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Rd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Ai,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Pd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],gg=[{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 yg(){return s.jsxs(Rc,{icon:s.jsx(Ri,{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.43"]}),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:xg.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:Ic.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Lc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Ac.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:bg.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:gg.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(Pc,{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(qd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function zn(e,t,r){return{...e,[t]:r}}function Vn({surface:e,title:t,description:r,value:n,options:a,onChange:i}){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;i(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=>i({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:$r(e,n)})]})]})]})}function vg({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:i,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(Vn,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:un,onChange:d=>i(zn(e,"chat",d))}),s.jsx(Vn,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:rr,onChange:d=>i(zn(e,"code",d))}),s.jsx(Vn,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:rr,onChange:d=>i(zn(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: ",Hs("chat",e.chat.preset)," · Code: ",Hs("code",e.code.preset)," · Terminal: ",Hs("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Hs("chat",as.chat.preset)," / ",Hs("code",as.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 wg(){const{ides:e}=os(),t=e.find(H=>H.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=wt(),{userName:a}=os(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[m,d]=o.useState(null),[h,f]=o.useState(as),[v,S]=o.useState(!1),[p,x]=o.useState(""),[y,g]=o.useState(""),[N,M]=o.useState("127.0.0.1"),[w,I]=o.useState(""),[k,j]=o.useState(""),[b,B]=o.useState(""),[R,P]=o.useState(""),[F,U]=o.useState(""),[W,T]=o.useState(!1),L=async()=>{const Q=await(await Pt("/auth/session")).json();u(Q)},z=async()=>{const Q=await(await Pt("/api/v1/standalone/preferences")).json();d(Q),M(Q.standaloneBindHost);const re=Et(Q.standaloneFontPreferences);f(re),Jt(re),ha(re)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([L(),z()]).catch(H=>{P(H instanceof Error?H.message:String(H))})},[]),o.useEffect(()=>{Jt(h)},[h]);const $=H=>{const Q=H.target.value.trim();t!=null&&t.id&&Q!==a&&n(t.id,"set_user_name",{userName:Q}).catch(console.error)},[E,V]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),q=H=>{V(H);try{localStorage.setItem("adhdev_sound",H?"1":"0")}catch{}},ve=async()=>{x(""),g(""),S(!0);try{const H=Et(h),Q=await Pt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:H})}),re=await Q.json();if(!Q.ok)throw new Error((re==null?void 0:re.error)||"Failed to save standalone font preferences");const he=Et(re.standaloneFontPreferences);d(re),f(he),Jt(he),ha(he),g("Standalone chat fonts saved for this self-hosted dashboard.")}catch(H){x(H instanceof Error?H.message:String(H))}finally{S(!1)}},ne=()=>{const H=Et(m==null?void 0:m.standaloneFontPreferences);x(""),g(""),f(H),Jt(H)},pe=()=>{x(""),g(""),f(as),Jt(as)},ie=async()=>{P(""),U(""),T(!0);try{const H=await Pt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),Q=await H.json();if(!H.ok)throw new Error((Q==null?void 0:Q.error)||"Failed to save standalone network preference");d(Q),M(Q.standaloneBindHost),U(Q.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(H){P(H instanceof Error?H.message:String(H))}finally{T(!1)}},ge=async()=>{if(P(""),U(""),k.trim().length<4){P("Password must be at least 4 characters.");return}if(k!==b){P("New password and confirmation do not match.");return}T(!0);try{const H=await Pt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,newPassword:k})}),Q=await H.json();if(!H.ok)throw new Error((Q==null?void 0:Q.error)||"Failed to save password");u(Q),await z(),I(""),j(""),B(""),U(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),jl()}catch(H){P(H instanceof Error?H.message:String(H))}finally{T(!1)}},be=async()=>{P(""),U(""),T(!0);try{const H=await Pt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,clear:!0})}),Q=await H.json();if(!H.ok)throw new Error((Q==null?void 0:Q.error)||"Failed to clear password");u(Q),await z(),I(""),j(""),B(""),U("Standalone password disabled.")}catch(H){P(H instanceof Error?H.message:String(H))}finally{T(!1)}};return s.jsxs(Rc,{icon:s.jsx(Xr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(gr,{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(gr,{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.43"]}),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:N==="127.0.0.1",onChange:()=>M("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:N==="0.0.0.0",onChange:()=>M("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:()=>{ie()},disabled:W,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:W?"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."}),R&&s.jsx(gr,{variant:"error",children:R}),F&&s.jsx(gr,{variant:"success",children:F}),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:w,onChange:H=>I(H.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:k,onChange:H=>j(H.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:b,onChange:H=>B(H.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{ge()},disabled:W,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:W?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{be()},disabled:W,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(H=>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 ${H.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:H.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:H.type})]},H.type))})}),s.jsx(kt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(np,{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(cp,{})]}),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(xp,{})]}),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(vg,{value:h,savedValue:Et(m==null?void 0:m.standaloneFontPreferences),saving:v,error:p,notice:y,onChange:f,onSave:()=>{ve()},onResetToSaved:ne,onResetToDefaults:pe})]}),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(yp,{})]})]})}),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(tp,{}),s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Gd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:q})]})}),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(Ld,{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:i,onChange:H=>c(H.target.value),onBlur:$,onKeyDown:H=>{H.key==="Enter"&&H.currentTarget.blur()}})]})})})]})}Gf();pp();fg();const jg=Ci({baseUrl:"",getToken:eo});function kg({children:e}){const[t,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[m,d]=o.useState(!1),h=async()=>{a(!0),u("");try{const S=await(await Pt("/auth/session")).json();r(S)}catch(v){u(v instanceof Error?v.message:String(v))}finally{a(!1)}};o.useEffect(()=>{h()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let v=!1;return(async()=>{try{const S=await Pt("/api/v1/standalone/preferences");if(!S.ok)return;const p=await S.json();if(v)return;const x=Et(p.standaloneFontPreferences);Jt(x),ha(x)}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 S=await Pt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),p=await S.json();if(!S.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),jl()}catch(S){u(S instanceof Error?S.message:String(S))}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:i,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||!i,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 yi(){const{ides:e,initialLoaded:t}=os();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(Yn,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Yn,{to:"/dashboard",replace:!0})}function Sg(){const e=o.useMemo(()=>({sendCommand:Dr,sendData:pa,sendPtyInput:ng}),[]);return s.jsx(od,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Cd,{client:jg,children:s.jsx(kg,{children:s.jsx(cg,{children:s.jsx(Md,{value:e,children:s.jsx(hg,{children:s.jsxs(id,{children:[s.jsx(Gt,{path:"/dashboard",element:s.jsx(zx,{})}),s.jsx(Gt,{path:"/machine",element:s.jsx(yi,{})}),s.jsx(Gt,{path:"/machines/:id",element:s.jsx(Jb,{})}),s.jsx(Gt,{path:"/machines",element:s.jsx(yi,{})}),s.jsx(Gt,{path:"/about",element:s.jsx(yg,{})}),s.jsx(Gt,{path:"/settings",element:s.jsx(wg,{})}),s.jsx(Gt,{path:"*",element:s.jsx(Yn,{to:"/dashboard",replace:!0})})]})})})})})})})}mf({connectionManager:Bt});cd(document.getElementById("root")).render(s.jsx(Sg,{}));