@adhdev/daemon-standalone 0.9.74 → 0.9.76-rc.1
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.
- package/dist/index.js +57 -19
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
- package/public/assets/index-B7upbbbO.js +94 -0
- package/public/assets/index-DHNzD5nE.css +1 -0
- package/public/index.html +2 -2
- package/vendor/mcp-server/index.js +92 -28
- package/vendor/mcp-server/index.js.map +1 -1
- package/vendor/mcp-server/package.json +1 -1
- package/vendor/session-host-daemon/index.js +0 -0
- package/vendor/session-host-daemon/index.mjs +0 -0
- package/public/assets/index-Bu3OpXMi.js +0 -94
- package/public/assets/index-CVquu5qt.css +0 -1
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-BeBmUW3m.js","assets/vendor-CLec0455.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
var pd=Object.defineProperty;var hd=(e,t,r)=>t in e?pd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Je=(e,t,r)=>hd(e,typeof t!="symbol"?t+"":t,r);import{r as o,j as s,M as Ra,a as xd,b as bd,c as gd,R as Nt,d as rr,t as yd,e as vd,u as Ds,D as wd,f as ca,g as la,h as La,i as jd,k as kd,B as Sd,l as Nd,m as Gt,N as da,n as Cd}from"./vendor-CLec0455.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 Td(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 Cs=Td();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 Md(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Ad(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Bi(e,t){if(!e)return t??null;if(!t)return e??null;const r=Ad(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:t.messages,a={...t,...e,activeModal:e.activeModal??null,inputContent:e.inputContent??t.inputContent};return r?{...a,messages:n}:a}function qs(e,t){const r=Md(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(t==null?void 0:t.parentSessionId)??null,providerSessionId:e.providerSessionId??(t==null?void 0:t.providerSessionId),providerName:r??(t==null?void 0:t.providerName)??(t==null?void 0:t.cliName)??(t==null?void 0:t.type)??e.providerName??e.providerType,title:e.title??(t==null?void 0:t.title)??r??(t==null?void 0:t.providerName)??e.providerName??e.providerType,workspace:e.workspace??(t==null?void 0:t.workspace)??null,mode:e.mode??(t==null?void 0:t.mode),capabilities:e.capabilities??(t==null?void 0:t.sessionCapabilities)??(t==null?void 0:t.capabilities)??[],cdpConnected:e.cdpConnected??(t==null?void 0:t.cdpConnected),activeChat:Bi(e.activeChat,t==null?void 0:t.activeChat),controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel),settings:e.settings??(t==null?void 0:t.settings)}}function Ki(e,t,r){if(!(t!=null&&t.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const n=t.map(a=>{const i=e.find(c=>c.id===a.id);return i?qs(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 To(e){return!!e&&typeof e=="object"&&"text"in e}function _a(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:To(i)?String(i.text||""):"").join(r):To(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Ts(e){return _a(e,{normalizeWhitespace:!0})}const Wi=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,connectionRetryStatuses:void 0}),Oi=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Mo(e){var r,n;let t=0;return e.activeChat!==void 0&&(t+=4),(r=e.childSessions)!=null&&r.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(n=e.agents)!=null&&n.length&&(t+=1),t}function Fi(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,i=t.serverVersion??e.serverVersion??r.serverVersion,c=t.versionMismatch===!0||e.versionMismatch===!0,l=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),i&&(n.serverVersion=i),d&&(n.versionUpdateReason=d),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 Id(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 jn(e){if(!e||typeof e!="object")return"";const t=e,r=Id(Ts(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 Rd(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=jn(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:jn(e[0]),last:jn(e[e.length-1])}}function ua(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function ma(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(ua(e)&&ua(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)ma(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"&&ma(n[c],a[c],r)}function Xs(e,t){return Array.isArray(e)?e.map(r=>Xs(r,t)):!e||typeof e!="object"?e:ua(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Rd(a,t):Xs(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Xs(n,t)]))}function Ld(e,t){try{const r=new WeakSet;return ma(e,t,r),JSON.stringify(Xs(e,r))===JSON.stringify(Xs(t,r))}catch{return!1}}function fa(e,t,r){return Ld(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Hi(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function _d(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Ao(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,i=Ki(e.childSessions,t.childSessions,{preserveMissing:n}),c=Bi(t.activeChat,e.activeChat);return Fi(e,t,{...e,...t,chats:a,childSessions:i,activeChat:c,_lastUpdate:r})}function Pd(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=Ki(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"])_d(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Dd(e,t,r,n){const a=Pd(e,t,n),i=Object.keys(a).length>0?Fi(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return fa(e,i,r)}function Ed(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=Hi(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 $d(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 Bd(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function Kd(e,t,r){var u,f;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(x=>({...x,_lastUpdate:n}));const i=new Map;for(const x of t)i.set(x.id,x);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:m}=Ed(e);for(const x of e){const N=i.get(x.id);if(!N){i.set(x.id,{...x,_lastUpdate:n});continue}const g=Mo(x),h=Mo(N),k=Hi(x),b=!a.has(k);if(g>h){const S=Ao(N,x,n,b);i.set(x.id,fa(N,S,n));continue}if(g<h){i.set(x.id,Dd(N,x,n,b));continue}const p=x.timestamp||n,y=N._lastUpdate||N.timestamp||0;if(p>=y){const S=Ao(N,x,n,b);i.set(x.id,fa(N,S,n));continue}(u=x.chats)!=null&&u.length&&!((f=N.chats)!=null&&f.length)&&i.set(x.id,{...N,chats:x.chats})}for(const[x,N]of i){const g=N.daemonId||x.split(":")[0];if(!l.has(g))continue;if(a.has(g)&&m.has(g)&&!c.has(x)){i.delete(x);continue}const h=n-(N._lastUpdate||N.timestamp||0);$d(N,g,h,c,a,d)&&i.delete(x)}for(const[x,N]of i){const g=N.daemonId||x.split(":")[0];if(Bd(N,g,l,d,i))continue;n-(N._lastUpdate||N.timestamp||0)>3e5&&N.status!=="online"&&i.delete(x)}return Array.from(i.values())}function Wd(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 Od({children:e,connectionOverrides:t}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[d,m]=o.useState(void 0),u=o.useRef(r);o.useEffect(()=>{u.current=r},[r]);const f=o.useCallback((b,p)=>{n(y=>{let S=!1;const j=y.map(A=>A.id!==b||A.chats===p?A:(S=!0,{...A,chats:p}));return S?j:y})},[]),x=o.useCallback((b,p)=>{n(y=>{const S=y.length===0?b:Kd(b,y,p),j=!Wd(y,S);return j&&Cs.record({kind:"dashboard.entries_applied",payload:{incoming:Co(b),next:Co(S)}}),j?S:y})},[]),N=o.useCallback(()=>i(!0),[]),g=o.useMemo(()=>({injectEntries:x,markLoaded:N,getIdes:()=>u.current}),[x,N]),h=t,k=o.useMemo(()=>({ides:r,updateRouteChats:f,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(h==null?void 0:h.wsStatus)??"connected",isConnected:(h==null?void 0:h.isConnected)??!0,connectionStates:(h==null?void 0:h.connectionStates)??{},connectionTransports:(h==null?void 0:h.connectionTransports)??{},showReconnected:(h==null?void 0:h.showReconnected)??!1,retryConnection:h==null?void 0:h.retryConnection,retryServerConnection:h==null?void 0:h.retryServerConnection,connectionLoginUrl:h==null?void 0:h.connectionLoginUrl,isP2PActive:(h==null?void 0:h.isP2PActive)??!1,p2pStates:(h==null?void 0:h.p2pStates)??{},userRole:h==null?void 0:h.userRole,connectionRetryStatuses:h==null?void 0:h.connectionRetryStatuses,userName:d,setUserName:m}),[r,f,a,c,h==null?void 0:h.wsStatus,h==null?void 0:h.isConnected,h==null?void 0:h.connectionStates,h==null?void 0:h.connectionTransports,h==null?void 0:h.showReconnected,h==null?void 0:h.retryConnection,h==null?void 0:h.retryServerConnection,h==null?void 0:h.connectionLoginUrl,h==null?void 0:h.isP2PActive,h==null?void 0:h.p2pStates,h==null?void 0:h.userRole,h==null?void 0:h.connectionRetryStatuses,d]);return s.jsx(Oi.Provider,{value:g,children:s.jsx(Wi.Provider,{value:k,children:e})})}function Jt(){return o.useContext(Wi)}function nr(){return o.useContext(Oi)}function Ui(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 d=r==null?void 0:r(),m=a(l),u=l.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!l.startsWith("http")&&!t?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function c(l,d={}){const m={"Content-Type":"application/json",...d.headers||{}},u=r==null?void 0:r();u&&(m.Authorization=`Bearer ${u}`);const f=a(l),x=new AbortController,N=setTimeout(()=>x.abort(),15e3);try{const g=await fetch(f,{...d,headers:m,signal:x.signal});if(g.status===401)throw n==null||n(),new Error("Unauthorized");if(!g.ok){const h=await g.json().catch(()=>({error:g.statusText}));throw new Error(h.error||`API Error: ${g.status}`)}return g.json()}finally{clearTimeout(N)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,d,m={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),execTerminal:(l,d,m)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:m})}),sendAgentMessage:(l,d,m)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:m})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,d,m)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:d,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,d,m={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Fd=Ui({baseUrl:"http://localhost:3847"}),Hd=o.createContext(Fd);function Ud({client:e,children:t}){return s.jsx(Hd.Provider,{value:e,children:t})}const zd={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},zi=o.createContext(zd);function Vd({value:e,children:t}){return s.jsx(zi.Provider,{value:e,children:t})}function xt(){return o.useContext(zi)}function Gd(e){let t=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)t^=n.charCodeAt(a),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function qd(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Yd(e){return e?Gd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),qd(e.content)]):""}const We={size:18};function Vi({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Pa({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Ot({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function Gi({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Xd({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Jd({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function qi({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Qd({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function cn({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Yi({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Zd({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Ut({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Tt({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Da({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("polyline",{points:"14 2 14 8 20 8"}),s.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),s.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function eu({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function us({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function cr({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function ar({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Ms({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function vr({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"5",r:"2"}),s.jsx("circle",{cx:"5",cy:"19",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),s.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),s.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function Xi({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Ea({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),s.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Ji({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function tu({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function $a({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function su({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Ba({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Qi({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function yt({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function ru({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),s.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),s.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),s.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function nu({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function au({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function ou({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function ln({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function iu({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"5"}),s.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),s.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),s.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),s.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),s.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),s.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),s.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),s.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function cu({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function lu({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function du({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function uu({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function mu({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function fu({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function pu({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function hu({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function xu({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function bu({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function gu({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const Zi=[xd,{singleTilde:!1}],ec=[Zi,bd,gd],yu=[Zi],Ka=200,vu=80,Io=650,Ks=new Map;function qr(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function wu(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}:${Yd(n)}`}function ju(e,t,r,n){return e||!t?!1:qr(r,n)}function ku({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=vu,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 Su(e){return ku({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Ys(e,t=Ka){return!!e&&e.fromBottom>=t}function Nu(e,t){return qr(e,t)?!Ys(e):!0}function Cu({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function Tu({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function kn(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function tc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Mu(e,t,r){return Number(e.receivedAt||r[Yr(e,t)]||0)||0}function sc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Au(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function wr(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 Sn(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 Ro(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):sc(e)?s.jsx(Ra,{remarkPlugins:ec,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function jr({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:Ro(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=Sn(r);return a?s.jsx("img",{src:a,alt:wr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=Sn(r);return a?s.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=Sn(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:wr(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||wr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=wr(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}),Ro(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 Yr(e,t){const r=e,n=_a(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 Iu=o.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Ra,{remarkPlugins:yu,children:t.text}),s.jsx("span",{className:"action-time",children:tc(t.timestamp)})]})},(e,t)=>e.log===t.log),Ru=o.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var A,M,w;const d=(t.role||"").toLowerCase(),m=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),f=Au(t.content)?t.content:null,x=!!(f!=null&&f.some(v=>v.type!=="text")),N=_a(t.content,{joiner:`
|
|
4
|
-
`});if(u==="thought"){const v=typeof((A=t.meta)==null?void 0:A.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(au,{size:13}),s.jsx("span",{children:v})]}),s.jsx("div",{className:"chat-msg-body",children:N})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),x&&f?s.jsx("div",{className:"tool-text w-full",children:s.jsx(jr,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:N})]});if(u==="terminal"){const v=(M=t.meta)!=null&&M.isRunning?"⏳":"✅",B=typeof((w=t.meta)==null?void 0:w.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:v}),s.jsx("span",{children:B})]}),x&&f?s.jsx("div",{className:"chat-msg-body",children:s.jsx(jr,{parts:f,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:N})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:x&&f?s.jsx(jr,{parts:f,renderAsPreformatted:!1}):N.slice(0,100)});const g=t.meta,k=(typeof(g==null?void 0:g.renderMode)=="string"?g.renderMode.trim():"")==="preformatted",b=N,p=!1,y=b,S=k,j=!S&&sc(y);return s.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${m?"self-end":"self-start"}`,children:(b||x||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${b||x?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:m?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:tc(r)})]}),(b||x)&&s.jsx("div",{className:"chat-markdown",children:x&&f?s.jsx(jr,{parts:f,renderAsPreformatted:S}):S?s.jsx("pre",{className:"chat-preformatted",children:y}):j?s.jsx(Ra,{remarkPlugins:ec,children:y}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:y})}),p]})})},(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),Lu=o.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:d={},lastMessageHash:m,emptyState:u,onLoadMore:f,isLoadingMore:x,hasMoreHistory:N,hiddenLiveCount:g=0,loadError:h,scrollToBottomRequestNonce:k,isVisible:b=!0},p){const y=o.useRef(null),S=o.useRef(null),j=o.useRef(null),A=o.useRef(0),M=o.useRef(""),w=o.useRef(""),v=o.useRef(!1),B=o.useRef(null),_=o.useRef(!1),T=o.useRef(null),D=o.useRef(!1),[K,L]=o.useState(new Set),[C,I]=o.useState({showTop:!1,showBottom:!1}),W=o.useRef(!1),P=o.useRef(!1),$=o.useRef(b),H=o.useRef(b),Q=o.useRef(null);H.current=b;const xe=()=>{const Y=y.current;return Y?Y.scrollHeight-Y.scrollTop-Y.clientHeight<Ka:!0},ie=o.useCallback(()=>{const Y=y.current,V=Y?Su(Y):{showTop:!1,showBottom:!1};I(le=>le.showTop===V.showTop&&le.showBottom===V.showBottom?le:V)},[]),se=o.useCallback((Y="auto")=>{var le;const V=y.current;V&&(V.scrollTo({top:V.scrollHeight,behavior:Y}),(le=V.ownerDocument.defaultView)==null||le.requestAnimationFrame(()=>ie()))},[ie]),be=o.useCallback((Y="auto")=>{var le;const V=y.current;V&&(V.scrollTo({top:0,behavior:Y}),(le=V.ownerDocument.defaultView)==null||le.requestAnimationFrame(()=>ie()))},[ie]),we=o.useCallback(()=>{var ee;const Y=y.current,V=(ee=window.getSelection)==null?void 0:ee.call(window);if(!Y||!V||V.rangeCount===0||V.isCollapsed){D.current=!1;return}const le=V.anchorNode,ke=V.focusNode;D.current=!!(le&&ke&&Y.contains(le)&&Y.contains(ke))},[]),ge=wu(t,m),J=o.useCallback(()=>{const Y=y.current;if(!Y||!l||!H.current)return;const V={top:Y.scrollTop,fromBottom:Math.max(0,Y.scrollHeight-Y.scrollTop-Y.clientHeight),messageFingerprint:ge};Q.current={contextKey:l,snapshot:V},Ks.set(l,V)},[l,ge]),ce=o.useCallback((Y="auto")=>{B.current!=null&&cancelAnimationFrame(B.current),B.current=requestAnimationFrame(()=>{B.current=null,se(Y)})},[se]),ye=o.useCallback(()=>{W.current=!1,_.current=!0,P.current=!0,T.current!=null&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{_.current=!1,T.current=null},Io)},[]);o.useEffect(()=>{const Y=!v.current,V=w.current!==l;if(w.current=l,Y||V){v.current=!0;const ke=l?Ks.get(l):null,ee=!!ke&&qr(ke,ge);W.current=ee?Ys(ke):!1,_.current=Nu(ke,ge),D.current||(ee?requestAnimationFrame(()=>{const Pe=y.current;Pe&&(kn(Pe,ke),W.current=Ys(ke),ie(),P.current=!0)}):ce("auto")),A.current=t.length,M.current=ge;return}t.length>A.current;const le=ge!==M.current;Cu({hasSelection:D.current,userScrolledUp:W.current,hasChatContentChanged:le})&&ce("auto"),A.current=t.length,M.current=ge},[ge,l,t.length,ce,ie]),o.useEffect(()=>{k&&(ye(),D.current||ce("auto"))},[ye,ce,k]),o.useEffect(()=>{const Y=$.current;Y&&!b&&J(),H.current=b,$.current=b;const V=l?Ks.get(l):null;if(ju(Y,b,V,ge)){if(!V)return;W.current=Ys(V),_.current=!1,D.current||requestAnimationFrame(()=>{const le=y.current;le&&(kn(le,V),ie())});return}},[b,l,ge,ye,J,ce,ie]),o.useEffect(()=>()=>{const Y=Q.current;Y&&Ks.set(Y.contextKey,Y.snapshot),B.current!=null&&cancelAnimationFrame(B.current),T.current!=null&&window.clearTimeout(T.current)},[]),o.useEffect(()=>{const Y=S.current,V=y.current;if(!Y||!V)return;const le=()=>{T.current!=null&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{_.current=!1,T.current=null},Io)},ke=new ResizeObserver(()=>{ie();const ee=_.current;Tu({hasSelection:D.current,userScrolledUp:W.current,contextAutoScrollActive:ee})&&(ce("auto"),ee&&le())});return ke.observe(Y),V!==Y&&ke.observe(V),()=>{ke.disconnect(),T.current!=null&&(window.clearTimeout(T.current),T.current=null)}},[ce,l,ie]),o.useImperativeHandle(p,()=>({scrollToBottom:(Y="smooth")=>{se(Y)}}),[se]),o.useEffect(()=>{const Y=y.current;if(!Y)return;let V;const le=()=>{J(),clearTimeout(V),V=setTimeout(()=>{W.current=!xe(),ie()},50)};return Y.addEventListener("scroll",le,{passive:!0}),()=>{Y.removeEventListener("scroll",le),clearTimeout(V)}},[J,ie]),o.useEffect(()=>(document.addEventListener("selectionchange",we),()=>document.removeEventListener("selectionchange",we)),[we]);const ae=o.useRef(0),de=o.useRef(!1);o.useEffect(()=>{const Y=y.current;if(!Y||!de.current||ae.current===0)return;const V=Y.scrollHeight-ae.current;V>0&&(Y.scrollTop=V),ie(),J(),ae.current=0,de.current=!1},[t.length,J,ie]),o.useEffect(()=>{if(P.current||!l)return;const Y=Ks.get(l),V=y.current;if(!(!Y||!V)){if(!qr(Y,ge)){se("auto"),P.current=!0;return}kn(V,Y),W.current=Ys(Y),ie(),P.current=!0}},[l,ge,t.length,se,ie]);const je=()=>{const Y=y.current;Y&&(ae.current=Y.scrollHeight),de.current=!0,f==null||f()},fe=()=>{W.current=!0,be("smooth"),J()},pe=()=>{ye(),se("smooth"),J()},te=o.useMemo(()=>{const Y=t.map((ee,Pe)=>({type:"message",data:ee,index:Pe,ts:Mu(ee,Pe,d)}));if(!r||r.length===0)return Y;const V=[...r].sort((ee,Pe)=>ee.timestamp-Pe.timestamp).map((ee,Pe)=>({type:"action",data:ee,index:Pe,ts:ee.timestamp})),le=[];let ke=0;for(const ee of Y){for(;ke<V.length&&ee.ts>0&&V[ke].ts<ee.ts;)le.push(V[ke++]);le.push(ee)}for(;ke<V.length;)le.push(V[ke++]);return le},[t,r,d]),me=g>0||!!N,oe=g>0?`↑ Show ${Math.min(g,80)} earlier messages${g>80?` (${g} hidden)`:""}`:h?`↻ ${h}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:y,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:S,className:"chat-container-content",children:[x&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),me&&!x&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:je,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${h&&g===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:oe})}),te.length===0&&!me&&(u||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),te.map(Y=>{if(Y.type==="action"){const Oe=Y.data;return s.jsx(Iu,{log:Oe},`action-${Y.index}`)}const V=Y.data,le=Y.index,ke=Yr(V,le),ee=V.receivedAt||d[ke],Pe=`${l}-${ke}`,$e=K.has(Pe);return s.jsx(Ru,{message:V,receivedAt:ee,agentName:n,userName:a,isCliMode:i,isTextExpanded:$e,onToggleTextExpanded:()=>L(Oe=>{const He=new Set(Oe);return $e?He.delete(Pe):He.add(Pe),He})},`msg-${ke}`)}),c&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),s.jsx("div",{className:"min-h-10",ref:j})]})}),(C.showTop||C.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[C.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:fe,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),C.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:pe,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),_u=o.memo(Lu,(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),Pu="modulepreload",Du=function(e){return"/"+e},Lo={},Eu=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=Du(d),d in Lo)return;Lo[d]=!0;const m=d.endsWith(".css"),u=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":Pu,m||(f.as="script"),f.crossOrigin="",f.href=d,l&&f.setAttribute("nonce",l),document.head.appendChild(f),m)return new Promise((x,N)=>{f.addEventListener("load",x),f.addEventListener("error",()=>N(new Error(`Unable to preload CSS for ${d}`)))})}))}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 _o=!1;const rc=o.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:i="measured"},c)=>{const l=o.useRef(null),[d,m]=o.useState(null),u=o.useRef([]),f=o.useRef(!1),x=o.useRef(!1),N=o.useRef(!1),g=o.useRef(!1),h=()=>{const k=l.current;if(k){f.current&&(k.clear(),f.current=!1);for(const b of u.current)k.write(b.data,b.onProcessed);u.current=[],x.current&&(k.fit(),x.current=!1),N.current&&(k.bumpResize(),N.current=!1),g.current&&(k.scrollToTop(),g.current=!1)}};return o.useImperativeHandle(c,()=>({write:(k,b)=>{l.current?l.current.write(k,b):u.current.push({data:k,onProcessed:b})},clear:()=>{l.current?l.current.clear():(u.current=[],f.current=!0)},reset:()=>{l.current&&typeof l.current.reset=="function"?l.current.reset():(u.current=[],f.current=!0)},resize:(k,b)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(k,b)},fit:()=>{l.current?l.current.fit():x.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():N.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():g.current=!0},getSelection:()=>{var k,b;return((b=(k=l.current)==null?void 0:k.getSelection)==null?void 0:b.call(k))||""},getVisibleText:()=>{var k,b;return((b=(k=l.current)==null?void 0:k.getVisibleText)==null?void 0:b.call(k))||""}}),[]),o.useEffect(()=>{d&&h()},[d]),o.useEffect(()=>{let k=!1;return Eu(()=>import("./terminal-BeBmUW3m.js"),__vite__mapDeps([0,1,2])).then(b=>{_o||(_o=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),k||m(()=>b.GhosttyTerminalView)}).catch(b=>{console.error("[CliTerminal] failed to load terminal renderer",b)}),()=>{k=!0}},[]),d?s.jsx(d,{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"}})});rc.displayName="CliTerminal";function kr({label:e,value:t,sub:r,icon:n}){return s.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:n}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),r&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function Po({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact: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 $u({cursorPos:e,viewportRef:t,imgRef:r}){var p;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(p=t.current)==null?void 0:p.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,d=c/l,m=a.width/a.height;let u,f,x,N;d>m?(u=a.width,f=a.width/d,x=0,N=(a.height-f)/2):(f=a.height,u=a.height*d,x=(a.width-u)/2,N=0);const g=a.left-i.left+x+u*e.nx,h=a.top-i.top+N+f*e.ny,k=Math.max(8,Math.min(i.width-8,g)),b=Math.max(8,Math.min(i.height-8,h));return s.jsxs("div",{style:{position:"absolute",left:k-8,top:b-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 Bu({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:f,mobileFillZoom:x,onZoomOut:N,onZoomReset:g,onZoomIn:h,transportType:k,screenshotUsage:b,lastActionStatus:p}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:y=>y.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(y=>!y),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:y=>y.stopPropagation(),onChange:y=>l(y.target.value),onKeyDown:y=>{d(y)},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(y=>!y),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:m?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),u>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),k==="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"}),k==="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"}),b&&b.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:b.budgetExhausted?"#ef4444":"#c4b5fd",background:b.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:b.budgetExhausted?"TURN blocked":`TURN ${b.dailyUsedMinutes}/${b.dailyBudgetMinutes}m`}),p&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:p})]})]}),a&&s.jsxs("div",{onTouchStart:y=>y.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(f?x:1)+.01?f?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:y=>{y.stopPropagation(),N()},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:y=>{y.stopPropagation(),g()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:f?"FILL":"FIT"}),s.jsx("button",{onClick:y=>{y.stopPropagation(),h()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function Ku({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 Do(e){return e==null||typeof e=="number"||typeof e=="boolean"?e:typeof e=="string"?e.length>64?`${e.slice(0,61)}...`:e:Array.isArray(e)?`Array(${e.length})`:typeof e=="object"?"Object":typeof e}function lr(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,Do(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,Do(t[c])]))}),r.current=t})}function Ou({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:d,setPanX:m,setPanY:u,setZoom:f,lastWheelTimeRef:x,onAction:N,setLastActionStatus:g,spawnRippleFromNormalized:h,clampPan:k,isMobile:b,mobileFillZoom:p}){const[y,S]=o.useState(null),j=o.useRef(null),A=o.useRef(null),M=o.useRef(null),w=o.useRef(!1),v=o.useRef(null),B=o.useRef(0),_=o.useRef(null),T=o.useRef(1),D=o.useRef({x:0,y:0}),K=o.useRef(!1),L=o.useRef(n),C=o.useRef(N),I=30,W=550,P=18,$=60,H=400,Q=12,xe=()=>{if(j.current)return;const be={nx:.5,ny:.5};j.current=be,S(be)};return o.useEffect(()=>{L.current=n,n==="mouse"&&xe()},[n]),o.useEffect(()=>{C.current=N},[N]),o.useEffect(()=>{const be=e.current;if(!be)return;const we=de=>{if(!r.current)return null;const je=r.current.getBoundingClientRect();return!je.width||!je.height?null:{nx:Math.max(0,Math.min(1,(de.clientX-je.left)/je.width)),ny:Math.max(0,Math.min(1,(de.clientY-je.top)/je.height))}},ge=(de,je)=>{if(!r.current)return{dnx:0,dny:0};const fe=r.current,pe=fe.getBoundingClientRect(),te=fe.naturalWidth||pe.width,me=fe.naturalHeight||pe.height,oe=te/me,Y=pe.width/pe.height;let V,le;return oe>Y?(V=pe.width,le=pe.width/oe):(le=pe.height,V=pe.height*oe),{dnx:de/V,dny:je/le}},J=(de,je,fe)=>{if(fe<=1.05)return;const pe=-(de-.5)*100,te=-(je-.5)*100,me=k(pe,te,fe);(Math.abs(me.x-l.current)>.1||Math.abs(me.y-d.current)>.1)&&(m(me.x),u(me.y),l.current=me.x,d.current=me.y)},ce=de=>{const je=t.current;if(je&&de.target instanceof Node&&je.contains(de.target))de.preventDefault();else return;if(de.touches.length===1){const fe=de.touches[0];A.current={x:fe.clientX,y:fe.clientY,time:Date.now()},M.current={x:fe.clientX,y:fe.clientY},K.current||(w.current=!1),v.current=setTimeout(()=>{if(!w.current&&!K.current)if(w.current=!0,L.current==="mouse"){const pe=j.current||{nx:.5,ny:.5};g("Right Click"),h(pe.nx,pe.ny,"right"),C.current("input_click",{...pe,button:"right"}).catch(()=>{})}else{const pe=we(fe);pe&&(g("Right Click"),h(pe.nx,pe.ny,"right"),C.current("input_click",{...pe,button:"right"}).catch(()=>{}))}},500);return}if(de.touches.length===2){v.current&&clearTimeout(v.current),w.current=!0,K.current=!0;const fe=de.touches[1].clientX-de.touches[0].clientX,pe=de.touches[1].clientY-de.touches[0].clientY;_.current=Math.sqrt(fe*fe+pe*pe),T.current=c.current,D.current={x:(de.touches[0].clientX+de.touches[1].clientX)/2,y:(de.touches[0].clientY+de.touches[1].clientY)/2}}},ye=de=>{const je=t.current;if(je&&de.target instanceof Node&&je.contains(de.target)&&de.preventDefault(),de.touches.length===1&&M.current){const fe=de.touches[0],pe=fe.clientX-M.current.x,te=fe.clientY-M.current.y;if(!w.current&&A.current){const me=fe.clientX-A.current.x,oe=fe.clientY-A.current.y;Math.sqrt(me*me+oe*oe)>8&&(w.current=!0,v.current&&clearTimeout(v.current))}if(w.current)if(L.current==="mouse"){const me=ge(pe,te),oe=j.current||{nx:.5,ny:.5},Y=Math.max(0,Math.min(1,oe.nx+me.dnx)),V=Math.max(0,Math.min(1,oe.ny+me.dny));j.current={nx:Y,ny:V},S({nx:Y,ny:V}),g(`Cursor: ${Math.round(Y*100)}%, ${Math.round(V*100)}%`),J(Y,V,c.current);const le=Date.now();le-x.current>=30&&(x.current=le,C.current("input_mouseMoved",{nx:Y,ny:V}).catch(()=>{}))}else if(c.current>1){const me=t.current;if(me){const oe=me.clientWidth,Y=me.clientHeight,V=l.current+pe/oe*100,le=d.current+te/Y*100,ke=k(V,le,c.current);m(ke.x),u(ke.y),l.current=ke.x,d.current=ke.y}}else{const me=we(fe);if(me){const oe=Date.now();oe-x.current>=40&&(x.current=oe,g("Scroll"),C.current("input_wheel",{nx:me.nx,ny:me.ny,deltaX:Math.round(-pe*2.5),deltaY:Math.round(-te*2.5)}).catch(()=>{}))}}M.current={x:fe.clientX,y:fe.clientY};return}if(de.touches.length===2&&_.current!==null){const fe=de.touches[1].clientX-de.touches[0].clientX,pe=de.touches[1].clientY-de.touches[0].clientY,me=Math.sqrt(fe*fe+pe*pe)/_.current,oe=(de.touches[0].clientX+de.touches[1].clientX)/2,Y=(de.touches[0].clientY+de.touches[1].clientY)/2,V=oe-D.current.x,le=Y-D.current.y,ke=Math.abs(me-1)>.03;if(L.current==="mouse"){if(ke){const ee=Math.max(i,Math.min(5,T.current*me));f(ee),c.current=ee}else if(Math.abs(V)>2||Math.abs(le)>2){const ee=j.current||{nx:.5,ny:.5},Pe=Date.now();Pe-x.current>=30&&(x.current=Pe,g("Scroll"),C.current("input_wheel",{nx:ee.nx,ny:ee.ny,deltaX:Math.round(-V*3),deltaY:Math.round(-le*3)}).catch(()=>{}))}}else{const ee=Math.max(i,Math.min(5,T.current*me));f(ee),c.current=ee;const Pe=t.current;if(Pe&&ee>1){const $e=Pe.clientWidth,Oe=Pe.clientHeight,He=l.current+V/$e*100,O=d.current+le/Oe*100,Ce=k(He,O,ee);m(Ce.x),u(Ce.y),l.current=Ce.x,d.current=Ce.y}}D.current={x:oe,y:Y}}},ae=de=>{var je;if(v.current&&clearTimeout(v.current),_.current=null,de.touches.length===1&&K.current){const fe=de.touches[0];A.current={x:fe.clientX,y:fe.clientY,time:Date.now()},M.current={x:fe.clientX,y:fe.clientY},w.current=!0;return}if(de.touches.length===0){if(K.current){K.current=!1,w.current=!1;return}if(de.changedTouches.length===1){const fe=de.changedTouches[0],pe=Date.now(),te=pe-(((je=A.current)==null?void 0:je.time)||0),me=A.current?fe.clientX-A.current.x:0,oe=A.current?fe.clientY-A.current.y:0,Y=Math.sqrt(me*me+oe*oe);if(L.current==="mouse"){if(te<I||te>W||Y>P){w.current=!1;return}const V=j.current||we(fe);V&&(g(`Click: ${Math.round(V.nx*100)}%, ${Math.round(V.ny*100)}%`),h(V.nx,V.ny,"left"),C.current("input_click",{...V}).catch(()=>{}))}else{if(w.current){w.current=!1;return}if(te<$||te>H||Y>Q){w.current=!1;return}const V=we(fe);if(!V)return;pe-B.current<300?(g("Double tap"),h(V.nx,V.ny,"double"),C.current("input_click",{...V,clickCount:2}).catch(()=>{}),B.current=0):(g(`Tap: ${Math.round(V.nx*100)}%, ${Math.round(V.ny*100)}%`),h(V.nx,V.ny,"left"),C.current("input_click",{...V}).catch(()=>{}),B.current=pe)}}w.current=!1}};return be.addEventListener("touchstart",ce,{passive:!1}),be.addEventListener("touchmove",ye,{passive:!1}),be.addEventListener("touchend",ae,{passive:!1}),()=>{be.removeEventListener("touchstart",ce),be.removeEventListener("touchmove",ye),be.removeEventListener("touchend",ae),v.current&&clearTimeout(v.current)}},[e,t,r,i,c,l,d,m,u,f,x,g,h,k]),{cursorPos:y,cursorPosRef:j,handleToggleInputMode:()=>{a(be=>{const we=be==="touch"?"mouse":"touch";return we==="mouse"&&xe(),we})},handleZoomReset:()=>{const be=b?p:1;f(be),c.current=be,m(0),u(0),l.current=0,d.current=0}}}function nc({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),d=o.useRef(null),[m,u]=o.useState(null),[f,x]=o.useState(""),[,N]=o.useState(!1),[g,h]=o.useState([]),k=o.useRef(0),[b,p]=o.useState(!1),[y,S]=o.useState(!1),j=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[A,M]=o.useState(j?"mouse":"touch"),[w,v]=o.useState(1),B=o.useRef(!1),[_,T]=o.useState(1),[D,K]=o.useState(0),[L,C]=o.useState(0);lr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:A,zoom:_,panX:D,panY:L,isMenuOpen:b,isImeOpen:y});const I=o.useRef(0),W=o.useRef(_),P=o.useRef(D),$=o.useRef(L);o.useEffect(()=>{W.current=_},[_]),o.useEffect(()=>{P.current=D},[D]),o.useEffect(()=>{$.current=L},[L]),o.useEffect(()=>{var te;(te=c.current)==null||te.focus()},[]);const H=r==="connected",Q=n,xe=H?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ie=H?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!j||B.current||!Q)return;const te=d.current,me=l.current;if(!te||!me)return;const oe=()=>{const Y=me.clientWidth,V=me.clientHeight,le=te.naturalWidth,ke=te.naturalHeight;if(!le||!ke||!Y||!V)return;const ee=Math.min(Y/le,V/ke),$e=Math.max(Y/le,V/ke)/ee;$e>1.01&&(v($e),T($e),W.current=$e),B.current=!0};te.complete&&te.naturalWidth?oe():te.addEventListener("load",oe,{once:!0})},[Q,j]);const se=.5;o.useEffect(()=>{_<=se&&(K(0),C(0))},[_,se]);const be=(te,me,oe)=>{if(oe<=se)return{x:0,y:0};const Y=(oe-1)/(2*oe)*100,V=(oe-1)/(2*oe)*100;return{x:Math.max(-Y,Math.min(Y,te)),y:Math.max(-V,Math.min(V,me))}},we=(te,me)=>{if(!d.current)return null;const oe=d.current.getBoundingClientRect();return!oe.width||!oe.height?null:{nx:Math.max(0,Math.min(1,(te-oe.left)/oe.width)),ny:Math.max(0,Math.min(1,(me-oe.top)/oe.height))}},ge=(te,me,oe)=>{const Y=l.current;if(!Y)return;const V=Y.getBoundingClientRect(),le=++k.current;h(ke=>[...ke,{id:le,x:te-V.left,y:me-V.top,type:oe}]),setTimeout(()=>h(ke=>ke.filter(ee=>ee.id!==le)),600)},J=(te,me,oe)=>{const Y=d.current,V=l.current;if(!Y||!V)return;const le=Y.getBoundingClientRect(),ke=V.getBoundingClientRect(),ee=Y.naturalWidth||le.width,Pe=Y.naturalHeight||le.height,$e=ee/Pe,Oe=le.width/le.height;let He,O,Ce,Te;$e>Oe?(He=le.width,O=le.width/$e,Ce=0,Te=(le.height-O)/2):(O=le.height,He=le.height*$e,Ce=(le.width-He)/2,Te=0);const Re=le.left-ke.left+Ce+He*te,Be=le.top-ke.top+Te+O*me,Fe=++k.current;h(Ye=>[...Ye,{id:Fe,x:Re,y:Be,type:oe}]),setTimeout(()=>h(Ye=>Ye.filter(tt=>tt.id!==Fe)),600)},ce=async te=>{var oe;const me=we(te.clientX,te.clientY);if(me){u(`Click: ${Math.round(me.nx*100)}%, ${Math.round(me.ny*100)}%`),ge(te.clientX,te.clientY,"left"),(oe=c.current)==null||oe.focus();try{const Y=await e("input_click",{nx:me.nx,ny:me.ny});Y!=null&&Y.success||t(`❌ Click failed: ${Y==null?void 0:Y.error}`)}catch(Y){t(`❌ Click error: ${Y.message||Y}`)}}},ye=async(te,me,oe,Y=0)=>{try{await e("input_key",{type:oe?"char":"keyDown",key:te,code:me,text:oe?te:void 0,unmodifiedText:oe?te:void 0,modifiers:Y})}catch(V){t(`❌ Key error: ${V.message||V}`)}},ae=async te=>{if(te.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(te.key)&&te.preventDefault();let oe=0;te.altKey&&(oe|=1),te.ctrlKey&&(oe|=2),te.metaKey&&(oe|=4),te.shiftKey&&(oe|=8),u(`Key: ${te.key}`),await ye(te.key,te.code,te.key.length===1,oe)},de=async te=>{if(te.key==="Enter"){if(te.nativeEvent.isComposing)return;if(f){const me=f;x(""),u(`IME Sent: ${me}`);try{const oe=await e("input_type",{text:me});oe!=null&&oe.success||t(`❌ IME error: ${oe==null?void 0:oe.error}`)}catch(oe){t(`❌ IME error: ${oe.message}`)}}else u("Key: Enter"),await ye("Enter","Enter",!1)}};o.useEffect(()=>{const te=c.current;if(!te)return;const me=oe=>{var Y;if((Y=d.current)!=null&&Y.contains(oe.target)){oe.preventDefault();const V=Date.now();if(V-I.current<40)return;I.current=V;const le=we(oe.clientX,oe.clientY);if(!le)return;u(`Scroll: ${Math.round(oe.deltaY)}`),e("input_wheel",{nx:le.nx,ny:le.ny,deltaX:Math.round(oe.deltaX),deltaY:Math.round(oe.deltaY)}).catch(()=>{})}};return te.addEventListener("wheel",me,{passive:!1}),()=>te.removeEventListener("wheel",me)},[e]);const{cursorPos:je,handleToggleInputMode:fe,handleZoomReset:pe}=Ou({containerRef:c,viewportRef:l,imgRef:d,inputMode:A,setInputMode:M,minZoom:se,zoomRef:W,panXRef:P,panYRef:$,setPanX:K,setPanY:C,setZoom:T,lastWheelTimeRef:I,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:J,clampPan:be,isMobile:j,mobileFillZoom:w});return s.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ae,onContextMenu:te=>te.preventDefault(),onFocus:()=>N(!0),onBlur:()=>N(!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:d,src:Q,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${_}) translate(${D}%, ${L}%)`,transformOrigin:"center center",cursor:A==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ce,onContextMenu:te=>te.preventDefault(),onDragStart:te=>te.preventDefault()}):s.jsx(Ku,{waitingLabel:xe,waitingHint:ie,transportType:i}),A==="mouse"&&Q&&s.jsx($u,{cursorPos:je,viewportRef:l,imgRef:d}),g.map(te=>{const oe={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[te.type];return s.jsxs("div",{style:{position:"absolute",left:te.x,top:te.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${oe}, 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(${oe}, 0.9)`,boxShadow:`0 0 12px rgba(${oe}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},te.id)})]}),s.jsx(Bu,{inputMode:A,onToggleInputMode:fe,isImeOpen:y,setIsImeOpen:S,isMenuOpen:b,setIsMenuOpen:p,imeText:f,setImeText:x,handleImeSubmit:de,isConnActive:H,zoom:_,isMobile:j,mobileFillZoom:w,onZoomOut:()=>T(te=>Math.max(.5,te-.25)),onZoomReset:pe,onZoomIn:()=>T(te=>Math.min(5,te+.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 dn(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 d=Math.floor(l/60);if(d<24)return`${d}h${r}`;const m=Math.floor(d/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const ac=e=>dn(e);function Fu(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 Es(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 Hu(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...Fu(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 Xr(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 un(e,t,r){const n=Xr(e,t),a=Es(e),i=a.isReconnecting,c=a.isConnecting,l=a.isGenerating,d=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,u=n.inboxBucket==="working"||l,x=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:x,requiresAction:m,isWorking:u,isReconnecting:i,isConnecting:c,isGenerating:l,isWaiting:d,inboxBucket:m?"needs_attention":u?"working":x?"task_complete":"idle"}}function Uu(e,t,r){return un(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function oc({activeConv:e,onModalButton:t}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Es(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(ar,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,d)=>{const m=c(l).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(m),f=/^(reject|deny|delete|remove|abort)/.test(m),x=r===l,N=r!==null;return s.jsx("button",{onClick:()=>i(l),disabled:N,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":f?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${N&&!x?"opacity-40":"opacity-100"} ${N?"cursor-not-allowed":"cursor-pointer"}`,style:u?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:f?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:x?"⏳ ...":c(l)},d)})})]})]})}const Wa="adhdev_controls_bar_visible",pa="adhdev:controlsbarvisibilitychange";function Nn(e){if(!e)return!1;try{return e.getItem(Wa)==="1"}catch{return!1}}function zu(e,t){if(t)try{t.setItem(Wa,e?"1":"0")}catch{}}function Vu(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(pa,{detail:{visible:e}}))}function Oa(){const[e,t]=o.useState(()=>typeof window>"u"?!1:Nn(window.localStorage)),r=o.useRef(e),n=o.useCallback((c,l=!0)=>{r.current=c,t(c),typeof window<"u"&&zu(c,window.localStorage),l&&Vu(c)},[]);o.useEffect(()=>{const c=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:Nn(window.localStorage);r.current=u,t(u)},l=d=>{if(d.key!==Wa)return;const m=Nn(window.localStorage);r.current=m,t(m)};return window.addEventListener(pa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(pa,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{n(c)},[n]),i=o.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:i}}var Gu=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function qu(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function wt(e,t){if(qu(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Gu.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 ic(e){return wt(e)==="generating"}function ot(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Yu(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 Cn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function mn(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 Xu(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 Ju(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Qu(e){return Xu(e.trim().replace(/\.local$/i,""))}function Zu(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function cc(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&&!Ju(c));if(r&&r!=="Unknown")return Qu(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Ct(e,t={}){return Zu(e)||cc(e,t)}function lc(e){return!e||!Array.isArray(e.items)?[]:e.items.map(t=>String((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim()).filter(Boolean)}function dc(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(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 ms(e,t){return lc(e).join(" · ")}function or(e){return e.transport==="pty"}function ks(e){return e.transport==="acp"}function em(e,t){var r,n;return(r=t==null?void 0:t.providerLabels)!=null&&r[e]?t.providerLabels[e]:(n=t==null?void 0:t.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:ot(e)}function Eo(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=ot(r||"").trim().toLowerCase();return n===a||n===i||n===c}function tm(e){return wt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function sm(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=wt(n.status);if(!i){t.set(a,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),d=r.indexOf(c||"idle");d>=0&&(l<0||d<l)&&t.set(a,{...n,status:c})}return Array.from(t.values())}function rm(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 nm(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&&rm(t.receivedAt)||0}function am(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ha(e){return Math.max(am(e),nm(e.activeChat))}function om(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 Fa(e,t){return om(ha(e),ha(t),Ct(e,{fallbackId:e.id}),Ct(t,{fallbackId:t.id}),e.id,t.id)}const uc="adhdev_notification_prefs",$o={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function im(){try{const e=localStorage.getItem(uc);if(e){const t=JSON.parse(e);return{...$o,...t}}}catch{}return{...$o}}function cm(e){try{localStorage.setItem(uc,JSON.stringify(e))}catch{}}let Wt=im(),$r=[];function lm(){$r.forEach(e=>e())}function dm(e){Wt={...Wt,...e},cm(Wt),lm()}function um(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return $r.push(r),()=>{$r=$r.filter(n=>n!==r)}},[]);const t=o.useCallback(r=>{dm(r)},[]);return[{...Wt},t]}function Js(e){if(!Wt.globalEnabled)return!1;switch(e){case"disconnect":return Wt.disconnectAlert;case"completion":return Wt.completionAlert;case"approval":return Wt.approvalAlert;case"browser":return Wt.browserNotifications;default:return!0}}const mm={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function mc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function fc(){return"Notification"in window&&Notification.permission==="granted"}let Qt=null;function fm(e){return e!==!1}async function pm(){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 xa(e,t,r){if(fc())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 hm(e,t={}){const r={...mm,...t},n=o.useRef(new Map),a=o.useRef(0),[i,c]=o.useState(null);o.useEffect(()=>{let d=!1;return pm().then(m=>{d||c(m)}),()=>{d=!0}},[]);const l=o.useCallback((d,m,u)=>{const f=Date.now();f-a.current<r.throttleMs||(a.current=f,xa(d,m,u))},[r.throttleMs]);o.useEffect(()=>{var d;if(!(!r.enabled||!fc())&&Js("browser")&&!fm(i)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,wt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const u=n.current.get(m.id),f=wt(m.status,{activeModal:m.activeModal}),x=m.name||m.id;if(r.onApproval&&Js("approval")&&f==="waiting_approval"&&u!=="waiting_approval"){const N=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";l(`🔔 ${x} — Approval needed`,N.slice(0,120),`approval-${m.id}`)}r.onComplete&&Js("completion")&&ic(u)&&f==="idle"&&l(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&f==="error"&&u!=="error"&&l(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,f)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,i,l])}const xm=/^(run|approve|accept|yes|allow|always)/,bm=/^(run|approve|accept|yes|allow|always|proceed|save)/,gm=/^(reject|deny|delete|remove|abort|cancel|no)/;function Ha(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function ym(e){const t=Ha(e).toLowerCase();return xm.test(t)?"primary":gm.test(t)?"danger":"default"}function vm(e){return bm.test(Ha(e).toLowerCase())?"approve":"reject"}function wm(e){return e.map((t,r)=>({label:Ha(t),variant:ym(t),action:vm(t),button:t,buttonIndex:r}))}function jm(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function km(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 Sm{constructor(){Je(this,"dedupMap",new Map);Je(this,"DEDUP_WINDOW_MS",5e3);Je(this,"DEDUP_MAX_SIZE",50);Je(this,"DEDUP_CLEANUP_AGE_MS",1e4);Je(this,"toastCallbacks",[]);Je(this,"resolveActionFn",null);Je(this,"viewRequestRespondFn",null);Je(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 g;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 d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(d==null?void 0:d.type)||"";let u=ot(m);const f=this.resolveOwningDaemon(t);if(f){const h=Ct(f,{fallbackId:f.id});h&&(u=!m||m==="adhdev-daemon"?h:`${h}/${u}`)}let x="",N="info";if(t.event==="agent:generating_completed"){const h=t.duration?` (${t.duration}s)`:"";x=`✅ ${u} agent task completed${h}`,N="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(x=`⚡ ${u} approval needed`,N="warning",(g=t.modalButtons)!=null&&g.length&&this.resolveActionFn){const h=this.resolveActionRouteTarget(t);if(!h)return;const k=this.resolveActionFn,b=wm(t.modalButtons).map(S=>({label:S.label,variant:S.variant,onClick:()=>{k(h,"resolve_action",{action:S.action,button:S.button,buttonIndex:S.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),p=jm(u,t.modalMessage,x),y=Date.now();this.emitToast({id:y,message:p,type:N,timestamp:y,targetKey:n||h,actions:b,duration:15e3}),x=""}}else if(t.event==="monitor:long_generating"){const h=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";x=`⚠️ ${u} agent is taking a long time${h}`,N="warning",Js("browser")&&!document.hasFocus()&&xa(`⚠️ ${u} — Long Running`,`Agent has been generating for over ${h.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const h=t.requesterName||"A team member",k=t.requestId,b=t.orgId;if(x=`👁️ ${h} wants to view your session`,N="warning",k&&b&&this.viewRequestRespondFn){const p=Date.now(),y=km(b,k,this.viewRequestRespondFn,(S,j)=>console.error(`[EventManager] ${S} view request failed:`,j));this.emitToast({id:p,message:x,type:N,timestamp:p,actions:y,duration:3e4}),x=""}Js("browser")&&!document.hasFocus()&&xa("👁️ View Request",`${h} wants to view your session`,`view-request-${k}`)}else t.event==="team:view_request_approved"?(x="✅ View request approved",N="success"):t.event==="team:view_request_rejected"&&(x=`❌ ${t.targetName||"Team member"} declined your view request`,N="warning");if(x){const h=Date.now();this.emitToast({id:h,message:x,type:N,timestamp:h,targetKey:n||t.daemonId,duration:5e3})}}}const nt=new Sm,Bo=new Map;function Jr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ss(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function fn(e){return Jr(e)?Jr(e.result)?e.result:e:null}function Nm(e){const t=fn(e);return!t||!Jr(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Sr(e){const t=fn(e);return!t||!Jr(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Ws(e){const t=fn(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Nr(e){const t=fn(e);return!!t&&t.success===!1}function Cm(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";nt.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";nt.showToast(n.notification.body,a)}}}function Tm(e,t){return e&&Ss(e.currentValue)?e.currentValue:t}function Mm(e,t){return Ss(t)?Ss(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Am(e,t){var i,c;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(Ss(l))return l}const n=(i=t.controlValues)==null?void 0:i[e];if(Ss(n))return n;const a=(c=t.defaultValues)==null?void 0:c[e];return Ss(a)?a:void 0}function Br(e,t){return e.options||t[e.id]||[]}const Im={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 Rm(e,t,r){var n;return((n=Im[t])==null?void 0:n.has(r.id))===!0}function Ua(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Rm(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function Tn(e,t){return{value:t}}function Lm(e,t,r){var a;return r?((a=Br(e,t).find(i=>i.value===r))==null?void 0:a.label)||r:""}const _m={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Pm({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=xt(),d=`${e}:${t||n}`,m=_m[n]||"#94a3b8",[u,f]=o.useState({}),x=o.useRef({}),N=o.useRef(c);x.current=u,N.current=c;const g=o.useRef(0),h={};for(const I of i||[])I.defaultValue!==void 0&&(h[I.id]=I.defaultValue);const k={...h,...c||{},...Date.now()<g.current?u:{}};o.useEffect(()=>{c&&Date.now()>g.current&&f({})},[c]);const[b,p]=o.useState(Bo.get(d)||{}),[y,S]=o.useState(null),[j,A]=o.useState(null),M=o.useCallback(async(I,W={})=>{const P={...W,...t&&{targetSessionId:t}};return await l(e,I,P)},[e,t,l]),w=o.useCallback(async(I,W={})=>{const P=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await M("invoke_provider_script",{...P,scriptName:I,...W})},[M,n,r,t]),v=o.useCallback((I,W,P)=>{const $=Tm(P,W);f(H=>({...H,[I.id]:$})),Cm(P==null?void 0:P.effects)},[]),B=o.useCallback((I,W)=>{f(P=>{const $={...P};return W===void 0?delete $[I.id]:$[I.id]=W,$}),g.current=0},[]);if(!i||i.length===0)return null;const _=Ua(i,{hostIdeType:r,providerType:n});if(_.length===0)return null;const T=async I=>{if(y===I.id){S(null);return}if(Br(I,b).length>0){S(I.id);return}if(I.dynamic&&I.listScript){A(I.id);try{const P=await w(I.listScript,{}),$=Nm(P);if(!$){const xe=Ws(P);xe&&nt.showToast(xe,"warning");return}const H=$.options;p(xe=>{const ie={...xe,[I.id]:H};return Bo.set(d,ie),ie});const Q=Am(I.id,{localOverrideUntil:g.current,localValues:x.current,controlValues:N.current,defaultValues:h});if(Mm(Q,$.currentValue)){const xe=$.currentValue;f(ie=>({...ie,[I.id]:xe}))}S(I.id)}catch(P){const $=P instanceof Error?P.message:`Could not load ${I.label}`;nt.showToast($,"warning")}finally{A(null)}}},D=async(I,W)=>{S(null);const P=(c==null?void 0:c[I.id])??h[I.id];f($=>({...$,[I.id]:W})),g.current=Date.now()+5e3;try{if(!I.setScript)return;const $=await w(I.setScript,Tn(I,W)),H=Sr($);if(H&&!H.ok||Nr($))throw new Error((H==null?void 0:H.error)||Ws($)||`Could not update ${I.label}`);v(I,W,H)}catch($){B(I,P);const H=$ instanceof Error?$.message:`Could not update ${I.label}`;nt.showToast(H,"warning")}},K=async I=>{const W=Br(I,b).map(ie=>ie.value);if(W.length===0)return;const P=String(k[I.id]||""),H=(W.indexOf(P)+1)%W.length,Q=W[H];if(typeof Q!="string")return;const xe=(c==null?void 0:c[I.id])??h[I.id];f(ie=>({...ie,[I.id]:Q})),g.current=Date.now()+5e3;try{if(!I.setScript)return;const ie=await w(I.setScript,Tn(I,Q)),se=Sr(ie);if(se&&!se.ok||Nr(ie))throw new Error((se==null?void 0:se.error)||Ws(ie)||`Could not update ${I.label}`);v(I,Q,se)}catch(ie){B(I,xe);const se=ie instanceof Error?ie.message:`Could not update ${I.label}`;nt.showToast(se,"warning")}},L=async I=>{const P=!k[I.id],$=(c==null?void 0:c[I.id])??h[I.id];f(H=>({...H,[I.id]:P})),g.current=Date.now()+5e3;try{if(!I.setScript)return;const H=await w(I.setScript,Tn(I,P)),Q=Sr(H);if(Q&&!Q.ok||Nr(H))throw new Error((Q==null?void 0:Q.error)||Ws(H)||`Could not update ${I.label}`);v(I,P,Q)}catch(H){B(I,$);const Q=H instanceof Error?H.message:`Could not update ${I.label}`;nt.showToast(Q,"warning")}},C=async I=>{if(!I.invokeScript)return;if(I.confirmMessage){const P=[I.confirmTitle,I.confirmMessage,I.confirmLabel].filter(H=>typeof H=="string"&&H.trim().length>0);if(!window.confirm(P.join(`
|
|
28
|
-
|
|
29
|
-
`)))return}const W=(c==null?void 0:c[I.id])??h[I.id];try{const P=await w(I.invokeScript),$=Sr(P);if($&&!$.ok||Nr(P))throw new Error(($==null?void 0:$.error)||Ws(P)||`Could not run ${I.label}`);$&&v(I,W??!0,$)}catch(P){B(I,W);const $=P instanceof Error?P.message:`Could not run ${I.label}`;nt.showToast($,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${m}33`,background:`${m}12`,color:m},children:a}),_.map(I=>{const W=String(k[I.id]||""),P=Lm(I,b,W),$=y===I.id,H=j===I.id,Q=Br(I,b),xe="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(I.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${xe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:$?`${m}55`:"var(--border-default)",background:$?`${m}10`:"var(--surface-tertiary)",color:W?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void T(I),title:I.label,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:H?"Loading…":P||I.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),$&&Q.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>S(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:I.label}),Q.map(ie=>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:ie.value===W?`${m}14`:"transparent",color:ie.value===W?"var(--text-primary)":"var(--text-secondary)",borderLeft:ie.value===W?`2px solid ${m}`:"2px solid transparent"},title:ie.description||ie.label,onMouseEnter:se=>{se.currentTarget.style.background=`${m}10`},onMouseLeave:se=>{se.currentTarget.style.background=ie.value===W?`${m}14`:"transparent"},onClick:()=>void D(I,ie.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ie.label}),ie.value===W&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},ie.value))]})]})]},I.id);case"cycle":return s.jsxs("button",{type:"button",className:`${xe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:W?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void K(I),title:`Click to cycle: ${Q.map(ie=>ie.label).join(" → ")}`,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:P||I.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},I.id);case"toggle":return s.jsxs("button",{type:"button",className:`${xe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:W?`${m}44`:"var(--border-default)",background:W?`${m}14`:"var(--surface-tertiary)",color:W?m:"var(--text-muted)"},onClick:()=>void L(I),"aria-pressed":!!W,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),I.label]},I.id);case"action":return s.jsxs("button",{type:"button",className:`${xe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void C(I),children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:I.resultDisplay==="inline"&&W?`${I.label}: ${W}`:I.label})]},I.id);case"display":return s.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:W?"var(--text-primary)":"var(--text-muted)"},children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:W?`${I.label}: ${W}`:I.label})]},I.id);default:return null}})]})})}function Dm({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:d}){const{isVisible:m}=Oa(),u=Ua(l,{hostIdeType:a,providerType:i});return!e||t||u.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(Pm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:u,controlValues:d})})}function Em({hasDraft:e,isBusy:t=!1}){return!e||t}const pc=o.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:d=!1,animateVisibility:m=!0,onControlsToggle:u}){const f=o.useRef(null),[x,N]=o.useState(""),g=o.useRef(!1),{isVisible:h,toggleVisibility:k}=Oa();o.useEffect(()=>{N("")},[t]),o.useEffect(()=>{var p;l&&((p=f.current)==null||p.focus({preventScroll:!0}))},[t,l]);const b=async()=>{const p=x.trim();if(!(!p||a)&&!g.current){g.current=!0;try{await c(p)!==!1&&N("")}finally{g.current=!1}}};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:[d&&s.jsx("button",{type:"button",onClick:()=>{k(),u==null||u()},"aria-label":h?"Hide controls":"Show controls","aria-pressed":h,title:h?"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:f,type:"text",placeholder:i||`Send message to ${r}...`,value:x,onChange:p=>N(p.target.value),onPaste:p=>{const y=p.clipboardData.getData("text");y&&N(S=>S+y),p.preventDefault()},onKeyDown:p=>{if(p.key==="Enter"){if(p.nativeEvent.isComposing){p.preventDefault();return}p.preventDefault(),b()}},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:()=>{b()},disabled:Em({hasDraft:!!x.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${x.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:x.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:x.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})]})}),et=e=>e.transport==="pty",$s=(e,t)=>et(e)?e.mode||"terminal":"chat",hc=(e,t)=>et(e)&&$s(e)==="terminal",Qe=e=>e.transport==="acp",$m=180;function Yt(e){return e.streamSource!=="agent-stream"}function xs(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function xc(e){return e.machineName||""}function dr(e){return xs(e)}function Bt(e){return e.agentType||""}function Qr(e){return e.hostIdeType||""}function za(e){return e.displayPrimary||e.agentName||"Agent"}function bc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Bm(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function gc(e){const t=Bm(e),r=Ts(t==null?void 0:t.content),n=Ts(e.lastMessagePreview);return r||n||""}function Km(e,t=$m){const r=Ts(e);if(!r||t<=0)return"";const n=Array.from(r);return n.length<=t?r:`${n.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function Wm(e){return Km(gc(e)||e.displaySecondary||"")}function yc(e){return[e.displaySecondary,xc(e)].filter(Boolean)}function As(e){return e.agentName||ot(Bt(e))}function Om(e){var t,r;if(!Yt(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return ot(Qr(e)||Bt(e))}function vc(e){return Yt(e)?e.sessionId:e.nativeSessionId}function Ko(e){return Yt(e)?"native":e.tabKey}function Fm(e){return e.sessionId}function Hm(e,t){if(t)return Yt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function Um(e,t){const r=Bt(e),n=Yt(e),a=et(e)||Qe(e),i=n?a?As(e)||(t==null?void 0:t.cliName)||ot(Qr(e)||r):t!=null&&t.type?ot(t.type):ot(Qr(e)||r):As(e);return{isNativeConversation:n,isCli:et(e),isAcp:Qe(e),isCliTerminal:hc(e),providerType:r,displayLabel:i,targetEntry:Hm(e,t)}}function ss(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:et(e)||Qe(e)?{agentType:Bt(e)}:e.streamSource==="agent-stream"?{agentType:Bt(e)}:t}function Is(e){return e?dr(e):""}function Os(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Va(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function zm(e){const t=e instanceof Error?e.message:String(e||""),r=t.toLowerCase();return r.includes("still processing the previous prompt")?"Wait for the current reply to finish before sending another message.":r.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":r.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":r.includes("not running")?"Runtime is not available right now.":t||"Unable to send message right now."}function wc(){return"select_session"}function Vm(){return"open_panel"}function Gm({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function qm(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Wo(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Zr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ga(e){return e instanceof Error?e.message:String(e||"")}function Oo(e){const t=Ga(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Fo(e,t){const r=Ga(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function pn({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[d,m]=o.useState(null),u=o.useRef(!1),f=o.useRef(null);o.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const x=o.useCallback(async k=>{if(!t||u.current)return!1;const b=k.trim(),p=Va(t);if(Gm({hasMessage:!!b,blockedMessage:p,sendInFlight:u.current}))return p&&m(p),!1;const y=Date.now(),S={tabKey:t.tabKey,message:b,timestamp:y};if(qm(f.current,S))return m(null),!0;u.current=!0,l(!0),m(null),f.current=S;try{const j=Is(t);if(!j)return f.current=Wo(f.current,S),m("Unable to send message right now."),!1;const A=await e(j,"send_chat",{message:b,...ss(t)}),M=Zr(A);if(M!=null&&M.deduplicated)return m(null),!0;if((M==null?void 0:M.sent)===!1)throw new Error((M==null?void 0:M.error)||"Send failed");if((M==null?void 0:M.success)===!1)throw new Error((M==null?void 0:M.error)||"Send failed");return m(null),!0}catch(j){const A=Ga(j);return A.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",A):console.warn("Send blocked/failed",j),f.current=Wo(f.current,S),m(zm(j)),!1}finally{u.current=!1,l(!1)}},[t,e]),N=o.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(k){console.error("Relaunch failed",k)}},[t,e]),g=o.useCallback(async k=>{if(t)try{const p=(t.modalButtons||[]).indexOf(k),y=k.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(y),j=Is(t);if(!j)return;const A=await e(j,"resolve_action",{button:k,action:S?"approve":"reject",...p>=0&&{buttonIndex:p},...ss(t)}),M=Zr(A);M.success||r(w=>[...w,{routeId:t.tabKey,text:Fo(k,M==null?void 0:M.error),timestamp:Date.now()}])}catch(b){Oo(b)||console.error("[ModalButton] Error:",b),r(p=>[...p,{routeId:t.tabKey,text:Oo(b)?Fo(k,b):`❌ **${k}** error`,timestamp:Date.now()}])}},[t,e,r]),h=o.useCallback(async()=>{if(!(!t||a)){i(!0);try{await e(t.routeId,Vm(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(k){console.error("Focus agent failed",k)}finally{i(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:x,handleRelaunch:N,handleModalButton:g,handleFocusAgent:h}}const Ym=10,Xm=8e3,Jm=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function Qm(e){return e.replace(/(Authorization\s*:\s*Bearer\s+)[^\s'"`]+/gi,"$1[REDACTED:bearer]").replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]{12,}=*/gi,"$1[REDACTED:bearer]").replace(/\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]{20,}\b/g,"[REDACTED:github-token]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:api-key]").replace(/\b(?:adk|adm)_[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:adhdev-token]").replace(/((?:api[_-]?key|token|secret|password|passwd|client[_-]?secret)\s*[:=]\s*)[^\s,'"`}&]+/gi,"$1[REDACTED:secret]").replace(/([?&](?:api[_-]?key|token|secret|password|client_secret)=)[^&#\s]+/gi,"$1[REDACTED:secret]")}function ba(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(Jm.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=Qm(e);return n.length>8e3?`${n.slice(0,8e3)}…[truncated ${n.length-8e3} chars]`:n}if(typeof e!="object")return String(e);if(r>=6)return"[MaxDepth]";if(Array.isArray(e)){const n=e.slice(-20).map(a=>ba(a,t,r+1));return e.length>20?[{truncatedBefore:e.length-20},...n]:n}return Object.fromEntries(Object.entries(e).slice(0,80).map(([n,a])=>[n,ba(a,n,r+1)]))}function Cr(e,t){return Array.isArray(e)?e.slice(-t):[]}function Zm(e,t=Date.now()){const r=e&&t-e.firstAt<=Xm,n=r?e.count+1:1;return n>=Ym?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function jc(e){var n;const{activeConv:t}=e,r={version:1,createdAt:new Date(e.now??Date.now()).toISOString(),url:e.locationHref??(typeof window<"u"?window.location.href:void 0),activeConversation:{routeId:t.routeId,tabKey:t.tabKey,sessionId:t.sessionId,providerSessionId:t.providerSessionId,transport:t.transport,agentName:t.agentName,agentType:t.agentType,hostIdeType:t.hostIdeType,status:t.status,connectionState:t.connectionState,title:t.title,workspaceName:t.workspaceName,displayPrimary:t.displayPrimary,displaySecondary:t.displaySecondary,streamSource:t.streamSource,lastMessageHash:t.lastMessageHash},messageCounts:{live:t.messages.length,visible:e.visibleMessages.length,history:((n=e.chatTailState.historyMessages)==null?void 0:n.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:Cr(t.messages,10),visibleMessagesTail:Cr(e.visibleMessages,5),historyMessagesTail:Cr(e.chatTailState.historyMessages,5),actionLogsTail:Cr(e.actionLogs.filter(a=>a.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{hasMoreHistory:!!e.chatTailState.hasMoreHistory,historyError:e.chatTailState.historyError||null},ui:e.ui,browser:typeof navigator<"u"?{userAgent:navigator.userAgent,language:navigator.language,online:navigator.onLine}:null};return ba(r)}function kc(e,t={}){const r=e&&typeof e=="object"?e:{},n=t.locatorCopyStatus??(t.locatorCopied===!1?"failed":"copied"),a=n==="copied"?"locator copied":n==="manual"?"locator shown for manual copy":"locator copy failed";return r.delivery==="daemon_file"?`Chat debug signal sent${typeof r.bundleId=="string"&&r.bundleId.trim()?` (${r.bundleId})`:""}; saved on daemon, ${a}.`:`Chat debug signal sent; ${a}.`}async function Sc(e){var t;if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.writeText)&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(e),"copied"}catch(r){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",r)}if(typeof document<"u"&&document.body){let r=null;try{if(r=document.createElement("textarea"),r.value=e,r.setAttribute("readonly","true"),r.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(r),r.focus(),r.select(),document.execCommand("copy"))return"copied"}catch{}finally{r==null||r.remove()}}if(typeof window<"u"&&typeof window.prompt=="function")try{return window.prompt("Copy ADHDev chat debug locator:",e),"manual"}catch{}return"failed"}function Nc(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const r=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&r.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&r.push("","warnings:",...t.warnings.map(n=>`- ${String(n)}`)),r.join(`
|
|
30
|
-
`)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
|
|
31
|
-
|
|
32
|
-
\`\`\`json
|
|
33
|
-
${JSON.stringify(t.bundle,null,2)}
|
|
34
|
-
\`\`\``:`# ADHDev Chat Debug Bundle
|
|
35
|
-
|
|
36
|
-
\`\`\`json
|
|
37
|
-
${JSON.stringify(t,null,2)}
|
|
38
|
-
\`\`\``}function Mn(e,t){return`${e}:${t}`}function ef(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Fs(e,t){ef()&&console.debug(`[subscription-manager] ${e}`,t)}class tf{constructor(){Je(this,"active",new Map);Je(this,"retryTimers",new Map)}subscribe(t,r,n,a,i){var u;const c=Mn(n.topic,n.key),l=this.active.get(c);let d=!0;if(l)l.handlers.add(a),l.lastUpdate&&a(l.lastUpdate);else{const f={daemonId:r,request:n,handlers:new Set([a])};this.active.set(c,f),Fs("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(i!=null&&i.retryIntervalMs)&&this.scheduleRetry(c,t,i.retryIntervalMs)}const m=()=>{var N;this.clearRetry(c);const f=this.active.get(c);if(!f||(f.handlers.delete(a),f.handlers.size>0))return;this.active.delete(c);const x={type:"unsubscribe",topic:n.topic,key:n.key};Fs("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(N=t.sendData)==null||N.call(t,r,x)};return m.initialSendAccepted=d,m}publish(t){const r=Mn(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Cs.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),Cs.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=Mn(t,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(t){var r;Fs("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=t.sendData)==null||r.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,r){var a;const n=Array.from(this.active.values()).filter(i=>i.daemonId===t);Fs("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;Fs("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 Ht=new tf;function sf(e,t){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===t&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker,settings:n.settings});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 rf(e){const t=[],r=new Map;for(const n of e)if(n.parentId){const a=r.get(n.parentId)||[];a.push(n),r.set(n.parentId,a)}else t.push(n);return{topLevel:t,childrenByParent:r}}function en(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=t,l=c||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:m,childrenByParent:u}=rf(d),f=sf(i,n),x=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,N=m.filter(k=>k.kind==="workspace"&&k.transport==="cdp-page"),g=m.filter(k=>k.kind==="agent"&&k.transport==="pty"),h=m.filter(k=>k.kind==="agent"&&k.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...x&&{machine:x,platform:x.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:N.some(k=>!!k.cdpConnected)});for(const k of N){const b=f.get(k.id),p=qs(k,b),y=(u.get(k.id)||[]).map(S=>qs(S,f.get(S.id)));r.push({id:`${n}:ide:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(b==null?void 0:b.providerSessionId),parentSessionId:p.parentId,sessionKind:p.kind,transport:p.transport,sessionCapabilities:p.capabilities,type:p.providerType,status:p.cdpConnected?"online":"detected",daemonId:n,instanceId:k.id,workspace:p.workspace,terminals:0,childSessions:y,agents:y.map(S=>({id:S.id,name:S.providerName||S.providerType,type:S.providerType,status:S.status})),activeChat:p.activeChat,chats:[],cdpConnected:p.cdpConnected,...p.lastMessagePreview!==void 0&&{lastMessagePreview:p.lastMessagePreview},...p.lastMessageRole!==void 0&&{lastMessageRole:p.lastMessageRole},...p.lastMessageAt!==void 0&&{lastMessageAt:p.lastMessageAt},...p.lastMessageHash!==void 0&&{lastMessageHash:p.lastMessageHash},lastUpdated:p.lastUpdated,unread:p.unread,lastSeenAt:p.lastSeenAt,inboxBucket:p.inboxBucket,completionMarker:p.completionMarker,seenCompletionMarker:p.seenCompletionMarker,surfaceHidden:p.surfaceHidden,...p.controlValues!==void 0&&{controlValues:p.controlValues},...p.providerControls!==void 0&&{providerControls:p.providerControls},...p.summaryMetadata!==void 0&&{summaryMetadata:p.summaryMetadata},...p.settings!==void 0&&{settings:p.settings},timestamp:l})}for(const k of g){const b=f.get(k.id),p=qs(k,b);r.push({id:`${n}:cli:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(b==null?void 0:b.providerSessionId),parentSessionId:p.parentId,sessionKind:p.kind,transport:p.transport,sessionCapabilities:p.capabilities,type:p.providerType,agentType:p.providerType,status:p.status||"running",daemonId:n,instanceId:k.id,cliName:p.providerName||p.providerType,mode:p.mode||(b==null?void 0:b.mode)||"terminal",workspace:p.workspace||"",activeChat:p.activeChat,...p.resume!==void 0&&{resume:p.resume},...p.runtimeKey!==void 0&&{runtimeKey:p.runtimeKey},...p.runtimeDisplayName!==void 0&&{runtimeDisplayName:p.runtimeDisplayName},...p.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:p.runtimeWorkspaceLabel},...p.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:p.runtimeWriteOwner},...p.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:p.runtimeAttachedClients},...p.lastMessagePreview!==void 0&&{lastMessagePreview:p.lastMessagePreview},...p.lastMessageRole!==void 0&&{lastMessageRole:p.lastMessageRole},...p.lastMessageAt!==void 0&&{lastMessageAt:p.lastMessageAt},...p.lastMessageHash!==void 0&&{lastMessageHash:p.lastMessageHash},lastUpdated:p.lastUpdated,unread:p.unread,lastSeenAt:p.lastSeenAt,inboxBucket:p.inboxBucket,completionMarker:p.completionMarker,seenCompletionMarker:p.seenCompletionMarker,surfaceHidden:p.surfaceHidden,...p.controlValues!==void 0&&{controlValues:p.controlValues},...p.providerControls!==void 0&&{providerControls:p.providerControls},...p.summaryMetadata!==void 0&&{summaryMetadata:p.summaryMetadata},...p.settings!==void 0&&{settings:p.settings},timestamp:l,_isCli:!0})}for(const k of h){const b=f.get(k.id),p=qs(k,b);r.push({id:`${n}:acp:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(b==null?void 0:b.providerSessionId),parentSessionId:p.parentId,sessionKind:p.kind,transport:p.transport,sessionCapabilities:p.capabilities,type:p.providerType,agentType:p.providerType,status:p.status||"running",daemonId:n,instanceId:k.id,cliName:p.providerName||p.providerType,mode:"chat",workspace:p.workspace||"",activeChat:p.activeChat,...p.runtimeKey!==void 0&&{runtimeKey:p.runtimeKey},...p.runtimeDisplayName!==void 0&&{runtimeDisplayName:p.runtimeDisplayName},...p.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:p.runtimeWorkspaceLabel},...p.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:p.runtimeWriteOwner},...p.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:p.runtimeAttachedClients},...p.lastMessagePreview!==void 0&&{lastMessagePreview:p.lastMessagePreview},...p.lastMessageRole!==void 0&&{lastMessageRole:p.lastMessageRole},...p.lastMessageAt!==void 0&&{lastMessageAt:p.lastMessageAt},...p.lastMessageHash!==void 0&&{lastMessageHash:p.lastMessageHash},lastUpdated:p.lastUpdated,unread:p.unread,lastSeenAt:p.lastSeenAt,inboxBucket:p.inboxBucket,completionMarker:p.completionMarker,seenCompletionMarker:p.seenCompletionMarker,surfaceHidden:p.surfaceHidden,...p.controlValues!==void 0&&{controlValues:p.controlValues},...p.providerControls!==void 0&&{providerControls:p.providerControls},...p.summaryMetadata!==void 0&&{summaryMetadata:p.summaryMetadata},...p.settings!==void 0&&{settings:p.settings},timestamp:l,_isAcp:!0})}return r}const nf=15e3,af=15e3,of=6e4,cf=1200,Ho=12,lf=8e3,df=4e3,An=new Map,In=new Map,Tr=new Set,Qs=new Map;function uf(e){if(!e||typeof e!="object")return null;const t=e,r=t.status;if(r&&typeof r=="object")return r;const n=t.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return t}function Uo(e,t){const r=Qs.get(e);!r||r.size===0||(Qs.delete(e),r.forEach(n=>n(t)))}function mf(e,t){return new Promise(r=>{const n=Qs.get(e)||new Set;Qs.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&Qs.delete(e),r(c)},i=setTimeout(()=>a(!1),t);n.add(a)})}function ur(){const{sendCommand:e,sendData:t}=xt(),{injectEntries:r,getIdes:n}=nr();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??of,l=In.get(a)||0;if(!(i!=null&&i.force)&&Tr.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const d=An.get(a);if(d)return d;const m=(async()=>{if(t&&!Tr.has(a)){const h=Ht.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},k=>{const b=n(),p=b.find(S=>S.id===a),y=en(k.status,{daemonId:a,existingDaemon:p,existingEntries:b,timestamp:k.timestamp});y.length>0&&r(y),In.set(a,Date.now()),Uo(a,!0)});if(h.initialSendAccepted?Tr.add(a):Tr.delete(a),!(i!=null&&i.force)&&h.initialSendAccepted&&await mf(a,cf))return}const u=await e(a,"get_status_metadata"),f=uf(u);if(!f)return;const x=n(),N=x.find(h=>h.id===a),g=en(f,{daemonId:a,existingDaemon:N,existingEntries:x,timestamp:f.timestamp||Date.now()});g.length>0&&r(g,{authoritativeDaemonIds:[a]}),In.set(a,Date.now()),Uo(a,!0)})().finally(()=>{An.delete(a)});return An.set(a,m),m},[n,r,e,t])}function ff(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const pf=60,hf=50;function Cc(e={}){return e.isCliLike?hf:pf}function xf(e={}){return Cc(e)}function kt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ft(e,t){const r=kt(t);return r?`${e}:${r}`:void 0}function qt(e,t,r){const n=Ft(t,r),a=kt(r);n&&e.push(n),a&&e.push(a)}function ws(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function Tc(e){return kt(e.providerSessionId)||kt(e.sessionId)||kt(e.tabKey)||kt(e.routeId)}function qa(e){return ws([kt(e.providerSessionId),kt(e.sessionId)])}function Ns(e){const t=[];return qt(t,"provider",e.providerSessionId),qt(t,"session",e.sessionId),qt(t,"tab",e.tabKey),qt(t,"route",e.routeId),ws(t)}function bf(e){const t=[];return kt(e.providerSessionId)?(qt(t,"provider",e.providerSessionId),ws(t)):kt(e.sessionId)?(qt(t,"session",e.sessionId),ws(t)):kt(e.tabKey)?(qt(t,"tab",e.tabKey),ws(t)):kt(e.routeId)?(qt(t,"route",e.routeId),ws(t)):[]}function Ya(e){return Ft("provider",e.providerSessionId)||Ft("session",e.sessionId)||Ft("tab",e.tabKey)||Ft("route",e.routeId)||"unknown:"}function mr(e){return qa(e)[0]}function gf(e){const t=kt(e.providerSessionId),r=kt(e.sessionId),n=kt(e.tabKey),a=kt(e.routeId),i=[Ft("provider",t),Ft("session",r),Ft("tab",n),Ft("route",a)].filter(d=>typeof d=="string"),c=Ns({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=Ya({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:Tc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:mr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function ga(e,t){const r=gf(e);return bf(t).some(n=>r.lookupKeys.includes(n))}const fr=60,yf=1e3,Xa=12e4,vf=new Set(["generating","waiting_approval","starting","streaming","working"]),zo=new Map;function Mc(e,t){return`${e}::${t}`}function ya(e=fr){return{liveMessages:[],cursor:wf([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function wf(e,t=fr){return{tailLimit:t}}function Vo(e,t){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}class jf{constructor(t){Je(this,"manager");Je(this,"sendData");Je(this,"daemonId");Je(this,"sessionId");Je(this,"historySessionId");Je(this,"subscriptionKey");Je(this,"snapshot");Je(this,"transportSubscription",null);Je(this,"listeners",new Set);Je(this,"retainCount",0);Je(this,"loadHistoryPromise",null);Je(this,"pendingDisconnectTimer",null);this.manager=t.manager||Ht,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=ya(Math.max(0,t.tailLimit??fr))}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);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}}getSnapshot(){return this.snapshot}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await t({offset:this.snapshot.historyOffset,excludeRecentCount:this.snapshot.liveMessages.length}),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}:{},...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:yf}))}disconnect(){var t;(t=this.transportSubscription)==null||t.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return;const r=Array.isArray(t.messages)?t.messages:[],n={tailLimit:this.snapshot.cursor.tailLimit};Vo(this.snapshot.liveMessages)===Vo(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,cursor:n},this.emit())}}function Ac(e){const t=Mc(e.daemonId,e.sessionId),r=zo.get(t);if(r)return r.updateOptions(e),r;const n=new jf(e);return zo.set(t,n),n}function kf(e,t){return{...e,loadHistoryPage:t}}function Sf(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Nf(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(vf.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=t.now??Date.now(),a=Math.max(0,Number(t.recentActivityMs??Xa)),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 Cf(e=Xa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Tf(e,t={}){const r=new Set,n=[];for(const a of e){if(!Nf(a,t))continue;const i=dr(a),c=a.sessionId||"";if(!i||!c)continue;const l=Mc(i,c);if(r.has(l))continue;r.add(l);const d=mr(a);n.push({daemonId:i,sessionId:c,historySessionId:d||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Sf),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Mf(e,t){const{sendData:r,sendCommand:n}=xt(),a=(t==null?void 0:t.enabled)!==!1,i=dr(e),c=e.sessionId||"",l=mr(e)||c,d=`daemon:${i}:session:${c}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??fr),u=o.useMemo(()=>!a||!i||!c?null:Ac({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:d,sendData:r,tailLimit:m}),[i,a,l,r,c,d,m]),[f,x]=o.useState(()=>(u==null?void 0:u.getSnapshot())||ya(m));o.useEffect(()=>{if(!u){x(ya(m));return}u.retain(),x(u.getSnapshot());const g=u.subscribe(h=>{x(h)});return()=>{g(),u.release()}},[u,m]);const N=o.useCallback(async()=>{!u||!i||!c||await u.loadHistoryPage(async({offset:g,excludeRecentCount:h})=>{const k=e.agentType,b=await n(i,"chat_history",{agentType:k,offset:g,limit:30,targetSessionId:c,historySessionId:l,excludeRecentCount:h}),p=b&&typeof b=="object"&&"result"in b?b.result||{}:b||{};return{messages:Array.isArray(p.messages)?p.messages:[],hasMore:p.hasMore===!0}})},[e.agentType,u,i,l,n,c]);return o.useMemo(()=>kf(f,N),[N,f])}function Af(e,t){const{sendData:r}=xt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??fr),i=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Xa)),c=Cf(i),[l,d]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(f=>f+1)},c);return()=>{clearInterval(u)}},[e.length,n,c]);const m=o.useMemo(()=>Tf(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(f=>Ac({...f,sendData:r,tailLimit:a}));return u.forEach(f=>{f.retain()}),()=>{u.forEach(f=>f.release())}},[m.signature,n,r,a])}function If(e,t){return t?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Go(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const r=String(e.kind||"standard").toLowerCase();return r===""||r==="standard"}function Rf(e,t){if(e.length===0)return[];if(t.some(Go))return[];const r=[],n=new Set;for(let a=e.length-1;a>=0&&r.length<2;a-=1){const i=e[a];if(!i||!Go(i))continue;const c=String(i.role||"").toLowerCase();n.has(c)||(n.add(c),r.unshift(i))}return r}function Lf(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),i=a>0?r.slice(0,a):[],c=a>0?r.slice(-n):r,l=Rf(i,c),d=l.length>0?[...l,...c]:c;return t.length===0?d:[...t,...d]}function _f(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Pf(e){return _f(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function Df(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Ef(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function $f(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Ic(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Rc(e){const t=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return t||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function Bf(e){return Ic(e)?!1:e.inboxBucket==="task_complete"&&Rc(e).length>0}function qo(e){return e.branch||"detached HEAD"}function Kf(e){if(e.error)return`${qo(e)} · Git error: ${e.error}`;const t=[qo(e)];return e.changedFiles>0?t.push(Df(e.changedFiles,"file")+" changed"):e.dirty||t.push("clean"),e.ahead>0&&t.push(`ahead ${e.ahead}`),e.behind>0&&t.push(`behind ${e.behind}`),e.hasConflicts&&t.push("conflicts"),t.join(" · ")}function Wf(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Kf(t)}`}function Of(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function Ff(e,t={}){if(t.enabled===!1)return[];if(!$f(e))return[];const r=Ic(e)?"working":Bf(e)?"complete":null;if(!r)return[];const n=r==="complete"?Rc(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Ef(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:Wf(r,e.git),timestamp:Of(e,e.git),meta:{source:"git-system-bubble",phase:r,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const Hf=60;function va({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:d,scrollToBottomRequestNonce:m,isInputActive:u=!0,isVisible:f=!0}){var ce,ye,ae,de,je,fe,pe;const x=o.useRef(new Map),N=o.useRef(void 0),g=ur(),{sendCommand:h}=xt(),{isVisible:k}=Oa();lr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const b=Nt.useMemo(()=>Es(e),[e.status,e.connectionState]),p=o.useMemo(()=>Um(e,t),[e,t]),y=o.useMemo(()=>{var te;return Ua((te=p.targetEntry)==null?void 0:te.providerControls,{hostIdeType:e.hostIdeType,providerType:p.providerType})},[e.hostIdeType,p.providerType,(ce=p.targetEntry)==null?void 0:ce.providerControls]),S=Cc({isCliLike:p.isCli||p.isAcp}),j=xf({isCliLike:p.isCli||p.isAcp}),A=Mf(e,{enabled:f&&!!e.sessionId,tailLimit:j}),[M,w]=o.useState(S),v=e.tabKey,B=A.historyMessages,_=A.hasMoreHistory,T=A.historyError,D=If(e,A);o.useEffect(()=>{w(S)},[S,v]);const K=Math.max(0,D.length-M),L=za(e),C=dr(e),I=Pf(e),W=Va(e),P=a||W,$=!!W,[H,Q]=o.useState(!1);o.useEffect(()=>{const te=p.targetEntry;C&&(!te||te.providerControls===void 0||te.controlValues===void 0)&&g(C,{minFreshMs:3e4}).catch(()=>{})},[C,p.isAcp,(ye=p.targetEntry)==null?void 0:ye.providerControls,(ae=p.targetEntry)==null?void 0:ae.controlValues,g]);const xe=o.useCallback(async()=>{if(!H){if(D.length>M){w(te=>Math.min(D.length,te+Hf));return}Q(!0);try{await A.loadHistoryPage()}finally{Q(!1)}}},[A,H,D.length,M]),{allMessages:ie,receivedAtMap:se}=o.useMemo(()=>{const te=Lf({historyMessages:B,liveMessages:D,visibleLiveCount:M}),me=Ff(e),oe=me.length>0?[...te,...me]:te,Y={};return oe.forEach((V,le)=>{const ke=`${e.tabKey}:${Yr(V,le)}`;let ee=ff(V)||x.current.get(ke)||0;ee||(ee=Date.now(),x.current.set(ke,ee)),Y[Yr(V,le)]=ee}),{allMessages:oe,receivedAtMap:Y}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,K,B,D,M]),be=o.useMemo(()=>l.filter(te=>te.routeId===e.tabKey).sort((te,me)=>te.timestamp-me.timestamp),[l,e.tabKey]),we=o.useCallback(async()=>{var le,ke;if(!C)return;const te=jc({activeConv:e,visibleMessages:ie,actionLogs:l,controls:(le=p.targetEntry)==null?void 0:le.providerControls,controlValues:(ke=p.targetEntry)==null?void 0:ke.controlValues,visibleBarControlCount:y.length,chatTailState:{hasMoreHistory:_,historyError:T,historyMessages:B},ui:{controlsVisible:k,visibleLiveCount:M,hiddenLiveCount:K,isInputActive:u,isVisible:f}}),me=await h(C,"get_chat_debug_bundle",{agentType:p.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:te}),oe=Zr(me),Y=Nc(oe),V=await Sc(Y);V==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),nt.showToast(kc(oe,{locatorCopyStatus:V}),V==="failed"?"warning":"success")},[e,l,ie,k,p.providerType,(de=p.targetEntry)==null?void 0:de.controlValues,(je=p.targetEntry)==null?void 0:je.providerControls,C,_,K,B,u,f,T,h,y.length,M]),ge=o.useCallback(()=>{const te=Zm(N.current);N.current=te.state,te.shouldCollect&&we().catch(me=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",me),nt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[we]),J=o.useMemo(()=>{if(D.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((b.isGenerating||e.status==="streaming")&&Q(!1),e.status==="not_monitored"&&I)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(Ms,{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(us,{size:14})," Open ",L," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&I)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(Xi,{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(us,{size:14})," Open ",L," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!H)return!_&&B.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"No messages yet"})]}):s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,I,i,_,B.length,c,H,D.length,L,b.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[s.jsx(_u,{messages:ie,actionLogs:be,agentName:As(e)||L||"Agent",userName:d,isCliMode:p.isCli||p.isAcp,isWorking:b.isGenerating,contextKey:e.tabKey,receivedAtMap:se,lastMessageHash:e.lastMessageHash,onLoadMore:xe,isLoadingMore:H,hasMoreHistory:_,hiddenLiveCount:K,loadError:T??void 0,emptyState:J,scrollToBottomRequestNonce:m,isVisible:f}),s.jsx(Dm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:p.providerType,displayLabel:p.displayLabel,controls:(fe=p.targetEntry)==null?void 0:fe.providerControls,controlValues:(pe=p.targetEntry)==null?void 0:pe.controlValues,isActive:u,isCliTerminal:p.isCliTerminal}),!p.isCliTerminal&&s.jsx(pc,{contextKey:e.tabKey,panelLabel:L,isSending:n,isBusy:$,statusMessage:P,onSend:r,isActive:u,showControlsToggle:y.length>0,onControlsToggle:ge})]})}let Lc=Jt;function _c(){return Lc()}class Uf{constructor(){Je(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 Pc=new Uf;class zf{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 dt=new zf;function Vf(e){e.dashboardWS&&(Pc=e.dashboardWS),e.connectionManager&&(dt=e.connectionManager),e.useDaemonsHook&&(Lc=e.useDaemonsHook)}const Gf=.5,qf=1.25;function ct(e){return za(e)}function fs(e){return yc(e).join(" · ")}function Dc(e){const t=gc(e);return t||(e.title?e.title:fs(e)||"No messages yet")}function Ec(e,t){const{isReconnecting:r,isConnecting:n}=Es(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function Yf(e,t){const r=["Chat",...yc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function rs(e){return Ec(e)||fs(e)}function Xf(e){return`${ct(e)} · ${Dc(e)}`}function Jf(e){const t=Qr(e),r=t?ot(t):As(e);return`${ct(e)} — ${r||"Agent"}`}function Qf(e){return As(e)||"CLI"}function $c(e){return bc(e)}function Bc(e){return e?`Remote · ${ct(e)||e.workspaceName||"Session"}`:"Remote"}function Zf({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var re;Jt();const{sendPtyInput:d}=xt(),[m,u]=o.useState(!1),f=o.useRef(!1);f.current=m;const[x,N]=o.useState("Runtime terminal unavailable"),[g,h]=o.useState(!1),[k,b]=o.useState(null),[p,y]=o.useState(!1),[S,j]=o.useState(!1),[A,M]=o.useState(1),[w,v]=o.useState(!1),[B,_]=o.useState({width:0,height:0}),[T,D]=o.useState({width:0,height:0}),[K,L]=o.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[C,I]=o.useState(null),W=o.useRef(null),P=o.useRef(null),$=o.useRef(!1),H=o.useRef(!1),Q=o.useRef(c),xe=o.useRef(0),ie=o.useRef(!1),se=o.useRef(""),be=o.useRef(null),we=o.useRef(!1),ge=o.useRef(!1),J=o.useRef(null),ce=o.useRef(null),ye=o.useRef(null),ae=32*1024,de=()=>{var E,X,Z,ne;return((X=(E=W.current)==null?void 0:E.ownerDocument)==null?void 0:X.defaultView)||((ne=(Z=P.current)==null?void 0:Z.ownerDocument)==null?void 0:ne.defaultView)||window},je=E=>{const X=de();return{ownerWindow:X,frameId:X.requestAnimationFrame(E)}},fe=()=>{const E=J.current;if(E){try{E.ownerWindow.cancelAnimationFrame(E.frameId)}catch{}J.current=null}},pe=()=>{const E=ce.current;if(E){try{E.ownerWindow.clearTimeout(E.timeoutId)}catch{}ce.current=null}},te=()=>{const E=ye.current;if(E){try{E.ownerWindow.clearTimeout(E.timeoutId)}catch{}ye.current=null}},me=()=>{c&&J.current===null&&(J.current=je(()=>{tt()}))},oe=e.tabKey,Y=e.sessionId||"",V=e.daemonId||((re=e.routeId)==null?void 0:re.split(":")[0])||e.routeId||"",le=Va(e),ke=m?i||le:x,ee=Gf,Pe=qf,$e=.05,Oe=()=>{const E=T.width,X=T.height;if(!Number.isFinite(B.width)||B.width<=0||!Number.isFinite(B.height)||B.height<=0||!Number.isFinite(E)||E<=0||!Number.isFinite(X)||X<=0)return 1;const Z=B.width/E,ne=B.height/X;return Number(Math.min(Pe,Math.max(ee,Math.min(Z,ne))).toFixed(2))},He=Oe(),O=$.current&&A>He,Ce=Number.isFinite(T.width)&&T.width>0?Math.max(B.width,Math.round(T.width*A)):B.width,Te=Number.isFinite(T.height)&&T.height>0?Math.max(B.height,Math.round(T.height*A)):B.height,Re=()=>{je(()=>{const E=P.current;E&&(E.scrollLeft=0,E.scrollTop=E.scrollHeight-E.clientHeight)})},Be=()=>{var E,X;xe.current=0,ie.current=!1,se.current="",be.current=null,we.current=!1,ge.current=!1,$.current||(H.current=!1,M(1)),J.current!==null&&fe(),u(!1),N("Runtime terminal unavailable"),te(),pe(),b(null),I(null),v(!1),h(!1),y(!1),j(!1),(X=(E=r.current)==null?void 0:E.reset)==null||X.call(E)},Fe=()=>{var E,X;xe.current=0,ie.current=!1,se.current="",be.current=null,we.current=!1,ge.current=!1,J.current!==null&&fe(),u(!0),N(""),te(),pe(),b(null),I(null),v(!1),h(!1),y(!1),j(!1),(X=(E=r.current)==null?void 0:E.reset)==null||X.call(E)},Ye=()=>{ge.current&&(ge.current=!1,je(()=>{var E,X;(X=(E=r.current)==null?void 0:E.scrollToTop)==null||X.call(E)}))},tt=()=>{if(J.current=null,!c)return;const E=se.current;if(!E)return;const X=E.slice(0,ae);se.current=E.slice(X.length);const Z=r.current;if(!Z){se.current=X+se.current,me();return}Z.write(X,()=>{if(se.current.length>0){me();return}Ye()})},ut=E=>{E&&(se.current+=E,me())},ft=(E,X=0,Z,ne,ve={})=>{var Le,Se,_e,Ee;const Ae=!!ve.force;!Ae&&X>0&&xe.current>=X||!Ae&&X===0&&ie.current||(xe.current=X,X>0&&y(!0),u(!0),N(""),typeof Z=="number"&&typeof ne=="number"&&Z>0&&ne>0&&((Se=(Le=r.current)==null?void 0:Le.resize)==null||Se.call(Le,Z,ne)),se.current="",(Ee=(_e=r.current)==null?void 0:_e.reset)==null||Ee.call(_e),E?ut(E):Ye())};o.useEffect(()=>{Be()},[Y]),o.useEffect(()=>{var X;if(!Y)return;const E=((X=dt.onRuntimeEvent)==null?void 0:X.call(dt,Y,Z=>{if(!(!Z||Z.sessionId!==Y)){if(Z.type==="runtime_snapshot"){if(!c){be.current={text:Z.text||"",seq:Z.seq||0,cols:Z.cols,rows:Z.rows,force:!!Z.force};return}ft(Z.text||"",Z.seq||0,Z.cols,Z.rows,{force:!!Z.force});return}if(Z.type==="session_output"){ie.current=!0,typeof Z.seq=="number"&&(xe.current=Math.max(xe.current,Z.seq),Z.seq>0&&y(!0)),f.current||u(!0),f.current||N(""),typeof Z.data=="string"&&ut(Z.data);return}if(Z.type==="session_cleared"){if(!c){we.current=!0,se.current="",be.current=null;return}Fe();return}if(Z.type==="session_io_error"){const ne=typeof Z.error=="string"&&Z.error?Z.error:typeof Z.reason=="string"&&Z.reason?Z.reason:"unknown error";u(!1),N(`Runtime input failed: ${ne}`);return}}},V))||(()=>{});return()=>{E()}},[V,Y,r,c]);const pt=async(E={})=>{var X;if(!V||!Y)return{success:!1,error:"daemonId and sessionId are required"};E.preserveStatus||N(E.loadingMessage||"Loading runtime terminal...");try{const Z=await((X=dt.requestRuntimeSnapshot)==null?void 0:X.call(dt,V,Y,{sinceSeq:E.sinceSeq,force:E.force}));return Z&&Z.success===!1?(E.preserveStatus||(u(!1),N(`Runtime terminal unavailable: ${Z.error}`)),Z):Z||{success:!0}}catch(Z){const ne=(Z==null?void 0:Z.message)||String(Z);return E.preserveStatus||(u(!1),N(`Runtime terminal unavailable: ${ne}`)),{success:!1,error:ne}}},Ne=async E=>{var Ae,Le;const X=((Ae=W.current)==null?void 0:Ae.ownerDocument)||document,Z=X.defaultView||window,ne=(Le=Z.navigator)==null?void 0:Le.clipboard;if(ne!=null&&ne.writeText&&Z.isSecureContext)try{return await ne.writeText(E),!0}catch{}let ve=null;try{return ve=X.createElement("textarea"),ve.value=E,ve.setAttribute("readonly","true"),ve.style.position="fixed",ve.style.left="-9999px",ve.style.top="0",X.body.appendChild(ve),ve.focus(),ve.select(),X.execCommand("copy")}catch{return!1}finally{ve==null||ve.remove()}},Ue=E=>{pe(),I(E);const X=de();ce.current={ownerWindow:X,timeoutId:X.setTimeout(()=>{ce.current=null,I(Z=>Z===E?null:Z)},2200)}},Xe=E=>{te(),b(E);const X=de();ye.current={ownerWindow:X,timeoutId:X.setTimeout(()=>{ye.current=null,b(Z=>Z===E?null:Z)},2200)}},Ve=async()=>{var ve,Ae,Le,Se;const E=((Ae=(ve=r.current)==null?void 0:ve.getSelection)==null?void 0:Ae.call(ve))||"",X=((Se=(Le=r.current)==null?void 0:Le.getVisibleText)==null?void 0:Se.call(Le))||"",Z=E.trimEnd()||X.trimEnd();if(!Z){Ue("Nothing to copy");return}if(!await Ne(Z)){Ue("Copy failed");return}Ue(E.trimEnd()?"Copied selection":"Copied visible terminal")},st=E=>{if(!m||!c)return;((d==null?void 0:d(V,Y,E))??!1)||Ue("Terminal input failed")},F=async()=>{if(g)return;h(!0),b("Loading older terminal output..."),ge.current=!0;const E=await pt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(h(!1),(E==null?void 0:E.success)===!1){ge.current=!1,b(`Older terminal output unavailable: ${E.error}`);return}j(!0),Xe("Older terminal output loaded"),je(()=>{var X;(X=r.current)==null||X.bumpResize()})};o.useEffect(()=>{var X,Z;if(!Y)return;V&&((X=dt.getState)==null?void 0:X.call(dt,V))==="connected"&&pt();const E=(Z=dt.onStateChange)==null?void 0:Z.call(dt,(ne,ve)=>{ne!==V||ve!=="connected"||pt()});return()=>{E==null||E()}},[V,Y,r]),o.useEffect(()=>{t&&Be()},[t,oe,r]),o.useEffect(()=>{var ne,ve;const E=W.current,X=(ve=(ne=E==null?void 0:E.ownerDocument)==null?void 0:ne.defaultView)==null?void 0:ve.ResizeObserver;if(!E||!X)return;const Z=new X(Ae=>{const Le=Ae[0];if(!Le)return;const{width:Se,height:_e}=Le.contentRect;_(Ee=>{const Ie=Math.round(Se),Ge=Math.round(_e);return Ee.width===Ie&&Ee.height===Ge?Ee:{width:Ie,height:Ge}})});return Z.observe(E),()=>Z.disconnect()},[]),o.useEffect(()=>{if($.current)return;const E=Oe();!Number.isFinite(E)||E<=0||M(X=>H.current?E<X-$e?E:X:(H.current=!0,E))},[T.height,T.width,B.height,B.width]),o.useEffect(()=>{O&&Re()},[O,Te,Ce]),o.useEffect(()=>{var Z;const E=Q.current;if(Q.current=c,!c)return;E||j(!1),we.current&&(we.current=!1,Fe());const X=be.current;X&&(be.current=null,ft(X.text,X.seq,X.cols,X.rows,{force:!!X.force})),V&&Y&&((Z=dt.getState)==null?void 0:Z.call(dt,V))==="connected"&&pt(),se.current&&J.current===null&&me(),je(()=>{var ne;(ne=r.current)==null||ne.bumpResize()})},[V,c,Y]),o.useEffect(()=>()=>{J.current!==null&&fe(),pe(),te()},[]),o.useEffect(()=>{const E=ne=>{var Ae;const ve=ne.detail;ve!=null&&ve.sessionId&&ve.sessionId!==Y||m&&((Ae=r.current)==null||Ae.bumpResize())},X=de(),Z=X===window?[window]:[window,X];for(const ne of Z)ne.addEventListener("adhdev:fit-cli-terminal",E);return()=>{for(const ne of Z)ne.removeEventListener("adhdev:fit-cli-terminal",E)}},[m,Y,r]);const q=m&&p&&!S&&(K.atTop||!K.canScroll)||g||!!k;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:W,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[q&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{F()},disabled:!Y||g,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:g?"Loading older...":"Load older terminal output"}),k&&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:k})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[C&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:C}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ve()},disabled:!m,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>v(E=>!E),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":w,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),w&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":"Terminal control keys",className:"absolute right-0 top-10 w-56 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>v(!1),"aria-label":"Close terminal control keys",children:"×"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>st("\x1B"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>st(" "),children:"Tab"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>st("\r"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>st("\x1B[A"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>st("\x1B[D"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>st("\x1B[B"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>st("\x1B[C"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>st(""),children:"Ctrl-C"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>st(""),children:"Ctrl-D"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>st(""),children:"Bksp"})]})]})]}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{$.current=!0,M(E=>{const X=Math.max(He,Number((E-.1).toFixed(2)));return X>He&&Re(),X})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{$.current=!0,M(E=>{const X=Math.min(Pe,Number((E+.1).toFixed(2)));return X>He&&Re(),X})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:P,className:O?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:Ce>0?`${Ce}px`:"100%",height:Te>0?`${Te}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:T.width>0?`${T.width}px`:"100%",height:T.height>0?`${T.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:A},children:s.jsx(rc,{ref:r,readOnly:!m||!c,sizingMode:"measured",onViewportMetrics:D,onScrollMetrics:L,onInput:E=>{!m||(d==null||d(V,Y,E))}})})})}),!m&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:x})]}),s.jsx(pc,{contextKey:e.tabKey,panelLabel:ct(e),isSending:a,isBusy:!!le,statusMessage:ke,onSend:async E=>le?!1:n(E),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const ep=5e3,tp=12e3;function sp(e){return e==="disconnected"||e==="reconnecting"}function rp({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=ep,reconnectActionDelayMs:i=tp}){const c=sp(e),[l,d]=o.useState(()=>!c||a<=0),[m,u]=o.useState(()=>!c||i<=0),f=o.useRef(!1);o.useEffect(()=>{if(!c){d(!1);return}if(f.current=!1,a<=0){f.current=!0,d(!0);return}d(!1);const j=setTimeout(()=>{f.current=!0,d(!0)},a);return()=>clearTimeout(j)},[a,c]),o.useEffect(()=>{if(!c){u(!1);return}if(i<=0){u(!0);return}u(!1);const j=setTimeout(()=>{u(!0)},i);return()=>clearTimeout(j)},[i,c]);const x=c?l:e==="offline"||e==="auth_failed",N=!!(n&&e!=="auth_failed"&&(!c||m)),g=o.useMemo(()=>!t||e!=="connected"?!1:a<=0||f.current,[a,t,e]),h=e==="auth_failed"?"red":e==="offline"?"orange":"accent",k={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))"},b={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)"},p={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},y="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",S={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[x&&s.jsx("div",{className:y,style:S,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:k[h],border:b[h],color:p[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&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>n==null?void 0:n(),disabled:e==="offline",children:"Reconnect now"})]})}),g&&s.jsx("div",{className:y,style:S,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 np({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",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!0)};return s.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[l," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:d,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Ja({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($a,{size:n}):s.jsx(Ut,{size:n})})}const Et="New session",Kc="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 ap(e){if(!e||e.isGitRepo===!1||e.reason==="not_git_repo")return null;if(e.hasConflicts)return`${e.branch||"Git"} · conflicts${e.changedFiles>0?` ${e.changedFiles}`:""}`;const t=[e.branch||"Git"];return e.changedFiles>0&&t.push(`±${e.changedFiles}`),e.ahead>0&&t.push(`↑${e.ahead}`),e.behind>0&&t.push(`↓${e.behind}`),t.length===1&&e.dirty&&t.push("dirty"),t.join(" ")}function op(e){return!e||e.isGitRepo===!1||e.reason==="not_git_repo"?null:e.hasConflicts?"conflict":e.error?"error":e.dirty||e.changedFiles>0||e.ahead>0||e.behind>0?"dirty":"quiet"}function ip(e){switch(e){case"conflict":return"border-red-500/25 bg-red-500/[0.08] text-red-400";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-emerald-500/15 bg-emerald-500/[0.06] text-emerald-500"}}function Rs({git:e,className:t="",compact:r=!1}){const n=ap(e),a=op(e);if(!n||!a)return null;const i=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${ip(a)} ${t}`.trim(),title:i.join(" · ")||n,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:n})]})}function cp({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 Yo({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Xo({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=dn(e.updatedAt),l=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),i()},children:"Delete"})]})]})}function lp({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:f,onShowAllHidden:x,onResetPanelsToMain:N,inboxOpen:g,onInboxOpenChange:h,hiddenOpen:k,onHiddenOpenChange:b,onOpenNewSession:p,onOpenDashboardGuide:y,guideNudgeVisible:S=!1,actionShortcuts:j,notifications:A,notificationUnreadCount:M,onOpenNotification:w,onMarkNotificationRead:v,onMarkNotificationUnread:B,onDeleteNotification:_,onOpenGitDialog:T}){const{ides:D,p2pStates:K={}}=Jt(),L=!!e&&et(e)&&!Qe(e),C=!!e&&Qe(e),I=l||(e?hc(e)?"terminal":"chat":null),[W,P]=o.useState(!1),$=o.useRef(null),H=o.useRef(null),Q=D.filter(ae=>ae.type==="adhdev-daemon"),xe=cp({wsStatus:t,isConnected:r,daemonCount:Q.length,p2pStates:K}),ie=xe.subtitle,se=xe.tone==="connected"?"#22c55e":xe.tone==="limited"?"#eab308":"#ef4444",be=xe.tone==="connected"?"0 0 4px #22c55e80":xe.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",we=o.useMemo(()=>A.filter(ae=>!ae.readAt),[A]),ge=o.useMemo(()=>A.filter(ae=>!!ae.readAt),[A]),J=o.useMemo(()=>we.slice(0,9),[we]),ce=M;o.useEffect(()=>{if(!g)return;const ae=de=>{var je;(je=$.current)!=null&&je.contains(de.target)||h(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[g,h]),o.useEffect(()=>{if(!k)return;const ae=de=>{var je;(je=H.current)!=null&&je.contains(de.target)||b(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[k,b]),o.useEffect(()=>{if(!k&&!g)return;const ae=de=>{if(!de.altKey)return;const je=de.code.match(/^Digit([1-9])$/);if(!je)return;const fe=Number(je[1])-1,pe=k?u[fe]:void 0,te=g?J[fe]:void 0;if(!(!pe&&!te)){if(de.preventDefault(),de.stopPropagation(),pe){f==null||f(pe),b(!1);return}te&&(w(te),h(!1))}};return window.addEventListener("keydown",ae,!0),()=>window.removeEventListener("keydown",ae,!0)},[u,k,g,J,b,h,w,f]);const ye=ae=>{if(!ae)return;const de=n.find(je=>je.tabKey===ae);de&&(m==null||m(de))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Ut,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?ct(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:se,boxShadow:be}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[s.jsx("span",{title:xe.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:se,boxShadow:be}}),ie&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ie]}),p&&s.jsx("button",{type:"button",onClick:p,className:"btn btn-secondary btn-sm ml-2",title:`${Et}${j!=null&&j.openNewSession?` (${j.openNewSession})`:""}`,"aria-label":Et,children:s.jsx(Qi,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[y&&s.jsxs("button",{type:"button",onClick:y,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),S&&s.jsx("span",{children:"Guide"})]}),e&&(L||C||!Qe(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:fs(e)||ct(e),children:ct(e)}),T&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>T(e.daemonId,e.workspacePath),children:s.jsx(Rs,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Rs,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(L||C)&&c&&s.jsxs(s.Fragment,{children:[L&&d&&I&&s.jsx(Ja,{mode:I,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:C?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(yt,{size:14})})]}),!Qe(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(Da,{size:14})}),!L&&!Qe(e)&&s.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Tt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:$,children:[s.jsxs("div",{className:`dashboard-header-hidden${W?" is-drop-target":""}`,ref:H,onDragEnter:ae=>{ae.dataTransfer.types.includes("text/tab-key")&&(ae.preventDefault(),P(!0))},onDragOver:ae=>{ae.dataTransfer.types.includes("text/tab-key")&&(ae.preventDefault(),ae.dataTransfer.dropEffect="move",P(!0))},onDragLeave:ae=>{ae.currentTarget.contains(ae.relatedTarget)||P(!1)},onDrop:ae=>{const de=ae.dataTransfer.getData("text/tab-key");ae.preventDefault(),P(!1),ye(de)},children:[s.jsxs("button",{type:"button",onClick:()=>b(!k),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${j!=null&&j.toggleHiddenTabs?` (${j.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Ea,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),k&&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(Yo,{value:j==null?void 0:j.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[N&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:N,children:"Reset panels"}),u.length>0&&x&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{x(),b(!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(Yo,{value:j==null?void 0:j.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:ct(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(ae=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{f==null||f(ae),b(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:ct(ae)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(ae)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(ae)+1]}):null,fs(ae)]})]},ae.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>h(!g),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(ln,{size:16}),ce>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ce})]}),g&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[we.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),we.map(ae=>s.jsx(Xo,{notification:ae,shortcutIndex:J.indexOf(ae)>=0?J.indexOf(ae)+1:void 0,onOpen:()=>w(ae),onMarkRead:()=>v(ae.id),onMarkUnread:()=>B(ae.id),onDelete:()=>_(ae.id)},ae.id))]}),ge.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),ge.map(ae=>s.jsx(Xo,{notification:ae,onOpen:()=>w(ae),onMarkRead:()=>v(ae.id),onMarkUnread:()=>B(ae.id),onDelete:()=>_(ae.id)},ae.id))]}),A.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function gt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function dp(e,t){return String(e||"")!==String(t||"")}function up(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(d=>String(d||"").toLowerCase()).join(`
|
|
39
|
-
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!lc(c.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
40
|
-
`).includes(a)))}function mp(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 Wc(e,t={}){return mp(up(e,t),t.sortMode||"recent")}function tn(e){return e?"Resume saved history":"Start fresh"}function Qa(e){return e?"Resuming saved history…":"Starting fresh…"}function fp(){return"Start fresh"}function Oc(e,t=!1){return e==="cli"?tn(t):e==="ide"?"Start IDE":"Start ACP session"}function Fc(e,t=!1){return e==="cli"?Qa(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function pp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function hp(){return"Open saved history"}function xp(){return"Saved History"}function Za(){return"Use saved history when you want continuity in the same provider conversation."}function bp(){return"No saved history found yet."}function gp(){return"Refresh saved history"}function yp(){return"Refreshing saved history…"}function ns(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function as(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Ls(e){return e==="start-fresh"?"Start fresh":"Restart"}function _s(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function eo(e){return`Resume saved history with ${e}?`}function to(){return"Review or change the target workspace before resuming saved history."}function vp(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 so({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:f,onSwitchSession:x,onRefreshHistory:N,onResumeSavedSession:g}){var _;const h=t.find(T=>T.id===e.routeId),k=(h==null?void 0:h.chats)||[],b=(_=h==null?void 0:h.activeChat)==null?void 0:_.id,p=et(e)&&!Qe(e),[y,S]=o.useState(()=>gt()),j=l||y,A=String(d||"").trim(),M=T=>{if(m){m(T);return}S(T)},w=o.useMemo(()=>a.map(T=>{const D=String(T.workspace||"").trim();return T.canResume||D||!A?T:{...T,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,a]),v=o.useMemo(()=>Wc(w,{textQuery:j.textQuery,workspaceQuery:j.workspaceQuery,modelQuery:j.modelQuery,resumableOnly:j.resumableOnly,sortMode:j.sortMode}),[w,j.modelQuery,j.resumableOnly,j.sortMode,j.textQuery,j.workspaceQuery]),B=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:p?xp():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Jf(e)}),p&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Za()})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(yt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!p&&s.jsx("button",{onClick:f,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"}),p?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:j.textQuery,onChange:T=>M({...j,textQuery:T.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:j.workspaceQuery,onChange:T=>M({...j,workspaceQuery:T.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:j.modelQuery,onChange:T=>M({...j,modelQuery:T.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:j.sortMode,onChange:T=>M({...j,sortMode:T.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:j.resumableOnly,onChange:T=>M({...j,resumableOnly:T.target.checked})}),"Resume-ready only"]})]}),v.map(T=>{const D=e.providerSessionId===T.providerSessionId,K=D||!T.canResume||!!c,L=T.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{K||!g||g(T)},disabled:K,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${D?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${K?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${D?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:T.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:vp(T.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:T.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[T.workspace||"Workspace unknown",L?" · selected workspace":"",ms(T.summaryMetadata)?` · ${ms(T.summaryMetadata)}`:"",T.messageCount>0?` · ${T.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:D?"ACTIVE":T.canResume?L?"RESUME IN SELECTED WORKSPACE":c===T.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},T.id)})]}):k.map(T=>s.jsxs("div",{onClick:()=>{x(e.routeId,T.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===T.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${b===T.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[T.id.substring(0,12),"..."]}),b===T.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},T.id)),(p&&!i&&v.length===0||!p&&k.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(ou,{size:32})}),s.jsx("div",{className:"text-[13px]",children:p?a.length>0?"No saved history matches these filters.":bp():"No recent chat sessions found."})]}),p&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:yp()})})]}),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:N,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(cr,{size:13})," ",p?gp():"Refresh History"]})})})]})]});return typeof document>"u"?B:rr.createPortal(B,document.body)}const Jo={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 Hc({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=Jo[n.type]||Jo.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(yt,{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 wp=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function jp(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function kp(e){return e.sessionId||e.instanceId||e.agentType}function Rn(e,t){return e||t}function Uc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Ct(r,{fallbackId:r.id}));return t}function zc(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 ro(e,t={}){return Sp(e,zc(e,t))}function Sp(e,t={}){var f,x,N,g,h,k,b,p;const r=[],n=t.machineName,a=t.connectionState,i=jp(e),c=e.workspace||"",l=em(e.type,{agentName:e.cliName}),d=et(e)||Qe(e)?l:ot(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var S,j;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||ot(y.providerType),status:y.status,title:y.title,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,messages:((S=y.activeChat)==null?void 0:S.messages)||[],activeModal:((j=y.activeChat)==null?void 0:j.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,surfaceHidden:y.surfaceHidden,git:y.git,settings:y.settings}}):[],u=wp(e);if(u){const y=e.sessionId||e.instanceId,S=(f=e.settings)==null?void 0:f.meshCoordinatorFor,j=(x=e.settings)==null?void 0:x.meshNodeFor,A=S?" (Coordinator)":j?" (Mesh Node)":"",M=l+A,w=(N=e.activeChat)==null?void 0:N.activeModal,v=w&&Array.isArray(w.buttons)&&w.buttons.length>0,B=wt((g=e.activeChat)==null?void 0:g.status,{activeModal:(h=e.activeChat)==null?void 0:h.activeModal})||wt((b=(k=e.agents)==null?void 0:k[0])==null?void 0:b.status)||"idle",_=e.activeChat||{title:"",messages:[]};let T=_.title&&String(_.title).trim()?String(_.title).trim():"";const D=(p=e.activeChat)==null?void 0:p.id,K=e.chats;if(D&&Array.isArray(K)&&K.length>0){const W=K.find(P=>P.id===D||P.id&&String(P.id)===String(D));W!=null&&W.title&&String(W.title).trim()&&(T=String(W.title).trim())}const L=(et(e)||Qe(e),e.type),C=(et(e)||Qe(e))&&Eo(T,M,L)?"":T,I=_.messages||[];r.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:et(e)?e.mode||"terminal":"chat",agentName:M,agentType:L,status:B,title:C,messages:I,resume:e.resume,hostIdeType:!et(e)&&!Qe(e)?e.type:void 0,workspaceName:i,workspacePath:c,git:e.git,displayPrimary:C||i||(et(e)?e.mode==="chat"?M:`Terminal${A}`:M),displaySecondary:et(e)&&i?M:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:v?w.buttons:void 0,modalMessage:v?w.message:void 0,streamSource:"native",tabKey:Rn(y,e.id),machineName:n,connectionState:a,settings:e.settings})}if(u&&(et(e)||Qe(e)))return r;for(const y of m){const S=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,j=tm(y),A=kp(y),M=`${e.id}:${A}`,w=y.title&&String(y.title).trim()||"",v=Eo(w,y.agentName,y.agentType)?"":w,B=y.messages||[];(y.transport==="cdp-webview"||y.sessionId||y.providerSessionId||B.length>0||S||v||!["idle","panel_hidden","disconnected","not_monitored"].includes(j))&&r.push({routeId:e.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:y.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:y.sessionCapabilities,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:j,title:v,messages:B,hostIdeType:e.type,workspaceName:i,workspacePath:c,git:y.git||e.git,displayPrimary:v||i||y.agentName||d,displaySecondary:`${d} · ${y.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,lastUpdated:y.lastUpdated||e.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,modalButtons:S?y.activeModal.buttons:void 0,modalMessage:S?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Rn(y.sessionId||y.instanceId,M),machineName:n,connectionState:a,settings:y.settings})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:i,workspacePath:c,git:e.git,displayPrimary:i||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Rn(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings}),r}function Np(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 Vc(e,t){const r=Np(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Gc=[{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:"🏄"}],qc=[{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:"🧩"}],Yc=[{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:"🟠"}],Cp=Gc,Tp=qc,Mp=Yc;function zt(...e){return yd(vd(e))}function Ap({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:zt("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 Zs({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(Ap,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:zt("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const wa="adhdev:themechange";function Ip(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ys(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function vs(e){return e==="system"?Ip():e}function Xc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Kr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(wa,{detail:{preference:e,theme:t}}))}function Rp(){const e=ys(),t=vs(e);Xc(t),Kr(e,t)}function no(){const[e,t]=o.useState(ys),[r,n]=o.useState(()=>vs(ys()));o.useEffect(()=>{Xc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),Kr("system",m)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=d=>{const m=d.detail||{},u=m.preference,f=m.theme;t(u==="dark"||u==="light"||u==="system"?u:ys()),n(f==="dark"||f==="light"?f:vs(ys()))},l=d=>{if(d.key!=="theme")return;const m=ys(),u=vs(m);t(m),n(u)};return window.addEventListener(wa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(wa,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=vs(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Kr(c,l)},[]),i=o.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=vs(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Kr(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const Qo={dark:"Dark",light:"Light",system:"System"};function Lp({collapsed:e}){const{preference:t,cycleTheme:r}=no(),n=t==="dark"?s.jsx(cu,{size:16}):t==="light"?s.jsx(iu,{size:16}):s.jsx(lu,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Qo[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Qo[t]})]})}function Ln(e,t){return e?typeof e=="function"?e(t):e:null}function _p({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=o.useState(!1),[f,x]=o.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),N=()=>u(!0),g=()=>u(!1),h=()=>{x(y=>{const S=!y;try{localStorage.setItem(d,S?"1":"0")}catch{}return S})},k=o.useMemo(()=>({collapsed:f,mobileMenuOpen:m,openMobileMenu:N,closeMobileMenu:g,toggleCollapsed:h}),[f,m]),b=y=>`nav-item${y.active?" active":""} cursor-pointer ${f?"justify-center py-2.5 px-0":""}${y.className?` ${y.className}`:""}`,p=y=>s.jsxs("div",{className:b(y),id:`nav-${y.id}`,onClick:()=>{y.onSelect(),g()},title:f?y.title??(typeof y.label=="string"?y.label:void 0):y.title,children:[s.jsx("span",{className:"nav-icon",children:y.icon}),!f&&y.label]},y.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${f?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:N,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),m&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:g,onKeyDown:y=>y.key==="Escape"&&g()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${f?"justify-center gap-0":""}`,children:Ln(t,k)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:g,children:s.jsx(yt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(p)}),n.map(y=>s.jsxs("div",{className:y.className??"border-t border-border-subtle pt-2 mt-2",children:[!f&&y.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:y.title}):null,y.items.map(p)]},y.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(p),Ln(i,k),s.jsx(Lp,{collapsed:f}),Ln(c,k)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function jt({title:e,icon:t,description:r,accentColor:n,className:a,children:i}){return s.jsxs("div",{className:zt("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 sn({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:zt("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 Pp={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"},Dp={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function js({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:zt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Pp[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Dp[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function _n({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:zt("mb-5",n),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function Pn(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:zt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const Ep={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"},$p={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Bp({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:zt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Ep[e],r),children:[s.jsx("span",{className:zt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",$p[e])}),n]})}function es({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 Kp({onPrefChange:e}){const[t,r]=um(),[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(es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ln,{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(es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>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:()=>{mc().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(du,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(uu,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ms,{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 rn(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Wp(e,t){const r=rn(e),n=rn(t);if(!r||!n)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function Jc(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function er(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Wp(r,t)>=0)return!1;const n=rn(r),a=rn(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Op(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Dn(e,t){return e instanceof Error?e.message:t}function Fp({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(sn,{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(Up,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Zo({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 rr.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 Hp(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Cp,...Tp,...Mp].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 Up({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var K,L;const[i,c]=o.useState("idle"),[l,d]=o.useState(""),[m,u]=o.useState(null),[f,x]=o.useState("idle"),[N,g]=o.useState(""),h=e.version||null,k=((K=e.machine)==null?void 0:K.platform)||((L=e.system)==null?void 0:L.platform)||"",b=Ct(e,{fallbackId:e.id}),p=k==="win32"?"🪟":k==="darwin"?"🍎":"🐧",y=t.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),S=t.filter(C=>C.daemonId===e.id&&C.transport==="pty"),j=t.filter(C=>C.daemonId===e.id&&C.transport==="acp"),A=e.p2p,M=async()=>{if(r){c("upgrading"),d("Starting upgrade...");try{const C=Op(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),d(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),d(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),d(C.error||"Upgrade failed"))}catch(C){c("error"),d(Dn(C,"Connection lost during upgrade"))}}},w=async()=>{if(u(null),!!n){x("loading");try{await n(e.id),x("done"),g("Machine disconnected.")}catch(C){x("error"),g(Dn(C,"Failed to disconnect"))}}},v=async()=>{if(u(null),!!a){x("loading");try{await a(e.id),x("done"),g("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){x("error"),g(Dn(C,"Failed to revoke token"))}}},B="0.9.74",_=Jc(e,B),T=er(e,B),D=y.length+S.length+j.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:p}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:b}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),h&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${_?"":"bg-bg-secondary"}`,style:_?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",h,!_&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&_&&s.jsx("button",{onClick:M,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":`${T?"↑ Update now":`↑ Update${` to v${B}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Bp,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[A&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${A.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${A.state==="connecting"||A.state==="new"?"animate-pulse":""}`,style:A.state==="connecting"||A.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",A.state==="connected"?"connected":A.state==="connecting"||A.state==="new"?"connecting...":A.state||"off"]}),A.peers!==void 0&&A.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",A.peers," peer",A.peers!==1?"s":"",")"]})]}),A&&D>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),D>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[y.map(C=>{const I=Hp(C.type),W=C.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:I.icon}),s.jsx("span",{children:I.name}),W!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${W?"bg-green-400":"animate-pulse"}`,style:W?void 0:{background:"var(--status-warning)"},title:W?"CDP connected":"CDP connecting..."})]},C.id)}),S.map(C=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:C.cliName||"CLI"})]},C.id)),j.map(C=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||N)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-red-400":i==="done"||f==="done"?"text-green-400":"text-text-muted"}`,children:N||l})]}),m==="disconnect"&&s.jsx(Zo,{title:"🔌 Disconnect Machine",message:`Disconnect "${b}" from ADHDev?
|
|
41
|
-
|
|
42
|
-
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
43
|
-
|
|
44
|
-
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:w,onCancel:()=>u(null)}),m==="revoke"&&s.jsx(Zo,{title:"⚠️ Remove Machine",message:`Remove "${b}" from your dashboard?
|
|
45
|
-
|
|
46
|
-
This will:
|
|
47
|
-
• Immediately disconnect the machine
|
|
48
|
-
• Delete the machine registration
|
|
49
|
-
• Require restarting ADHDev on that machine
|
|
50
|
-
|
|
51
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:v,onCancel:()=>u(null)})]})}const zp=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Vp(){const{preference:e,setPreference:t}=no();return s.jsx("div",{className:"flex gap-2",children:zp.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 Gp(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 qp(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function En(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function ei(e){const{r:t,g:r,b:n}=qp(e);return .2126*En(t)+.7152*En(r)+.0722*En(n)}function ti(e,t){const r=ei(e),n=ei(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Qc(e){const t=Gp(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return ti(t,r)>=ti(t,n)?r:n}const ja={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},ka={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},Yp=[{id:"midnight",name:"Midnight",description:"Classic violet theme",preview:{dark:{userBubble:"#8b5cf6",assistantBubble:"#18181d",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0f0f13",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#7c3aed",assistantBubble:"#ffffff",assistantBorder:"1px solid rgba(0,0,0,0.08)",containerBg:"#f0f1f5",textColor:"#52525b"}}},{id:"ember",name:"Ember",description:"Default landing-inspired amber theme",preview:{dark:{userBubble:"#f59e0b",assistantBubble:"#111726",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0a0e1a",textColor:"#9ca3af"},light:{userBubble:"#f59e0b",assistantBubble:"#fffaf4",assistantBorder:"1px solid rgba(146,64,14,0.10)",containerBg:"#fff8ee",textColor:"#6f6255"}}},{id:"aurora",name:"Aurora",description:"Pink accent theme",preview:{dark:{userBubble:"#ec4899",assistantBubble:"#1e1b2e",assistantBorder:"1px solid rgba(236,72,153,0.12)",containerBg:"#0f0d17",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#ec4899",assistantBubble:"#fef2f8",assistantBorder:"1px solid rgba(236,72,153,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}},{id:"honey",name:"Honey",description:"Warm yellow accents",preview:{dark:{userBubble:"#fbbf24",assistantBubble:"#1c1c1e",assistantBorder:"1px solid rgba(255,255,255,0.06)",containerBg:"#111113",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#fbbf24",assistantBubble:"#fffbeb",assistantBorder:"1px solid rgba(251,191,36,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}}],Zc="adhdev-chat-theme",el="adhdev-chat-theme-custom";function Wr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Zc)||"ember"}catch{return"ember"}}function _t(e){try{const t=localStorage.getItem(el);if(t){const r=JSON.parse(t);return{...e==="dark"?ja:ka,...r[e]}}}catch{}return e==="dark"?ja:ka}function Mr(e,t){try{localStorage.setItem(el,JSON.stringify({dark:e,light:t}))}catch{}}function Mt(e,t){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${t})`}function nn(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 Xp={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function tr(e,t){var a;const r=(a=Xp[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",nn(r,24)),n.style.setProperty("--accent-on-primary",Qc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${nn(r,18)})`),n.style.setProperty("--border-accent",Mt(r,.35)),n.style.setProperty("--nav-active-bg",Mt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Mt(r,.06)}`)}function os(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Mt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Mt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Mt(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",Mt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Mt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",nn(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Qc(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${nn(e.accentColor,40)})`),t.style.setProperty("--border-accent",Mt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Mt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Mt(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${Mt(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function ao(){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 Jp(e){try{localStorage.setItem(Zc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=is()?"dark":"light";os(_t(t))}else ao(),tr(e,is()?"dark":"light")}function Qp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Wr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=is()?"dark":"light";os(_t(t))}else ao(),tr(e,is()?"dark":"light")}function is(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function vt({label:e,value:t,onChange:r}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Hs({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function Zp({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=o.useState(()=>_t(r));o.useEffect(()=>{a(_t(r))},[r]);const i=o.useCallback((c,l)=>{a(d=>{const m={...d,[c]:l},f=_t(r==="dark"?"light":"dark");return r==="dark"?Mr(m,f):Mr(f,m),os(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(Hs,{title:"App Background",children:[s.jsx(vt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(vt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(vt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Hs,{title:"App Text",children:[s.jsx(vt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(vt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(vt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Hs,{title:"Borders & Accent",children:[s.jsx(vt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(vt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(vt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Hs,{title:"Chat Bubbles",children:[s.jsx(vt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(vt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(vt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(vt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Hs,{title:"Chat Layout",children:[s.jsx(vt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(vt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(vt,{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?ja:ka,d=_t(e?"light":"dark");e?Mr(c,d):Mr(d,c),a(c),os(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function eh(){const[e,t]=o.useState(Wr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>_t("dark"));o.useEffect(()=>{n(is());const d=new MutationObserver(()=>{const f=is();n(f);const x=Wr();x==="custom"?os(_t(f?"dark":"light")):tr(x,f?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const f=is();n(f);const x=Wr();x==="custom"?os(_t(f?"dark":"light")):tr(x,f?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?os(_t(r?"dark":"light")):(ao(),tr(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(_t(r?"dark":"light"))},[r]);const c=d=>{t(d),Jp(d)},l=[...Yp,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(d=>{const m=e===d.id,u=r?d.preview.dark:d.preview.light,f=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:u.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:f},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[m&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:d.id==="custom"?"🎨 Custom":d.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&s.jsx(Zp,{dark:r,onColorsChange:d=>i(d)})]})}const oo="adhdev_mobileDashboardMode_v1",Sa="adhdev:mobile-dashboard-mode-change";function io(){try{return localStorage.getItem(oo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function th(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??io())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==oo||t()};return window.addEventListener(Sa,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Sa,r),window.removeEventListener("storage",n)}}function sh(e){try{localStorage.setItem(oo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Sa,{detail:e}))}function rh(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(io()==="chat")},[]),s.jsx(es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ut,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{t(r),sh(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const $n=new Map,si=new Map;function nh(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 ah(e,t,r,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n,platform:r.platform,machine:r}}function tl(){const{sendCommand:e}=xt(),{injectEntries:t,getIdes:r}=nr();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??af,c=si.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=$n.get(n);if(l)return l;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=nh(m);if(!u)return;const f=r().find(N=>N.id===n),x=ah(f,n,u.machine,u.timestamp||Date.now());t([x]),si.set(n,Date.now())})().finally(()=>{$n.delete(n)});return $n.set(n,d),d},[r,t,e])}function oh(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 ih(e,t){const{sendData:r}=xt(),{injectEntries:n,getIdes:a}=nr(),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(d=>Ht.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const f=a().find(N=>N.id===d),x=oh(f,d,u);n([x])}));return()=>{l.forEach(d=>d())}},[i,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function ch(e,t){const{sendData:r}=xt(),[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 d=Ht.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},m=>{l&&(clearTimeout(l),l=null),a(m.diagnostics),c(!1)});return d.initialSendAccepted?l=setTimeout(()=>{c(!1)},df):c(!1),()=>{l&&clearTimeout(l),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:a}}function lh(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function sl(e){const{sendData:t}=xt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=lh(e);if(!a||!e.sessionId||!t){n({});return}const i=Ht.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),Cs.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 rl="adhdev_hiddenTabs";function dh(){try{const e=localStorage.getItem(rl);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function bs(e){try{localStorage.setItem(rl,JSON.stringify([...e]))}catch{}}function Bn(e){return Ya(e)}function co(e,t){return Ns(t).some(r=>e.has(r))}function uh(){const[e,t]=o.useState(dh),r=o.useCallback(m=>{const u=Bn(m);t(f=>{const x=new Set(f);return x.has(u)?x.delete(u):x.add(u),bs(x),x})},[]),n=o.useCallback(m=>{const u=Bn(m);t(f=>{if(f.has(u))return f;const x=new Set(f);return x.add(u),bs(x),x})},[]),a=o.useCallback(m=>{const u=Bn(m);t(f=>{if(!f.has(u))return f;const x=new Set(f);return x.delete(u),bs(x),x})},[]),i=o.useCallback(()=>{t(m=>{if(m.size===0)return m;const u=new Set;return bs(u),u})},[]),c=o.useCallback((m,u)=>{t(f=>{const x=new Set(f);for(const N of u)x.add(N);return bs(x),x})},[]),l=o.useCallback((m,u)=>{t(f=>{const x=new Set(f);for(const N of u)x.delete(N);return bs(x),x})},[]),d=o.useCallback(m=>co(e,m),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:d}}function nl(e){return e instanceof Error?e.message:String(e||"")}function al(e){const t=nl(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function ol(e){const t=nl(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function il({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!et(e)||Qe(e))return;const i=$s(e);if(i===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(xs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Bt(e),mode:t})}catch(l){const d=ol(l);c&&!d&&a(m=>{const u={...m};return i===cl(r,c)?delete u[c]:u[c]=i,u}),al(l)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function ri(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 mh(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=ri(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>ri(d,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function cl(e,t){if(!t)return null;for(const r of e){if(r.sessionId===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function fh(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))cl(t,a)===i&&(delete n[a],r=!0);return r?n:e}function ph({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{mc()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:$c(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return hm(a),o.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const d=Date.now(),m={};for(const[u,f]of Object.entries(l))d-f<5e3&&(m[u]=f);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 d=l.filter(m=>m.timestamp>c).slice(-100);return d.length===l.length?l:d})},6e4);return()=>clearInterval(i)},[n]),null}function ni(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 cs(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=ni(t==null?void 0:t.receivedAt)||ni(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function Na(e,t=0){return cs(e)||e.lastUpdated||t||0}function ll(e){return cs(e)||e.lastUpdated||0}function dl(e,t,r=ll){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 Ca(e){var r;const t=wt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function hh(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Ca(e)&&!e.title.trim()}function xh(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(Ca(r))-Number(Ca(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:dl(t,r)})[0]||null}function Pt(e,t){const r=e.filter(c=>c.routeId===t);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,a=r.filter(c=>c.streamSource==="agent-stream"),i=xh(a);return n?i&&hh(n)?i:n:i||r[0]||null}function bh(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 Kn(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 gh(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 ai(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?gh(Ts(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 yh(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||""),ai(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||""),ai(r.activeChat)].join(":"))].join("|")}function vh(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 wh(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const i of Ns({routeId:n.routeId}))r.set(i,a);for(const i of Ns({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of Ns({tabKey:n.tabKey}))r.set(i,n)}return r}function jh(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function kh(e){const t=jh(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=Ts(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Sh({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>bh(e),[e]),i=o.useMemo(()=>Uc(e),[e]),c=o.useRef([]),l=o.useRef([]),d=o.useRef([]),m=o.useRef(new Map),u=o.useRef(new Map),f=o.useMemo(()=>{const S=new Map,j=[];for(const v of a){const{connectionState:B="new",machineName:_}=zc(v,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),T=yh(v),D=m.current.get(v.id);if(D&&D.ide===v&&D.sourceSignature===T&&D.connectionState===B&&D.machineName===_){S.set(v.id,D),j.push(...D.conversations);continue}const K=ro(v,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),L={ide:v,sourceSignature:T,connectionState:B,machineName:_,conversations:K};S.set(v.id,L),j.push(...K)}m.current=S;const A=new Map,M=v=>{const B=kh(v),_=u.current.get(v.tabKey);if(_&&_.signature===B)return A.set(v.tabKey,_),_.timestamp;const T={signature:B,timestamp:ll(v)||(_==null?void 0:_.timestamp)||0};return A.set(v.tabKey,T),T.timestamp},w=[...j].sort((v,B)=>dl(v,B,M));return u.current=A,w},[a,t,i]),x=o.useMemo(()=>{const S=vh(f,r);return Kn(c.current,S)?c.current:(c.current=S,S)},[f,r]),N=o.useMemo(()=>{const S=new Map,j=Array.from(new Set(x.map(A=>A.routeId)));for(const A of j){const M=Pt(x,A);M&&S.set(A,M)}return S},[x]),g=o.useMemo(()=>{const S=new Map;for(const j of x){const A=N.get(j.routeId),M=j.streamSource==="native"&&A?A:j;for(const w of Ns({providerSessionId:j.providerSessionId,sessionId:j.sessionId}))S.set(w,M)}return S},[x,N]),h=o.useMemo(()=>wh(x,N),[x,N]),k=o.useCallback(S=>{if(S)return g.get(S)},[g]),b=o.useCallback(S=>{if(S)return h.get(S)},[h]),p=o.useMemo(()=>{const S=x.filter(j=>!co(n,j));return Kn(l.current,S)?l.current:(l.current=S,S)},[x,n]),y=o.useMemo(()=>{const S=p.map(j=>j.tabKey);return Kn(d.current,S)?d.current:(d.current=S,S)},[p]);return{chatIdes:a,conversations:x,visibleConversations:p,visibleTabKeys:y,resolveConversationBySessionId:k,resolveConversationByTarget:b}}function Nh({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 d=new URLSearchParams(l);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Ch({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{nt.setIdes(e)},[e]),o.useEffect(()=>{nt.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),o.useEffect(()=>{const a=nt.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(d=>d.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=Pc.on("status_event",i=>{nt.handleRawEvent(i,"ws")});return()=>{a()}},[]),o.useEffect(()=>{var i;const a=c=>{var h;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const d=l.targetSessionId||l.targetKey||l.daemonId,m=n(d),u=(m==null?void 0:m.routeId)||l.daemonId;if(!u)return;const f=Number(l.buttonIndex),x=l.button||((h=m==null?void 0:m.modalButtons)==null?void 0:h[f])||"Approve",N=String(x).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),g=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N);t(u,"resolve_action",{action:g?"approve":"reject",button:x,...Number.isFinite(f)&&{buttonIndex:f},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(k=>console.error("[SW Action] approval failed:",k))};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 Th="adhdev_dashboardLayout_v1",Mh="adhdev_dashboardDockview_v1",Ah="adhdev_dashboardDockviewHiddenRestore_v1",Us={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function lo(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Ih(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function ul(e){return`${Th}:${e}`}function Rh(e){const t=ul(e);return lo(t,null)}function Lh(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=ul(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function ml(e){return`${Mh}:${e}`}function _h(e){const t=ml(e);return lo(t,null)}function Ph(e,t){try{const r=ml(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function fl(e){return`${Ah}:${e}`}function Dh(e){const t=fl(e);return lo(t,{})}function Eh(e,t){try{const r=fl(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function $h(){return{groupAssignments:[...Us.groupAssignments],focusedGroup:Us.focusedGroup,groupActiveTabIds:{...Us.groupActiveTabIds},groupTabOrders:{...Us.groupTabOrders},groupSizes:[...Us.groupSizes]}}function Bh(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Kh(){const[e]=o.useState(()=>Ih(typeof window<"u"?window.innerWidth:1280)),[t,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,d]=o.useState({}),[m,u]=o.useState([]),[f,x]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[N,g]=o.useState(!1),h=o.useCallback(()=>{if(N)return;const v=Rh(e)??$h();r(new Map(v.groupAssignments)),a(v.focusedGroup),c(v.groupActiveTabIds),d(v.groupTabOrders),u(v.groupSizes),g(!0)},[N,e]);o.useEffect(()=>{N&&Lh(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:m})},[N,e,t,n,i,l,m]),o.useEffect(()=>{const v=window.matchMedia("(max-width: 767px)"),B=_=>x(_.matches);return v.addEventListener("change",B),()=>v.removeEventListener("change",B)},[]);const k=o.useCallback(v=>{r(v)},[]),b=o.useCallback(v=>{a(v)},[]),p=o.useCallback(v=>{c(v)},[]),y=o.useCallback(v=>{d(v)},[]),S=o.useCallback(v=>{u(v)},[]),j=o.useCallback(v=>{b(v)},[b]),A=o.useCallback((v,B)=>{c(_=>(_[v]??null)===(B??null)?_:{..._,[v]:B})},[]),M=o.useCallback((v,B)=>{d(_=>{const T=_[v];return Bh(T,B)?_:{..._,[v]:B}})},[]),w=o.useCallback((v,B)=>{const _=B.get(v)??0;return A(_,v),j(_),_},[j,A]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:k,focusedGroup:n,updateFocusedGroup:b,focusGroup:j,groupActiveTabIds:i,updateGroupActiveTabIds:p,setGroupActiveTab:A,groupTabOrders:l,updateGroupTabOrders:y,setGroupTabOrder:M,groupSizes:m,updateGroupSizes:S,isMobile:f,hasHydratedStoredLayout:N,hydrateStoredLayout:h,focusConversationTab:w}}function Wh(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=qa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Oh({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:f,handleRefreshHistory:x}){const N=o.useRef(!1),g=o.useRef(!1),h=o.useRef(null),k=o.useRef(!1);o.useEffect(()=>{if(!e||N.current||t.length===0)return;if(!a){i();return}const b=r(e);b&&(c(b.tabKey,n),N.current=!0,g.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),l(p=>{const y=new URLSearchParams(p);return y.delete("activeTab"),y},{replace:!0}))},[e,t,r,n,a,i,c,l]),o.useEffect(()=>{if(!(g.current||a)&&t.length!==0){if(!e){i(),g.current=!0;return}if(N.current){g.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(g.current||a)&&(i(),g.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,a,i]),o.useEffect(()=>{if(!d){k.current=!1;return}if(!m||k.current||u)return;const b=f.find(p=>p.id===m.routeId);b&&(!b.chats||b.chats.length===0||Wh(b.chats,m))&&(k.current=!0,x())},[d,m,u,f,x])}function Wn(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=qa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function pl({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[d,m]=o.useState(!1),u=o.useCallback(async g=>{try{await e("standalone","launch_ide",{ideType:g,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),f=o.useCallback(async(g,h)=>{try{const k=g||(t==null?void 0:t.daemonId)||"",b=await e(k,"switch_chat",{id:h,sessionId:h,...ss(t)}),p=b==null?void 0:b.result;if((b==null?void 0:b.success)===!0||p==="switched"||p==="switched-by-title")return;p===!1||p==="not_found"?Os(a,"⚠️ Session tab not found — try refreshing history"):typeof p=="string"&&p.startsWith("error:")?Os(a,`⚠️ Switch error: ${p}`):Os(a,"⚠️ Session switch failed")}catch(k){console.error("Switch failed",k),Os(a,`❌ Switch failed: ${k.message||"connection error"}`)}},[t,e,a]),x=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const g=Is(t);await e(g,"new_chat",{...ss(t)}),i(h=>({...h,[t.tabKey]:Date.now()}))}catch(g){console.error("New chat failed",g)}finally{l(!1)}}},[t,c,e,i]),N=o.useCallback(async()=>{var g,h;if(!(!t||d)){m(!0);try{const k=Is(t),b=async()=>e(k,"list_chats",{forceExpand:!0,...ss(t)});let p=await b(),y=(p==null?void 0:p.chats)||((g=p==null?void 0:p.result)==null?void 0:g.chats);Wn(y,t)&&(await new Promise(S=>setTimeout(S,450)),p=await b(),y=(p==null?void 0:p.chats)||((h=p==null?void 0:p.result)==null?void 0:h.chats)),p!=null&&p.success&&Array.isArray(y)&&(n(t.routeId,y),Wn(y,t)&&!Wn(r,t)&&Os(a,"⚠️ History dialog did not fully open — try once more"))}catch(k){console.error("Refresh history failed",k)}finally{m(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:f,handleNewChat:x,handleRefreshHistory:N}}function Fh(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 Hh(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function oi(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 Ar(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 d=a[l];typeof d=="number"&&d>0&&i.set(c,d)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function ii(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 Uh(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 zh(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 ci(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 li(e){return Array(e).fill(100/e)}function Vh({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:d,visibleTabKeys:m}){const u=o.useRef(null),f=o.useMemo(()=>Ar(e,m),[e,m]),x=f.assignments,N=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),g=N>1,h=o.useCallback((j,A)=>{t(M=>{const w=new Map(Ar(M,m).assignments);return A===0?w.delete(j):w.set(j,A),w}),n(M=>({...M,[A]:j})),r(A)},[t,m,n,r]),k=o.useCallback(j=>{t(A=>{const M=Ar(A,m).assignments,w=new Map;for(const[v,B]of M)B!==j&&(B>j?w.set(v,B-1):w.set(v,B));return w}),c(A=>{if(A.length<=1)return[];const M=[...A];M.splice(j,1);const w=M.reduce((v,B)=>v+B,0);return w>0?M.map(v=>v/w*100):[]}),r(0)},[t,m,c,r]),b=o.useCallback((j,A)=>{A.preventDefault();const M=u.current;if(!M)return;const w=A.clientX,v=M.offsetWidth,B=i.length===N?[...i]:li(N),_=D=>{const L=(D.clientX-w)/v*100,C=[...B];C[j]=Math.max(15,B[j]+L),C[j+1]=Math.max(15,B[j+1]-L),c(C)},T=()=>{document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",T),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",_),document.addEventListener("mouseup",T)},[i,N,c]),p=o.useCallback((j,A,M)=>{if(N>=4)return;const w=M==="left"?A:A+1;t(v=>{const B=Ar(v,m).assignments,_=new Map;for(const T of d){const D=B.get(T.tabKey)??0,K=D>=w?D+1:D;K>0&&_.set(T.tabKey,K)}return w>0&&_.set(j,w),_}),c(v=>{const B=v.length===N?[...v]:li(N),_=B[A]??100/N,T=Math.max(15,_/2),D=Math.max(15,_/2),K=[...B];K[A]=T,K.splice(w,0,D);const L=K.reduce((C,I)=>C+I,0);return K.map(C=>C/L*100)}),n(v=>{const B=ci(v,w);return B[w]=j,B}),a(v=>{const B=ci(v,w);return B[w]=[j],B}),r(w)},[N,t,m,d,c,n,a,r]);o.useEffect(()=>{Fh(e,x)||t(x)},[e,x,t]),o.useEffect(()=>{const{mapping:j,usedGroups:A}=f;n(M=>{const w=ii(M,j);return oi(M,w)?M:w}),a(M=>{const w=ii(M,j);return oi(M,w)?M:w}),r(M=>{const w=l?0:Uh(M,A,j);return M===w?M:w}),c(M=>{const w=l?[]:zh(M,A,f.groupCount);return Hh(M,w)?M:w})},[f,l,n,a,r,c]);const y=o.useMemo(()=>{const j=Array.from({length:N},()=>[]);for(const A of d){const M=x.get(A.tabKey)??0,w=Math.min(M,N-1);j[w].push(A)}return j},[d,x,N]),S=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:x,numGroups:N,isSplitMode:g,groupedConvs:y,moveTabToGroup:h,closeGroup:k,handleResizeStart:b,splitTabRelative:p,clearAllSplits:S}}function Gh({ides:e,sendDaemonCommand:t}){const r="0.9.74",n=o.useMemo(()=>e.filter(u=>u.type!=="adhdev-daemon"?!1:Jc(u,r)).sort((u,f)=>Number(er(f,r))-Number(er(u,r))),[r,e]),a=o.useMemo(()=>n.some(u=>er(u,r)),[r,n]),[i,c]=o.useState(!1),[l,d]=o.useState({}),m=o.useCallback(async u=>{var f,x;d(N=>({...N,[u]:"upgrading"}));try{const N=await t(u,"daemon_upgrade",{});(f=N==null?void 0:N.result)!=null&&f.upgraded||(x=N==null?void 0:N.result)!=null&&x.success?d(g=>({...g,[u]:"done"})):d(g=>({...g,[u]:"error"}))}catch{d(N=>({...N,[u]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:m}}const hl=80;function Or(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function qh(e){return{...e,createdAt:Or(e.createdAt),updatedAt:Or(e.updatedAt,e.createdAt),lastEventAt:Or(e.lastEventAt,e.updatedAt||e.createdAt)}}function Yh(e){const t=Ya(e);return t==="unknown:"?e.id:t}function Xh(e){return[e.type,Tc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Jh(e,t=hl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Yh(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 Qh(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=un(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const d=Or(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),m=Xh({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(qh({id:m,dedupKey:m,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:bc(a),preview:Wm(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return Jh(n)}function Zh(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function ex(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=hl}=e,a=o.useMemo(()=>Qh(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>Zh(a),[a]);return{notifications:a,unreadCount:i}}function tx({notifications:e,sendDaemonCommand:t}){const r=o.useCallback(i=>{const c=e.find(d=>d.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}}const sx=o.createContext(null);function rx(){return o.useContext(sx)}function hn(...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 nx(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 xn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=nx(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 ax(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 ox(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function bn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=ox(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,u)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${u}`:m==="/"||m==="\\"?`${c}${u}`:`${m.replace(/[\\/]+$/,"")}${c}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:typeof(m==null?void 0:m.path)=="string"&&m.path.trim()?m.path:l(i,m.name)})).sort((m,u)=>m.name.localeCompare(u.name)):[];return{path:i,directories:d}}function ix(e,t){const r={meshId:t.meshId||"",workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp"};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand)\s*\}\}/g,(n,a)=>r[a]||"")}function xl(e,t={}){const r=e==null?void 0:e.mcpConfig;return(r==null?void 0:r.mode)!=="manual"?null:{serverName:r.serverName||"adhdev-mesh",configFormat:r.format,configPathCommand:r.configPathCommand,requiresRestart:r.requiresRestart===!0,instructions:r.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:ix(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function cx(e){if(!e||typeof e!="object")return null;const t=e,r=typeof t.instructions=="string"?t.instructions:"",n=typeof t.template=="string"?t.template:"";return!r&&!n?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:r||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:n}}function Xt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function uo(e){return mr(e)||e.tabKey||e.routeId||null}function bl(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(t)return t;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=Pt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?uo(a):null}function lx(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function di(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ui(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function dx({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=di(n.workspacePath),l=e.find(m=>{var g,h,k,b;if(!m||m.type==="adhdev-daemon"||lx(m.daemonId||m.id)!==n.machineId||(or(m)?"cli":ks(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 p=di(m.workspace||m.runtimeWorkspaceLabel);return p?p===c:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((b=(k=(h=(g=m.activeChat)==null?void 0:g.messages)==null?void 0:h.at)==null?void 0:k.call(h,-1))==null?void 0:b.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const d=bl({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});d&&(a(null),r(d))},[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 ux({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=rx(),l=o.useCallback(async(h,k)=>bn(e,h,k),[e]),d=o.useCallback(async(h,k)=>{if(!k.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(h,"workspace_add",{path:k.trim()});return b!=null&&b.success?{ok:!0}:{ok:!1,error:(b==null?void 0:b.error)||"Could not save workspace"}}catch(b){return{ok:!1,error:b instanceof Error?b.message:"Could not save workspace"}}},[e]),m=o.useCallback(async(h,k,b)=>{var p;try{const y={ideType:k,enableCdp:!0};(p=b==null?void 0:b.workspacePath)!=null&&p.trim()&&(y.workspace=b.workspacePath.trim());const S=await e(h,"launch_ide",y);return!(S!=null&&S.success)&&(S==null?void 0:S.success)!==void 0?{ok:!1,error:(S==null?void 0:S.error)||"Could not launch IDE"}:(t({machineId:h,kind:"ide",providerType:k,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(y){return{ok:!1,error:y instanceof Error?y.message:"Could not launch IDE"}}},[e,t]),u=o.useCallback(async(h,k,b,p)=>{var S,j,A;const y=Date.now();try{const M={cliType:b};(S=p==null?void 0:p.workspacePath)!=null&&S.trim()?M.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(M.workspaceId=p.workspaceId),(j=p==null?void 0:p.resumeSessionId)!=null&&j.trim()&&(M.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(M.cliArgs=p.cliArgs),(A=p==null?void 0:p.initialModel)!=null&&A.trim()&&(M.initialModel=p.initialModel.trim());const w=await e(h,"launch_cli",M),v=(w==null?void 0:w.result)||w,B=(v==null?void 0:v.sessionId)||(v==null?void 0:v.id);return w!=null&&w.success&&B?(r(B),{ok:!0}):w!=null&&w.success?(t({machineId:h,kind:k,providerType:b,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:y}),{ok:!0}):{ok:!1,error:(w==null?void 0:w.error)||(v==null?void 0:v.error)||`Could not launch ${k.toUpperCase()} session`}}catch(M){return ui(M)?(t({machineId:h,kind:k,providerType:b,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:y}),{ok:!0}):{ok:!1,error:M instanceof Error?M.message:`Could not launch ${k.toUpperCase()} session`}}},[r,e,t]),f=o.useCallback(async h=>{var k;if(c!=null&&c.listMeshes)return c.listMeshes(h);if(!h)return[];try{const b=await e(h,"list_meshes",{}),p=(b==null?void 0:b.result)??b;if((p==null?void 0:p.success)===!1)throw new Error((p==null?void 0:p.error)||"Could not load meshes");return(Array.isArray(p==null?void 0:p.meshes)?p.meshes:Array.isArray((k=p==null?void 0:p.result)==null?void 0:k.meshes)?p.result.meshes:[]).map(S=>{var j;return{id:String((S==null?void 0:S.id)||""),name:String((S==null?void 0:S.name)||(S==null?void 0:S.id)||"Untitled mesh"),repoIdentity:(S==null?void 0:S.repoIdentity)||(S==null?void 0:S.repo_identity)||null,workspace:Array.isArray(S==null?void 0:S.nodes)&&S.nodes.length>0?String(((j=S.nodes[0])==null?void 0:j.workspace)||""):null,nodesCount:Array.isArray(S==null?void 0:S.nodes)?S.nodes.length:void 0,status:(S==null?void 0:S.status)||null}}).filter(S=>S.id)}catch(b){throw console.error("List meshes failed",b),b}},[c,e]),x=o.useCallback(async(h,k,b)=>{if(!k.trim())return{ok:!1,error:"Choose a mesh first."};if(c!=null&&c.launchMeshCoordinator)return c.launchMeshCoordinator(h,k,b);const p=Date.now();try{const y=await e(h,"launch_mesh_coordinator",{meshId:k.trim(),cliType:b.trim()||"claude-cli"}),S=(y==null?void 0:y.result)??y;if((S==null?void 0:S.success)===!1||(y==null?void 0:y.success)===!1){const A=String((S==null?void 0:S.code)||(y==null?void 0:y.code)||""),M=cx((S==null?void 0:S.meshCoordinatorSetup)||(S==null?void 0:S.manualSetup)||(y==null?void 0:y.meshCoordinatorSetup)||(y==null?void 0:y.manualSetup));return{ok:!1,error:(S==null?void 0:S.error)||(y==null?void 0:y.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:M}}const j=(S==null?void 0:S.sessionId)||(S==null?void 0:S.id);return j?r(j):t({machineId:h,kind:"cli",providerType:b,workspacePath:(S==null?void 0:S.workspace)||null,startedAt:p}),{ok:!0}}catch(y){return ui(y)?(t({machineId:h,kind:"cli",providerType:b,startedAt:p}),{ok:!0}):{ok:!1,error:y instanceof Error?y.message:"Could not launch mesh coordinator"}}},[c,r,e,t]),N=o.useCallback(async(h,k)=>{if(!h||!k)return[];try{const b=await e(h,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),p=(b==null?void 0:b.result)??b;return Array.isArray(p==null?void 0:p.sessions)?p.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),g=o.useCallback(async h=>{await il({conversation:n,mode:h,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:i})},[n,a,e,i]);return{handleBrowseMachineDirectory:l,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:f,handleLaunchMeshCoordinator:x,handleListMachineSavedSessions:N,setActiveCliViewMode:g}}function mx(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":return!0;case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function fx(e,t,r=Date.now()){return!e||!mx(t)?null:{tabKey:e,nonce:r}}function px({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,d]=o.useState(null),[m,u]=o.useState(null),f=o.useMemo(()=>{var k,b;if(!e){if(l){const p=t.find(y=>y.tabKey===l);if(p)return p}return r[0]}const h=n[a];if(h){const p=t.find(y=>y.tabKey===h);if(p)return p}return((k=i[a])==null?void 0:k[0])||((b=i[0])==null?void 0:b[0])},[t,l,a,n,i,e,r]),x=o.useCallback(h=>{d(h)},[]),N=o.useCallback(h=>{d(h.tabKey),c(k=>{const b=new URLSearchParams(k),p=Fm(h);return p?b.set("activeTab",p):b.delete("activeTab"),b},{replace:!0})},[c]),g=o.useCallback((h,k)=>{const b=fx(h,k);b&&u(b)},[]);return{activeConv:f,openDesktopConversation:N,requestScrollToBottom:g,scrollToBottomRequest:m,setDesktopActiveTab:x}}function hx(e){const t=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:r===e.autoReadKey?r:null}:r===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:r}:{shouldSchedule:!0,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!r,nextPendingKey:null}}function xx(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,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 bx({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),d=o.useRef(null);o.useEffect(()=>{const m=()=>{c.current&&(clearTimeout(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),i.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const u=Xr(e,r),f=xx({tabKey:e.tabKey,historySessionId:mr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:cs(e),liveState:u}),x=f.autoReadKey,N=hx({autoReadKey:x,shouldMarkSeen:f.shouldMarkSeen,completedKey:a.current,pendingKey:i.current});if(!f.shouldMarkSeen){N.shouldCancelPending&&m(),a.current=x;return}if(!N.shouldSchedule)return;N.shouldCancelPending&&m();const g=()=>{if(document.visibilityState!=="visible"||a.current===x)return;a.current=x,i.current=null,c.current=null,l.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const k=f.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:k,completionMarker:f.completionMarker}).catch(()=>{})};if(i.current=N.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(g,1500);const k=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};d.current=k,document.addEventListener("visibilitychange",k);return}const h=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(g,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,r,n]),o.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function On(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const r=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(r)?r:""}function gx({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:d}){var I;const[m,u]=o.useState(!1),[f,x]=o.useState([]),[N,g]=o.useState(()=>gt()),[h,k]=o.useState(!1),[b,p]=o.useState(null),y=o.useRef(null),S=o.useMemo(()=>r||t||e,[e,r,t]),j=!!S&&et(S)&&!Qe(S),A=o.useMemo(()=>{if(!S||!j)return null;const W=S.daemonId||S.routeId||"",P=Bt(S),$=On(S);return`${W}:${P}:${S.providerSessionId||""}:${$}`},[S,j]),M=o.useMemo(()=>!S||!j?"":On(S),[S,j]),{isCreatingChat:w,isRefreshingHistory:v,handleSwitchSession:B,handleNewChat:_,handleRefreshHistory:T}=pl({sendDaemonCommand:a,activeConv:S,chats:(I=n.find(W=>W.id===(S==null?void 0:S.routeId)))==null?void 0:I.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),D=o.useCallback(()=>{u(!0)},[]),K=o.useCallback(()=>{u(!1)},[]),L=o.useCallback(async()=>{if(!(!S||!j||h)){k(!0);try{const W=S.daemonId||S.routeId,P=Bt(S),$=On(S),H=await a(W,"list_saved_sessions",{agentType:P,providerType:P,kind:"cli",limit:50,...S.providerSessionId?{providerSessionId:S.providerSessionId}:{},...$?{workspace:$}:{}}),Q=(H==null?void 0:H.result)??H;x(Array.isArray(Q==null?void 0:Q.sessions)?Q.sessions:[])}catch(W){console.error("Refresh saved sessions failed",W),x([])}finally{k(!1)}}},[S,h,j,a]);o.useEffect(()=>{if(!m){y.current=null;return}if(!j){y.current=null,x([]),k(!1);return}!A||h||y.current!==A&&(y.current=A,L())},[L,m,h,j,A]);const C=o.useCallback(async W=>{if(!S||!j||!W.providerSessionId||!W.workspace)return;const P=S.daemonId||S.routeId,$=Bt(S);try{p(W.providerSessionId);const H=await a(P,"launch_cli",{cliType:$,dir:W.workspace,resumeSessionId:W.providerSessionId,initialModel:dc(W.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Q=(H==null?void 0:H.result)??H,xe=typeof(Q==null?void 0:Q.sessionId)=="string"?Q.sessionId:typeof(Q==null?void 0:Q.id)=="string"?Q.id:"";xe&&d(ie=>{const se=new URLSearchParams(ie);return se.set("activeTab",xe),se},{replace:!0}),K()}catch(H){console.error("Resume saved session failed",H)}finally{p(null)}},[K,S,j,a,d]);return{historyModalOpen:m,openHistoryModal:D,closeHistoryModal:K,historyTargetConv:S,isSavedSessionHistoryTarget:j,isHistoryCreatingChat:w,isHistoryRefreshingHistory:v,handleHistorySwitchSession:B,handleHistoryNewChat:_,handleHistoryRefresh:T,savedHistorySessions:f,savedHistoryFilters:N,setSavedHistoryFilters:g,missingWorkspaceResumePath:M,isSavedHistoryLoading:h,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:L,handleResumeSavedHistorySession:C}}function yx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[d,m]=o.useState(null),[u,f]=o.useState(null),x=o.useMemo(()=>{if(e||!n)return null;const b=l(n);return b&&!et(b)&&!Qe(b)?b:null},[e,n,l]),N=o.useMemo(()=>{const b=d==null?void 0:d.routeId;if(!b)return null;const p=d!=null&&d.tabKey?i.find(y=>y.tabKey===d.tabKey):a?i.find(y=>y.tabKey===a):null;return(p==null?void 0:p.routeId)===b?p:Pt(i,b)},[i,d,a]),g=o.useMemo(()=>{if(N)return c.find(b=>b.id===N.routeId)},[c,N]);o.useEffect(()=>{x&&(m({routeId:x.routeId,tabKey:Ko(x)}),f(x),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,x]);const h=o.useCallback(b=>{b&&(m({routeId:b.routeId,tabKey:Ko(b)}),f(b))},[]),k=o.useCallback(()=>{m(null),f(null)},[]);return{remoteDialogConv:N,remoteDialogIdeEntry:g,remoteDialogActiveConv:u,setRemoteDialogActiveConv:f,openRemoteDialog:h,closeRemoteDialog:k}}function vx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:f,remoteDialogActiveConv:x,setRemoteDialogActiveConv:N,openRemoteDialog:g,closeRemoteDialog:h}=yx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[k,b]=o.useState(!1),[p,y]=o.useState(null),S=o.useCallback(async M=>{const w=M||d;!w||!et(w)&&!Qe(w)||(y(w),b(!0))},[d]),j=o.useCallback(()=>{b(!1),y(null)},[]),A=o.useCallback(async M=>{const w=p||d;if(!w||!et(w)&&!Qe(w)){j();return}b(!1);try{const v=Bt(w),B=w.routeId||w.daemonId||"";await m(B,"stop_cli",{cliType:v,targetSessionId:w.sessionId,mode:M})}catch(v){console.error("Stop CLI failed:",v)}finally{y(null)}},[d,j,p,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:f,remoteDialogActiveConv:x,setRemoteDialogActiveConv:N,openRemoteDialog:g,closeRemoteDialog:h,cliStopDialogOpen:k,cliStopTargetConv:p,requestCliStop:S,cancelCliStop:j,confirmCliStop:A}}function gl({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:i=!1}){var p,y;const c=Ds(),l=xs(e),d=i?null:xc(e),m=!i&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!i&&e.streamSource==="agent-stream"&&!!e.agentName,f=!i&&!u&&(e.transport==="pty"||e.transport==="acp"),x=As(e),N=Om(e),g=(p=e.settings)==null?void 0:p.meshNodeFor,h=(y=e.settings)==null?void 0:y.meshCoordinatorFor;if(!m&&!u&&!f&&!d&&!g&&!h)return null;const k=o.useCallback(()=>{if(n){n();return}l&&c("/dashboard",{state:{openMachineId:l}})},[l,c,n]),b=o.useCallback(()=>{if(r){r();return}const S=uo(e);S&&c(Xt(S))},[e,c,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[m&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:b,title:N,children:[s.jsx(Tt,{size:12}),s.jsx("span",{children:N})]}):s.jsxs("span",{className:"conversation-meta-chip",title:N,children:[s.jsx(Tt,{size:12}),s.jsx("span",{children:N})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Ms,{size:12}),s.jsx("span",{children:x})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Ms,{size:12}),s.jsx("span",{children:x})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:k,title:d,children:[s.jsx(Ot,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(Ot,{size:12}),s.jsx("span",{children:d})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh Coordinator",children:[s.jsx(Ot,{size:12}),s.jsx("span",{children:"Coordinator"})]}),g&&s.jsxs("span",{className:"conversation-meta-chip",title:"Managed by Coordinator",children:[s.jsx(Ot,{size:12}),s.jsx("span",{children:"Mesh Node"})]})]})}function Fn(e,t=!0){return(e??!0)&&t}const mo=o.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u=null,handleFocusAgent:f,isFocusingAgent:x,actionLogs:N,userName:g,scrollToBottomRequestNonce:h,isInputActive:k=!0,isVisible:b=!0}){const p=n,y=!n,S=Fn(b,p),j=Fn(b,y),A=Fn(b),M=sl(t),w=M.status||M.modalMessage||M.modalButtons?{...t,...M.status?{status:M.status}:{},...M.modalMessage!==void 0?{modalMessage:M.modalMessage}:{},...M.modalButtons!==void 0?{modalButtons:M.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(oc,{activeConv:w,onModalButton:c}),s.jsx(gl,{conversation:w,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),w.transport!=="pty"&&w.transport!=="acp"&&w.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(ar,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:l,children:"Relaunch with CDP"})]})}):null,w.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:p?"visible":"hidden",pointerEvents:p?"auto":"none"},children:s.jsx(Zf,{activeConv:w,clearToken:r,terminalRef:i,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,isVisible:S,isInputActive:k&&S})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:y?"visible":"hidden",pointerEvents:y?"auto":"none"},children:s.jsx(va,{activeConv:w,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:x,actionLogs:N,userName:g,scrollToBottomRequestNonce:h,isInputActive:k&&j,isVisible:j})})]}):s.jsx(va,{activeConv:w,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:x,actionLogs:N,userName:g,scrollToBottomRequestNonce:h,isInputActive:k&&A,isVisible:A})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function wx({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:f,onOpenHistory:x,onOpenRemote:N,onStopCli:g,cliViewMode:h,onSetCliViewMode:k,handleSendChat:b,handleFocusAgent:p,handleModalButton:y,handleRelaunch:S}){const j=o.useRef(null),A=et(e)&&!t,M=A&&h==="terminal",w=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${w} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(Pa,{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:ct(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(gl,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>f(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[A&&h&&s.jsx(Ja,{mode:h,onChange:k,compact:!0}),A&&g&&s.jsx("button",{onClick:()=>{g(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(yt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",children:s.jsx(Da,{size:14})}),!t&&!A&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>N(e),type:"button",children:s.jsx(Tt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(mo,{activeConv:e,clearToken:0,isCliTerminal:M,ideEntry:n,terminalRef:j,handleModalButton:y,handleRelaunch:S,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:p,isFocusingAgent:d,actionLogs:a,userName:i})})]})}const Hn={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 jx(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function yl(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(jx())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Hn[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:Hn[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Hn[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 vl({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Tt},{key:"chats",label:"Chats",icon:Ut}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon: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 Ir({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function gs({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function zs({icon:e,title:t,subtitle:r,children:n}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function kx({conversation:e,onCancel:t,onConfirm:r}){const n=ct(e),a=fs(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"fade-in relative w-full sm:w-[min(92vw,420px)] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] border border-border-subtle bg-bg-primary shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),s.jsx("div",{className:"mt-1 text-[13px] leading-relaxed text-text-muted",children:"This only collapses the chat locally. You can restore it from Hidden tabs."})]}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary text-text-secondary transition-colors hover:bg-surface-primary hover:text-text-primary",onClick:t,"aria-label":"Cancel hide chat",children:s.jsx(yt,{size:16})})]}),s.jsx("div",{className:"px-4 py-4",children:s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[s.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),s.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border-subtle bg-bg-secondary px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))]",children:[s.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:t,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function Rr({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onCollectChatDebugBundle:i}){const c=t==="needs_attention"||t==="task_complete",l=t==="working",d=t==="earlier",m=t==="task_complete",{isReconnecting:u,isConnecting:f}=Es(e.conversation),x=ct(e.conversation),N=fs(e.conversation),g=Ec(e.conversation,{requiresAction:t==="needs_attention"}),h=c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":l?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":d?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",k=c?"bg-accent-primary shadow-glow":l?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":d?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",b=d?"text-text-secondary":"text-text-primary",p=d?"text-text-muted":"text-text-secondary",y=d?"text-text-secondary opacity-80":"text-text-muted",S=d?"text-text-muted opacity-80":"text-text-muted",j=!l&&!m,A="text-[color:var(--status-warning)]",M=w=>{if(!i)return;w.preventDefault(),w.stopPropagation();const v=i==null?void 0:i(e.conversation);Promise.resolve(v).catch(B=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",B)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${h}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[c||l?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${k}`,style:c?{color:"var(--accent-on-primary)"}:void 0,children:r(x)}),a&&s.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:w=>{w.preventDefault(),w.stopPropagation(),a()},"aria-label":`Hide ${x}`,title:"Hide conversation",children:[s.jsx(Ea,{size:11}),s.jsx("span",{children:"Hide"})]})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:M,type:"button",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${b}`,children:x}),j&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${S}`,children:ac(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${p}`,children:[s.jsx("span",{className:"truncate",children:N}),s.jsx(Rs,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),u?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${A} animate-pulse`,children:"Reconnecting…"})]}):f?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):g==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:A,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,children:e.preview})]}),c&&!m&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),m&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),l&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]})},e.conversation.tabKey)}function mi({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}})})}function Sx({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:f,onHideConversation:x,onOpenNewSession:N,onOpenMachine:g,onOpenSettings:h,onSectionChange:k,wsStatus:b="connected",isStandalone:p=!1,onCollectChatDebugBundle:y}){const[S,j]=o.useState(null),A=b==="disconnected"||b==="reconnecting"||b==="offline"||b==="auth_failed",M=c.length>0,w=t.length>0||r.length>0||n.length>0||a.length>0,v=e==="machines"?"Machines":"Chats",B=p?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",_=p?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",T=o.useCallback(async L=>{const C=Is(L);if(!C)return;const I=Array.isArray(L.messages)?L.messages:[],W=jc({activeConv:L,visibleMessages:I,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:I.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),P=await m(C,"get_chat_debug_bundle",{...ss(L),delivery:"daemon_file",frontendSnapshot:W}),$=Zr(P),H=Nc($),Q=await Sc(H);Q==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),nt.showToast(kc($,{locatorCopyStatus:Q}),Q==="failed"?"warning":"success")},[d,m]),D=y||T,K=o.useCallback(()=>{S&&(x==null||x(S),j(null))},[S,x]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${B}`,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:v}),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(ln,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:h,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(cn,{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] ${_}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:A?s.jsx(zs,{icon:s.jsx(mi,{}),title:b==="offline"?"Network offline":b==="auth_failed"?"Session expired":"Reconnecting",subtitle:b==="offline"?"Waiting for network…":b==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(zs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:p?"Waiting for your daemon":"Connect your machines",subtitle:p?"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:!p&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(yl,{})})}):s.jsx(gs,{children:c.map((L,C)=>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] ${C>0?"border-t border-border-subtle/70":""}`,onClick:()=>g(L.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(L.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:L.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:L.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[L.unread," new"]}):L.total>0?`${L.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:L.subtitle}),L.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[L.total," chat",L.total!==1?"s":"",L.unread>0?` · ${L.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},L.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(Ir,{title:"Needs attention",className:"mb-0"}),s.jsx(gs,{children:t.map((L,C)=>s.jsx("div",{className:C>0?"border-t border-border-subtle/70":"",children:s.jsx(Rr,{item:L,type:"needs_attention",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>j(L.conversation):void 0,onCollectChatDebugBundle:D})},L.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(Ir,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(gs,{children:r.map((L,C)=>s.jsx("div",{className:C>0?"border-t border-border-subtle/70":"",children:s.jsx(Rr,{item:L,type:"task_complete",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>j(L.conversation):void 0,onCollectChatDebugBundle:D})},L.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(Ir,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(gs,{children:n.map((L,C)=>s.jsx("div",{className:C>0?"border-t border-border-subtle/70":"",children:s.jsx(Rr,{item:L,type:"working",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>j(L.conversation):void 0,onCollectChatDebugBundle:D})},L.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(Ir,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(gs,{children:a.map((L,C)=>s.jsx("div",{className:C>0?"border-t border-border-subtle/70":"",children:s.jsx(Rr,{item:L,type:"earlier",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>j(L.conversation):void 0,onCollectChatDebugBundle:D})},L.conversation.tabKey))}):w?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):A?s.jsx(zs,{icon:s.jsx(mi,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):M?s.jsx(zs,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Ut,{size:20})}),title:"No conversations yet",subtitle:Kc,children:N&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:N,"aria-label":Et,title:Et,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:Et})]})}):s.jsx(zs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(gs,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[i.length," collapsed ",i.length===1?"conversation":"conversations"]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:f,children:"Restore all"})]})})})]}),e==="chats"&&N&&w&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:N,"aria-label":Et,title:Et,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),S&&s.jsx(kx,{conversation:S,onCancel:()=>j(null),onConfirm:K}),s.jsx(vl,{section:e,onSectionChange:k})]})}function Nx(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 wl(e){const t=[e.workspace||"Workspace unknown"],r=ms(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Nx(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function gn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:d,onConfirm:m}){const[u,f]=o.useState(r);o.useEffect(()=>{f(r)},[r]);const x=ax(r),N=u.trim();return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:s.jsx(yt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!x||a||d(x)},disabled:!x||a,children:[s.jsx(Pa,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:g=>f(g.target.value),onKeyDown:g=>{g.key!=="Enter"||!N||a||(g.preventDefault(),d(N))},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:()=>{!N||a||d(N)},disabled:!N||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(g=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(g.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(us,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:g.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:g.path})]})]},g.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(N||r),disabled:!N&&!r||a,children:c})]})]})})}function fo({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:f,showModelInput:x,modelValue:N,onModelChange:g,historyProviderNode:h,onConfirm:k,onCancel:b}){const p=n==null?void 0:n.find(y=>y.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:b,"aria-label":"Close launch confirmation",children:s.jsx(yt,{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:y=>i(y.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(y=>s.jsx("option",{value:y.key,children:y.label},y.key))}),(p==null?void 0:p.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:p.description})]}),h,r.map(y=>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:y.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:y.value})]},`${y.label}:${y.value}`)),x&&g&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:N||"",onChange:y=>g(y.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),m&&f&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:y=>f(y.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:b,disabled:d,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:k,disabled:d,children:[s.jsx(Ba,{size:14}),d?l:c]})]})]})})}function fi(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ls(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 d of t.workspaces||[])i.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${fi(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(d=>d.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:fi(c),description:c,workspaceId:null,workspacePath:c}),n){const d=`saved:${n}`;if(i.some(m=>m.key===d))return{options:i,selectedKey:d}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Cx(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Tx(e){return[Cx(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Mx(e){return e.lastLaunchedAt?dn(e.lastLaunchedAt):""}function jl(e){return{metaText:Tx(e),updatedLabel:Mx(e)}}function Un(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Ax({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var tt,ut,ft,pt;const c=ur(),[l,d]=o.useState(!1),m=(((tt=e.detectedIdes)==null?void 0:tt.length)||0)>0,u=o.useMemo(()=>(e.workspaces||[]).map(Ne=>({id:Ne.id,path:Ne.path,label:Ne.label})),[e]),f=e.defaultWorkspaceId||null,[x,N]=o.useState(f||((ut=u[0])==null?void 0:ut.id)||""),[g,h]=o.useState(""),[k,b]=o.useState(""),[p,y]=o.useState([]),[S,j]=o.useState(!1),[A,M]=o.useState(""),[w,v]=o.useState(!1),[B,_]=o.useState(Un(m,t.length,r.length)),T=o.useRef(null),[D,K]=o.useState(null),L=o.useRef("__home__"),[C,I]=o.useState("__home__"),[W,P]=o.useState(""),[$,H]=o.useState(""),[Q,xe]=o.useState(""),[ie,se]=o.useState([]),[be,we]=o.useState(()=>gt().textQuery),[ge,J]=o.useState(()=>gt().workspaceQuery),[ce,ye]=o.useState(()=>gt().modelQuery),[ae,de]=o.useState(()=>gt().resumableOnly),[je,fe]=o.useState(()=>gt().sortMode),[pe,te]=o.useState(!1),[me,oe]=o.useState(!1),Y=o.useRef(null),V=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const le=x==="__custom__"?g.trim():((ft=u.find(Ne=>Ne.id===x))==null?void 0:ft.path)||"",ke=x==="__custom__"&&!!le&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ee=x!=="__custom__"&&((pt=u.find(Ne=>Ne.id===x))==null?void 0:pt.path)||"",Pe=o.useMemo(()=>(e.recentLaunches||[]).map(Ne=>Ne.workspace),[e]),$e=o.useCallback(async Ne=>{j(!0),M("");try{const Ue=await a(Ne);b(Ue.path),h(Ue.path),y(Ue.directories)}catch(Ue){M(Ue instanceof Error?Ue.message:"Could not load folder")}finally{j(!1)}},[a]),Oe=o.useCallback(()=>{var Ue;N("__custom__"),v(!0);const Ne=xn(e.platform,hn(g.trim(),ee,Pe,e.defaultWorkspacePath,(Ue=u.find(Xe=>Xe.id===f))==null?void 0:Ue.path,u.map(Xe=>Xe.path)));$e(Ne)},[g,f,$e,Pe,ee,e.platform,u]),He=o.useCallback(Ne=>{if(Ne!=null&&Ne.workspaceId){N(Ne.workspaceId),h("");return}if(Ne!=null&&Ne.workspacePath){N("__custom__"),h(Ne.workspacePath);return}N(""),h("")},[]),O=o.useCallback(Ne=>{if(N(Ne),Ne==="__custom__"){Oe();return}h("")},[Oe]),Ce=o.useCallback(Ne=>{N("__custom__"),h(Ne)},[]),Te=o.useCallback((Ne,Ue)=>{T.current=Ue,L.current=Ne.selectedWorkspaceKey||"__home__",I(Ne.selectedWorkspaceKey||"__home__"),P(Ne.initialArgs||""),H(Ne.initialModel||""),xe(""),se([]);const Xe=Ne.providerType?`${e.id}:${Ne.providerType}`:null;if(dp(V.current,Xe)){const Ve=gt();we(Ve.textQuery),J(Ve.workspaceQuery),ye(Ve.modelQuery),de(Ve.resumableOnly),fe(Ve.sortMode)}V.current=Xe,K(Ne),Ne.providerType&&i&&(te(!0),i(Ne.providerType).then(Ve=>se(Ve||[])).catch(Ve=>console.warn("Failed to load saved sessions",Ve)).finally(()=>te(!1)))},[i,e.id]),Re=o.useMemo(()=>Wc(ie,{textQuery:be,workspaceQuery:ge,modelQuery:ce,resumableOnly:ae,sortMode:je}),[ce,ae,ie,je,be,ge]);o.useEffect(()=>{Q&&(Re.some(Ne=>Ne.providerSessionId===Q)||xe(""))},[Re,Q]);const Be=o.useCallback(()=>{T.current&&(oe(!0),T.current().finally(()=>{T.current=null,oe(!1),K(null)}))},[]),Fe=o.useCallback(()=>{T.current=null,K(null)},[]),Ye=o.useCallback(Ne=>{L.current=Ne,I(Ne)},[]);return o.useEffect(()=>{var Ne;Y.current!==e.id&&(Y.current=e.id,N(f||((Ne=u[0])==null?void 0:Ne.id)||"__custom__"),h(""),b(""),y([]),M(""),v(!1),we(gt().textQuery),J(gt().workspaceQuery),ye(gt().modelQuery),de(gt().resumableOnly),fe(gt().sortMode),V.current=null,_(Un(m,t.length,r.length)))},[r.length,t.length,f,m,e.id,u]),o.useEffect(()=>{var Ne;x!=="__custom__"&&(x&&u.some(Ue=>Ue.id===x)||N(f||((Ne=u[0])==null?void 0:Ne.id)||"__custom__"))},[f,x,u]),o.useEffect(()=>{B==="ide"&&m||B==="cli"&&t.length>0||B==="acp"&&r.length>0||_(Un(m,t.length,r.length))},[B,r.length,t.length,m]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:f,workspaceChoice:x,customWorkspacePath:g,browseCurrentPath:k,browseDirectories:p,browseBusy:S,browseError:A,browseDialogOpen:w,activeLauncherKind:B,launchConfirm:D,launchConfirmWorkspaceKeyRef:L,launchConfirmWorkspaceKey:C,launchConfirmArgs:W,launchConfirmModel:$,launchConfirmResumeId:Q,launchConfirmSavedSessions:ie,launchConfirmTextFilter:be,launchConfirmWorkspaceFilter:ge,launchConfirmModelFilter:ce,launchConfirmResumableOnly:ae,launchConfirmSortMode:je,filteredLaunchConfirmSavedSessions:Re,launchConfirmSessionsLoading:pe,launchConfirmBusy:me,resolvedWorkspacePath:le,canCreateMissingWorkspace:ke,openBrowseDialog:Oe,loadBrowsePath:$e,handleWorkspaceChoiceChange:O,chooseCustomWorkspacePath:Ce,setCustomWorkspacePath:h,setBrowseDialogOpen:v,setActiveLauncherKind:_,openLaunchConfirm:Te,handleConfirmLaunch:Be,closeLaunchConfirm:Fe,setWorkspaceSelectionFromOption:He,setLaunchConfirmWorkspaceKeyAndSync:Ye,setLaunchConfirmArgs:P,setLaunchConfirmModel:H,setLaunchConfirmResumeId:xe,setLaunchConfirmTextFilter:we,setLaunchConfirmWorkspaceFilter:J,setLaunchConfirmModelFilter:ye,setLaunchConfirmResumableOnly:de,setLaunchConfirmSortMode:fe}}function Ix({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:d,section:m,showBottomNav:u,onBack:f,onSectionChange:x,onOpenConversation:N,onOpenRecent:g,onOpenMachineDetails:h,onMachineUpgrade:k,onLaunchDetectedIde:b,onAddWorkspace:p,onBrowseDirectory:y,onLaunchWorkspaceProvider:S,onListSavedSessions:j}){const A=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",M=r.slice(0,4),w=t.slice(0,3),v=Ax({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:y,onListSavedSessions:j}),B=o.useMemo(()=>M.map(C=>{const{metaText:I,updatedLabel:W}=jl(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:I,updatedLabel:W,onClick:()=>{const{options:P,selectedKey:$}=ls({machine:{workspaces:v.workspaceRows,defaultWorkspaceId:v.defaultWorkspaceId},currentWorkspacePath:C.workspace});v.openLaunchConfirm({title:C.kind==="ide"?ns("restart-ide",C.label):C.providerSessionId?eo(C.label):ns("start-fresh",C.label),description:C.kind==="ide"?as("restart-ide"):C.providerSessionId?to():as("start-fresh"),confirmLabel:C.kind==="ide"?Ls("restart-ide"):C.providerSessionId?tn(!0):Ls("start-fresh"),busyLabel:C.kind==="ide"?_s("restart-ide"):C.providerSessionId?Qa(!0):_s("start-fresh"),workspaceOptions:P,selectedWorkspaceKey:$,details:[{label:"Mode",value:A(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const H=P.find(Q=>Q.key===v.launchConfirmWorkspaceKeyRef.current);v.setWorkspaceSelectionFromOption(H),await g({...C,workspace:(H==null?void 0:H.workspacePath)??null})})}}}),[v,g,M]),_=o.useMemo(()=>w.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:ct(C.conversation),secondary:Yf(C.conversation,{timestampLabel:C.timestamp?ac(C.timestamp):null}),unread:C.unread,onClick:()=>N(C.conversation)})),[N,w]),T=v.showAllRecent?B:B.slice(0,4),D=B.length>0,K=_.length>0,L=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${L} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:f,type:"button","aria-label":"Back",children:s.jsx(Pa,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Ct(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[K&&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:_.map(C=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),D&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:T.map(C=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:C.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:C.primary}),C.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),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:()=>v.setShowAllRecent(C=>!C),children:v.showAllRecent?"Show fewer":`Show ${B.length-4} more`})})]}),(v.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:v.workspaceChoice,onChange:C=>v.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:v.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[v.workspaceRows.map(C=>s.jsxs("option",{value:C.id,children:[C.id===v.defaultWorkspaceId?"⭐ ":"",mn(C.path,C.label)||C.path]},C.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),v.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(us,{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:v.resolvedWorkspacePath||v.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:v.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:()=>{v.resolvedWorkspacePath&&p(v.resolvedWorkspacePath)},disabled:!v.resolvedWorkspacePath||v.browseBusy,children:"Save as workspace"})]})]}),v.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:v.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[v.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${v.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:()=>v.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${v.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:()=>v.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${v.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:()=>v.setActiveLauncherKind("acp"),children:"ACP"})]}),v.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:v.activeLauncherKind==="ide"?"Choose an IDE":v.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:v.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(C=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:I,selectedKey:W}=ls({machine:{workspaces:v.workspaceRows,defaultWorkspaceId:v.defaultWorkspaceId},currentWorkspaceId:v.workspaceChoice!=="__custom__"?v.workspaceChoice:null,currentWorkspacePath:v.resolvedWorkspacePath});v.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:I,selectedWorkspaceKey:W,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const P=I.find($=>$.key===v.launchConfirmWorkspaceKeyRef.current);v.setWorkspaceSelectionFromOption(P),b(C.type,{workspacePath:(P==null?void 0:P.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:v.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(v.activeLauncherKind==="cli"?n:a).map(C=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const I=v.activeLauncherKind==="cli"?"cli":"acp",{options:W,selectedKey:P}=ls({machine:{workspaces:v.workspaceRows,defaultWorkspaceId:v.defaultWorkspaceId},currentWorkspaceId:v.workspaceChoice!=="__custom__"?v.workspaceChoice:null,currentWorkspacePath:v.resolvedWorkspacePath});v.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${I.toUpperCase()}`,workspaceOptions:W,selectedWorkspaceKey:P,details:[{label:"Mode",value:I.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:I==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const $=W.find(H=>H.key===v.launchConfirmWorkspaceKeyRef.current);v.setWorkspaceSelectionFromOption($),S(I,C.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.workspacePath)??null,args:v.launchConfirmArgs,model:v.launchConfirmModel,resumeSessionId:v.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:v.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),l.message&&s.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,v.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:()=>p(v.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:k,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:h,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),v.browseDialogOpen&&s.jsx(gn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:v.browseCurrentPath,directories:v.browseDirectories,busy:v.browseBusy,error:v.browseError,confirmLabel:"Use this folder",onClose:()=>v.setBrowseDialogOpen(!1),onNavigate:C=>{v.loadBrowsePath(C)},onConfirm:C=>{v.chooseCustomWorkspacePath(C),v.setBrowseDialogOpen(!1)}}),v.launchConfirm&&s.jsx(fo,{title:v.launchConfirm.title,description:v.launchConfirm.description,details:v.launchConfirm.details,workspaceOptions:v.launchConfirm.workspaceOptions,selectedWorkspaceKey:v.launchConfirmWorkspaceKey,onWorkspaceChange:v.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:v.launchConfirm.providerType?tn(!!v.launchConfirmResumeId):v.launchConfirm.confirmLabel,busyLabel:v.launchConfirm.providerType?void 0:v.launchConfirm.busyLabel,busy:v.launchConfirmBusy,showArgsInput:v.launchConfirm.showArgsInput,argsValue:v.launchConfirmArgs,onArgsChange:v.setLaunchConfirmArgs,showModelInput:v.launchConfirm.showModelInput,modelValue:v.launchConfirmModel,onModelChange:v.setLaunchConfirmModel,historyProviderNode:v.launchConfirm.providerType&&(v.launchConfirmSessionsLoading||v.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"}),v.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:Za()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:v.launchConfirmTextFilter,onChange:C=>v.setLaunchConfirmTextFilter(C.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:v.launchConfirmWorkspaceFilter,onChange:C=>v.setLaunchConfirmWorkspaceFilter(C.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:v.launchConfirmModelFilter,onChange:C=>v.setLaunchConfirmModelFilter(C.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),s.jsxs("select",{value:v.launchConfirmSortMode,onChange:C=>v.setLaunchConfirmSortMode(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.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:v.launchConfirmResumableOnly,onChange:C=>v.setLaunchConfirmResumableOnly(C.target.checked),disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:v.launchConfirmResumeId,onChange:C=>v.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:fp()}),v.filteredLaunchConfirmSavedSessions.map(C=>s.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]}),!v.launchConfirmSessionsLoading&&v.launchConfirmSavedSessions.length>0&&v.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),v.launchConfirmResumeId&&(()=>{const C=v.filteredLaunchConfirmSavedSessions.find(W=>W.providerSessionId===v.launchConfirmResumeId);if(!C)return null;const I=wl(C);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:I.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:I.providerSessionId}),s.jsx("div",{className:"mt-1",children:I.metaLine}),I.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:I.updatedLabel}),I.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:I.preview})]})})()]}),onConfirm:v.handleConfirmLaunch,onCancel:v.closeLaunchConfirm}),u&&s.jsx(vl,{section:m,onSectionChange:x})]})}function Fr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Rx(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:Fr(e)}function Lx(e){var r;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":"Offline"}function _x(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:ms(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,d,m,u;const a=or(n)?"cli":ks(n)?"acp":"ide",i=ms(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(or(n)?n.cliName||n.type:ks(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:ks(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((u=(m=(d=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:d.at)==null?void 0:m.call(d,-1))==null?void 0:u.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Px(e,t){const r=new Map;for(const n of t){const a=xs(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((f,x)=>x.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=ha(n),d=a.filter(f=>f.unread||f.requiresAction).length,m=Lx(n),u=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Ct(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,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 Dx(e){return e==="chat"}function Lr(e,t){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function Ex({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:N,setSelectedTabKey:g,setScreen:h,setSelectedMachineId:k,setSection:b,setMachineBackTarget:p,resetMachineAction:y}){const S=o.useRef(null),j=o.useCallback(A=>{if(!(A!=null&&A.sessionId))return;const M=Xr(A,c),w=Math.max(Date.now(),cs(A),M.lastUpdated||0);Lr("mark_read:start",{tabKey:A.tabKey,sessionId:A.sessionId,displayPrimary:ct(A),inboxBucket:M.inboxBucket,unread:M.unread,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,activityAt:cs(A),readAt:w}),l(xs(A)||A.routeId,"mark_session_seen",{sessionId:A.sessionId,providerSessionId:A.providerSessionId,seenAt:w,completionMarker:M.completionMarker}).then(v=>{Lr("mark_read:result",{tabKey:A.tabKey,sessionId:A.sessionId,result:v})}).catch(v=>{Lr("mark_read:error",{tabKey:A.tabKey,sessionId:A.sessionId,error:v instanceof Error?v.message:String(v)})})},[c,l]);return o.useEffect(()=>{var M;if(!n){Dx(i)&&h("inbox"),g(((M=e[0])==null?void 0:M.tabKey)||null),S.current=null;return}if(i!=="chat"){S.current=null;return}const A=`${n.tabKey}:${n.sessionId||""}`;S.current!==A&&(S.current=A,j(n))},[e,j,i,n,h,g]),o.useEffect(()=>{if(!d)return;const A=e.find(M=>M.tabKey===d);A&&(g(A.tabKey),h("chat"),m==null||m())},[e,m,d,h,g]),o.useEffect(()=>{if(!u)return;const A=t.find(M=>M.id===u);A&&(k(A.id),y(),b("machines"),p("inbox"),h("machine"),f==null||f())},[t,f,u,y,p,h,b,k]),o.useEffect(()=>{x&&(b(x),h("inbox"),N==null||N())},[N,x,h,b]),o.useEffect(()=>{const A=r.filter(M=>M.inboxBucket==="task_complete"||M.unread);A.length!==0&&Lr("inbox_state",{screen:i,selectedTabKey:a,items:A.map(M=>{const w=Xr(M.conversation,c);return{liveState:w,tabKey:M.conversation.tabKey,sessionId:M.conversation.sessionId,displayPrimary:ct(M.conversation),serverBucket:w.inboxBucket,computedBucket:M.inboxBucket,serverUnread:w.unread,computedUnread:M.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:cs(M.conversation)}})})},[r,c,i,a]),{markConversationRead:j}}function $x(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function pi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Bx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Kx({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[d,m]=o.useState(null),u=o.useCallback(()=>{i("idle"),l(""),m(null)},[]),f=o.useCallback(async(p,y,S)=>{var j;try{i("loading"),l(`Launching ${y}…`);const A={ideType:y,enableCdp:!0};(j=S==null?void 0:S.workspacePath)!=null&&j.trim()&&(A.workspace=S.workspacePath.trim()),await e(p,"launch_ide",A),i("done"),l(`${y} launch requested`)}catch(A){i("error"),l(A instanceof Error?A.message:"Launch IDE failed"),console.error("Launch IDE failed",A)}},[e]),x=o.useCallback(async(p,y,S)=>{if(y.trim())try{i("loading"),l(S!=null&&S.createIfMissing?"Creating folder…":"Saving workspace…");const j=await e(p,"workspace_add",{path:y.trim(),createIfMissing:(S==null?void 0:S.createIfMissing)===!0});if(j!=null&&j.success){i("done"),l(S!=null&&S.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((j==null?void 0:j.error)||"Could not save workspace")}catch(j){i("error"),l(j instanceof Error?j.message:"Could not save workspace")}},[e]),N=o.useCallback(async p=>{var y,S,j,A,M,w;try{i("loading"),l("Starting daemon upgrade…");const v=await e(p,"daemon_upgrade",{});if((y=v==null?void 0:v.result)!=null&&y.alreadyLatest){i("done"),l(`Already on v${((S=v==null?void 0:v.result)==null?void 0:S.version)||"latest"}.`);return}if((j=v==null?void 0:v.result)!=null&&j.upgraded||(A=v==null?void 0:v.result)!=null&&A.success){i("done"),l(`Upgrade to v${((M=v==null?void 0:v.result)==null?void 0:M.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((w=v==null?void 0:v.result)==null?void 0:w.error)||"Upgrade failed")}catch(v){i("error"),l(v instanceof Error?v.message:"Upgrade failed")}},[e]),g=o.useCallback(async(p,y,S,j)=>{var w,v,B;const A=Date.now(),M={machineId:p,kind:y,providerType:S,workspaceId:(j==null?void 0:j.workspaceId)||null,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:A};try{i("loading"),l(`Launching ${S}…`),m(M);const _={cliType:S};(w=j==null?void 0:j.workspacePath)!=null&&w.trim()?_.dir=j.workspacePath.trim():j!=null&&j.workspaceId&&(_.workspaceId=j.workspaceId),j!=null&&j.resumeSessionId&&(_.resumeSessionId=j.resumeSessionId),(v=j==null?void 0:j.args)!=null&&v.trim()&&(_.cliArgs=j.args.trim().split(/\s+/).filter(Boolean)),(B=j==null?void 0:j.model)!=null&&B.trim()&&(_.initialModel=j.model.trim());const T=await e(p,"launch_cli",_),D=(T==null?void 0:T.result)||T,K=(D==null?void 0:D.sessionId)||(D==null?void 0:D.id);if(T!=null&&T.success&&K){m(null),i("done"),l(`${S} launched`),t(Xt(K));return}if(T!=null&&T.success){i("loading"),l(`${S} launch requested — waiting for session…`);return}m(null),i("error"),l((T==null?void 0:T.error)||(D==null?void 0:D.error)||`Could not launch ${y.toUpperCase()} workspace`)}catch(_){if(Bx(_)){i("loading"),l(`${S} launch requested — waiting for session…`);return}m(null),i("error"),l(_ instanceof Error?_.message:`Could not launch ${y.toUpperCase()} workspace`)}},[t,e]),h=o.useCallback(async(p,y)=>{try{const S=await e(p,"list_saved_sessions",{providerType:y,kind:"cli",limit:30}),j=(S==null?void 0:S.result)??S;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(S){return console.error("Failed to list saved sessions on mobile:",S),[]}},[e]),k=o.useCallback(async(p,y)=>bn(e,p,y),[e]);o.useEffect(()=>{if(!d)return;const p=pi(d.workspacePath),y=r.find(j=>{var _,T,D,K;if(!j||j.type==="adhdev-daemon"||$x(j.daemonId||j.id)!==d.machineId||(j.transport==="acp"?"acp":j.transport==="pty"?"cli":null)!==d.kind||String(j.agentType||j.type||"")!==d.providerType)return!1;const v=String(j.providerSessionId||"");if(d.resumeSessionId&&v)return v===d.resumeSessionId;if(p){const L=pi(j.workspace||j.runtimeWorkspaceLabel);return L?L===p:!1}return Number(j.lastUpdated||j._lastUpdate||j.timestamp||((K=(D=(T=(_=j.activeChat)==null?void 0:_.messages)==null?void 0:T.at)==null?void 0:D.call(T,-1))==null?void 0:K.timestamp)||0)>=d.startedAt-5e3});if(!y)return;const S=bl({entrySessionId:y.sessionId,entryInstanceId:y.instanceId,entryRouteId:y.id,conversations:n});S&&(m(null),i("done"),l(`${d.providerType} launched`),t(Xt(S)))},[n,r,t,d]),o.useEffect(()=>{if(!d)return;const p=window.setTimeout(()=>{m(y=>!y||y.startedAt!==d.startedAt?y:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(p)},[d]);const b=o.useCallback(async(p,y)=>{if(y.kind==="ide"&&y.providerType){await f(p,y.providerType,{workspacePath:y.workspace||null});return}(y.kind==="cli"||y.kind==="acp")&&y.providerType&&await g(p,y.kind,y.providerType,{workspacePath:y.workspace||null,resumeSessionId:y.providerSessionId||null})},[f,g]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:f,handleAddWorkspace:x,handleMachineUpgrade:N,handleLaunchWorkspaceProvider:g,handleListSavedSessions:h,handleBrowseDirectory:k,handleOpenRecent:b}}function Wx({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:d,setMachineBackTarget:m}){const u=o.useCallback(b=>{i(b.tabKey),c("chat"),n(b)},[n,c,i]),f=o.useCallback(b=>{const p=e.find(y=>y.routeId===b.routeId&&y.streamSource==="native");p&&(i(p.tabKey),c("chat"),n(p))},[e,n,c,i]),x=o.useCallback(()=>{n(t),c("inbox")},[n,t,c]),N=o.useCallback((b,p="inbox")=>{l(b),a(),d("machines"),m(p),c("machine")},[a,m,c,d,l]),g=o.useCallback(b=>{const p=xs(b);p&&N(p,"chat")},[N]),h=o.useCallback(()=>{a(),c(r)},[r,a,c]),k=o.useCallback(b=>{d(b),c("inbox")},[c,d]);return{openConversation:u,openNativeConversation:f,backFromConversation:x,openMachine:N,openConversationMachine:g,backFromMachine:h,changeMachineSection:k}}function ps(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function Ox(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Fx({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:N,onOpenHistory:g,onOpenRemote:h,onStopCli:k,wsStatus:b,isConnected:p,onShowAllHiddenConversations:y,onHideConversation:S,onOpenNewSession:j,liveSessionInboxState:A,setCliViewModeOverrides:M}){const[w,v]=o.useState(()=>{var ee;return((ee=e[0])==null?void 0:ee.tabKey)||null}),[B,_]=o.useState(()=>e[0]?"chat":"inbox"),[T,D]=o.useState("chats"),[K,L]=o.useState(null),[C,I]=o.useState("inbox"),W=o.useRef([]),P=Ds(),$="0.9.74",H=o.useMemo(()=>e.find(ee=>ee.tabKey===w)||e[0]||null,[e,w]),Q=o.useMemo(()=>H?r.find(ee=>ee.id===H.routeId):void 0,[r,H]),xe=o.useMemo(()=>!H||Qe(H)||!et(H)?null:$s(H),[H]),ie=o.useMemo(()=>r.filter(ee=>ee.type==="adhdev-daemon").sort(Fa),[r]),se=o.useMemo(()=>ie.find(ee=>ee.id===K)||null,[ie,K]),be=pn({sendDaemonCommand:a,activeConv:H||void 0,setActionLogs:i,isStandalone:c}),we=Kx({sendDaemonCommand:a,navigate:P,ides:r,conversations:e}),ge=o.useMemo(()=>e.map(ee=>{const Pe=B==="chat"&&(H==null?void 0:H.tabKey)===ee.tabKey,$e=un(ee,A,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Pe}),Oe=cs(ee),He=Dc(ee);return{conversation:ee,timestamp:Oe,preview:He,unread:$e.unread,requiresAction:$e.requiresAction,isWorking:$e.isWorking,inboxBucket:$e.inboxBucket}}),[e,A,B,H]),{markConversationRead:J}=Ex({conversations:e,machineEntries:ie,items:ge,selectedConversation:H,selectedTabKey:w,screen:B,liveSessionInboxState:A,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:N,setSelectedTabKey:v,setScreen:_,setSelectedMachineId:L,setSection:D,setMachineBackTarget:I,resetMachineAction:we.resetMachineAction}),ce=Wx({conversations:e,selectedConversation:H,machineBackTarget:C,markConversationRead:J,resetMachineAction:we.resetMachineAction,setSelectedTabKey:v,setScreen:_,setSelectedMachineId:L,setSection:D,setMachineBackTarget:I}),ye=o.useMemo(()=>Fr(ge.filter(ee=>ee.requiresAction)),[ge]),ae=o.useMemo(()=>Fr(ge.filter(ee=>ee.unread&&!ee.requiresAction)),[ge]),de=o.useMemo(()=>Rx(ge.filter(ee=>!ee.unread&&!ee.requiresAction&&ee.isWorking),W.current),[ge]);o.useEffect(()=>{W.current=de.map(ee=>ee.conversation.tabKey)},[de]);const je=o.useMemo(()=>Fr(ge.filter(ee=>!ee.unread&&!ee.requiresAction&&!ee.isWorking)),[ge]),fe=o.useMemo(()=>se?ge.filter(ee=>xs(ee.conversation)===se.id):[],[ge,se]),pe=o.useMemo(()=>_x(se,r),[r,se]),te=(se==null?void 0:se.version)||null,me=!!se&&!!te&&!0&&te!==$,oe=o.useMemo(()=>(se==null?void 0:se.availableProviders)||[],[se]),Y=o.useMemo(()=>oe.filter(ee=>ps(ee,"cli")).map(ee=>({type:ee.type,displayName:ee.displayName||ee.type,icon:ee.icon})),[oe]),V=o.useMemo(()=>oe.filter(ee=>ps(ee,"acp")).map(ee=>({type:ee.type,displayName:ee.displayName||ee.type,icon:ee.icon})),[oe]),le=o.useMemo(()=>Px(ie,ge),[ge,ie]),ke=o.useCallback(async ee=>{se&&await we.handleOpenRecent(se.id,ee)},[we,se]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:B==="chat"&&H?s.jsx(wx,{selectedConversation:H,isAcp:Qe(H),isStandalone:c,selectedIdeEntry:Q,actionLogs:n,userName:l,isSendingChat:be.isSendingChat,sendFeedbackMessage:be.sendFeedbackMessage,isFocusingAgent:be.isFocusingAgent,handleModalButton:be.handleModalButton,handleRelaunch:be.handleRelaunch,onBack:ce.backFromConversation,onOpenNativeConversation:ce.openNativeConversation,onOpenMachine:ce.openConversationMachine,onOpenHistory:g,onOpenRemote:h,onStopCli:k,cliViewMode:xe,onSetCliViewMode:async ee=>{await il({conversation:H,mode:ee,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:M})},handleSendChat:be.handleSendChat,handleFocusAgent:be.handleFocusAgent}):B==="machine"&&se?s.jsx(Ix,{selectedMachineEntry:se,selectedMachineConversations:fe,selectedMachineRecentLaunches:pe,cliProviders:Y,acpProviders:V,selectedMachineNeedsUpgrade:me,appVersion:$,machineAction:we.machineAction,isStandalone:c,section:T,showBottomNav:C==="inbox",onBack:ce.backFromMachine,onSectionChange:ce.changeMachineSection,onOpenConversation:ce.openConversation,onOpenRecent:ke,onOpenMachineDetails:()=>P(`/machines/${se.id}`),onMachineUpgrade:()=>we.handleMachineUpgrade(se.id),onLaunchDetectedIde:(ee,Pe)=>we.handleLaunchDetectedIde(se.id,ee,Pe),onAddWorkspace:(ee,Pe)=>we.handleAddWorkspace(se.id,ee,Pe),onBrowseDirectory:ee=>we.handleBrowseDirectory(se.id,ee),onLaunchWorkspaceProvider:(ee,Pe,$e)=>we.handleLaunchWorkspaceProvider(se.id,ee,Pe,$e),onListSavedSessions:ee=>we.handleListSavedSessions(se.id,ee)}):s.jsx(Sx,{section:T,attentionItems:ye,unreadItems:ae,workingItems:de,completedItems:je,hiddenConversations:t,machineCards:le,getAvatarText:Ox,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ce.openConversation,onShowAllHidden:y,onHideConversation:S,onOpenNewSession:j,onOpenMachine:ce.openMachine,onOpenSettings:()=>P("/settings"),onSectionChange:D,wsStatus:b,isConnected:p,isStandalone:c})})}function zn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Hx({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,d]=o.useState(!1),[m,u]=o.useState(null),f=o.useCallback(()=>{c.current=0,d(!1),u(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const x=o.useCallback(k=>{k.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,d(!0))},[]),N=o.useCallback(k=>{if(!k.dataTransfer.types.includes("text/tab-key"))return;if(k.preventDefault(),!zn(t,r)){u("merge");return}const b=k.currentTarget.getBoundingClientRect(),p=k.clientX-b.left,y=b.width/3;p<y?u("split-left"):p>y*2?u("split-right"):u("merge")},[t,r]),g=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,d(!1),u(null))},[]),h=o.useCallback(k=>{c.current=0,d(!1);const b=k.dataTransfer.getData("text/tab-key"),p=b?e.some(S=>S.tabKey===b):!1,y=m;if(u(null),i(),!!b){if(k.preventDefault(),y==="split-left"&&zn(t,r)){r==null||r(b,"split-left");return}if(y==="split-right"&&zn(t,r)){r==null||r(b,"split-right");return}if(p){a(b);return}n==null||n(b)}},[e,m,t,r,n,a,i]);return{dragOver:l,dropAction:m,resetDragState:f,handleDragEnter:x,handleDragOver:N,handleDragLeave:g,handleDrop:h}}function Ux(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 zx({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(t??null),[l,d]=o.useState(r??[]),[m,u]=o.useState(null),f=o.useRef(null),x=o.useRef(null),N=o.useRef(n),g=o.useRef(a);o.useEffect(()=>{N.current=n},[n]),o.useEffect(()=>{g.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{d(M=>{const w=Ux(M,e);return w.length===M.length&&w.every((v,B)=>v===M[B])?M:w})},[e]);const h=o.useMemo(()=>{const M=m??l;if(M.length===0)return e;const w=new Map(M.map((v,B)=>[v,B]));return[...e].sort((v,B)=>{const _=w.get(v.tabKey)??999,T=w.get(B.tabKey)??999;return _-T})},[e,m,l]);o.useEffect(()=>{var w,v;if(h.length===0){i!==null&&(c(null),(w=N.current)==null||w.call(N,null));return}if(i&&h.some(B=>B.tabKey===i))return;const M=h[0].tabKey;M!==i&&(c(M),(v=N.current)==null||v.call(N,M))},[h,i]);const k=o.useMemo(()=>h.find(M=>M.tabKey===i),[h,i]),b=o.useCallback(M=>{var w;c(M),(w=N.current)==null||w.call(N,M)},[]),p=o.useCallback((M,w,v)=>{d(B=>{var K;const _=B.filter(L=>L!==M),T=_.indexOf(w);if(T<0)return B;const D=v==="left"?T:T+1;return _.splice(D,0,M),(K=g.current)==null||K.call(g,_),_}),u(null)},[]),y=o.useCallback((M,w,v)=>{const _=(l.length>0?l:e.map(K=>K.tabKey)).filter(K=>K!==M),T=_.indexOf(w);if(T<0)return;const D=v==="left"?T:T+1;_.splice(D,0,M),f.current=_,u(_)},[l,e]),S=o.useCallback(()=>{var w;const M=f.current;M&&(d(M),(w=g.current)==null||w.call(g,M))},[]),j=o.useCallback(()=>{f.current=null,u(null)},[]),A=o.useCallback(M=>{d(w=>{var B;const v=w.filter(_=>_!==M);return v.push(M),(B=g.current)==null||B.call(g,v),v})},[]);return{activeTabId:i,activeConv:k,sortedConversations:h,previewOrderRef:f,draggingTabRef:x,selectTab:b,handleTabReorder:p,updatePreviewOrder:y,commitPreviewOrder:S,clearPreviewOrder:j,moveTabToEnd:A,setDraggingTabKey:M=>{x.current=M}}}function Vx({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),s.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function po({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession: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,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?Kc:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),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:Et,"aria-label":Et,children:[s.jsx(Qi,{size:14}),s.jsx("span",{children:Et})]})}),c&&s.jsx(yl,{}),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 kl="adhdev-tab-shortcuts";function Sl(){try{return JSON.parse(localStorage.getItem(kl)||"{}")}catch{return{}}}function Nl({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>Sl()),[l,d]=o.useState(null),m=o.useCallback(f=>{const x=[];return f.metaKey&&x.push(a?"⌘":"Meta"),f.ctrlKey&&x.push("Ctrl"),f.altKey&&x.push(a?"⌥":"Alt"),f.shiftKey&&x.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(x.push(f.key.length===1?f.key.toUpperCase():f.key),x.join("+"))},[a]),u=o.useCallback(f=>{c(f);try{localStorage.setItem(kl,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){d(null);return}const N=m(x);if(!N)return;const g={...i};for(const[h,k]of Object.entries(g))k===N&&delete g[h];g[l]=N,u(g),d(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,i,u,m]),o.useEffect(()=>{if(!e)return;const f=x=>{if(!(!x.ctrlKey&&!x.metaKey&&!x.altKey)){for(const[N,g]of Object.entries(i))if(t.includes(N)&&m(x)===g){x.preventDefault(),r(),n(N);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,i,t,r,n,m]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const Vn=e=>{e.preventDefault()},Gx=o.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:f,onReorderTab:x,onCommitPreviewOrder:N,onClearPreviewOrder:g,onDragStateReset:h,onDragTabKeyChange:k,onReceiveTab:b,onOpenContextMenu:p,longPressTimer:y,isGroupActive:S}){const j=Es(t),A=j.isGenerating?"agent-tab-generating":j.isWaiting?"agent-tab-waiting":"",M=j.isReconnecting,w=o.useCallback(I=>{l.current=t.tabKey,k(t.tabKey),I.dataTransfer.setData("text/tab-key",t.tabKey),I.dataTransfer.effectAllowed="move"},[t.tabKey,l,k]),v=o.useCallback(()=>{l.current=null,k(null),N(),g(),h()},[l,k,N,g,h]),B=o.useCallback(I=>{const W=l.current;if(!(!W||W===t.tabKey)&&I.dataTransfer.types.includes("text/tab-key")){I.preventDefault(),I.stopPropagation();const P=I.currentTarget.getBoundingClientRect(),$=I.clientX<P.left+P.width/2?"left":"right";f(W,t.tabKey,$)}},[t.tabKey,l,f]),_=o.useCallback(I=>{I.preventDefault(),I.stopPropagation();const W=I.dataTransfer.getData("text/tab-key");if(W&&W!==t.tabKey){const P=I.currentTarget.getBoundingClientRect(),$=I.clientX<P.left+P.width/2?"left":"right";c.includes(W)?x(W,t.tabKey,$):b&&b(W)}g()},[t.tabKey,c,x,b,g]),T=o.useCallback(I=>{I.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),D=o.useCallback(I=>{I.preventDefault(),p(I.clientX,I.clientY,t.tabKey)},[t.tabKey,p]),K=o.useCallback(I=>{const W=I.touches[0];y.current=setTimeout(()=>{p(W.clientX,W.clientY,t.tabKey)},600)},[t.tabKey,y,p]),L=o.useCallback(()=>{y.current&&clearTimeout(y.current)},[y]),C=["adhdev-dockview-tab",A,r&&"is-active",S&&"is-group-active",M&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:C,draggable:!0,onDragStart:w,onDragEnd:v,onDragOver:B,onDrop:_,onClick:T,onContextMenu:D,onTouchStart:K,onTouchEnd:L,onTouchMove:L,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:j.isGenerating?s.jsx("div",{className:"tab-spinner"}):j.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):M?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):j.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:ct(t),children:ct(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[M?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:rs(t)}):j.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[rs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:rs(t)}),s.jsx(Rs,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),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 qx({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:N,onReceiveTab:g,onHideTab:h,isGroupActive:k,allowTabShortcuts:b=!0}){const[p,y]=o.useState(null),S=o.useRef(null),j=o.useRef(null),A=o.useMemo(()=>e.map(D=>D.tabKey),[e]);lr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(p==null?void 0:p.tabKey)||null});const{isMac:M,tabShortcuts:w,shortcutListening:v,setShortcutListening:B,saveShortcuts:_}=Nl({enabled:b,sortedTabKeys:e.map(D=>D.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!p)return;const D=K=>{const L=document.querySelector("[data-pane-context-menu]");L&&L.contains(K.target)||y(null)};return window.addEventListener("mousedown",D,!0),()=>window.removeEventListener("mousedown",D,!0)},[p]),o.useEffect(()=>{const D=j.current;if(!D)return;const K=L=>{Math.abs(L.deltaY)<=Math.abs(L.deltaX)||(L.preventDefault(),D.scrollLeft+=L.deltaY)};return D.addEventListener("wheel",K,{passive:!1}),()=>D.removeEventListener("wheel",K)},[]);const T=o.useCallback((D,K,L)=>{y({x:D,y:K,tabKey:L})},[]);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:j,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(D=>s.jsx(Gx,{conv:D,isActive:t===D.tabKey,isDraggedTab:a.current===D.tabKey,isTaskCompleteUnread:n.has(D.tabKey),shortcut:b?w[D.tabKey]:void 0,conversationKeys:A,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:N,onReceiveTab:g,onOpenContextMenu:T,longPressTimer:S,isGroupActive:k},D.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),p&&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:p.x,top:p.y},children:[b&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Vn,onClick:D=>{D.stopPropagation(),B(p.tabKey),y(null)},children:["⌨ ",w[p.tabKey]?`Change shortcut (${w[p.tabKey]})`:"Set shortcut"]}),w[p.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:Vn,onClick:()=>{const D={...w};delete D[p.tabKey],_(D),y(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[b&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:Vn,onClick:()=>{h(p.tabKey),y(null)},children:"🚫 Hide from Dashboard"})]})]}),b&&v&&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:D=>D.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",M?"⌘+1":"Ctrl+1",", ",M?"⌥+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 Yx({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:d,groupIndex:m,onFocus:u,isSplitMode:f,numGroups:x,onMoveTab:N,onReceiveTab:g,style:h,onActiveTabChange:k,initialActiveTabId:b,initialTabOrder:p,onTabOrderChange:y,onHideTab:S,isFocused:j,allowTabShortcuts:A=!0,onOpenNewSession:M,liveSessionInboxState:w}){const{sendCommand:v}=xt(),B=o.useRef(null),{activeTabId:_,activeConv:T,sortedConversations:D,draggingTabRef:K,selectTab:L,handleTabReorder:C,updatePreviewOrder:I,commitPreviewOrder:W,clearPreviewOrder:P,moveTabToEnd:$,setDraggingTabKey:H}=zx({conversations:e,initialActiveTabId:b,initialTabOrder:p,onActiveTabChange:k,onTabOrderChange:y}),Q=pn({sendDaemonCommand:a,activeConv:T,setActionLogs:i,isStandalone:c}),{dragOver:xe,dropAction:ie,resetDragState:se,handleDragEnter:be,handleDragOver:we,handleDragLeave:ge,handleDrop:J}=Hx({conversations:e,numGroups:x,onMoveTab:N,onReceiveTab:g,onOwnTabDrop:$,onClearPreviewOrder:P}),ce=T&&!Qe(T)&&$s(T)==="terminal",ye=o.useMemo(()=>T?t.find(fe=>fe.id===T.routeId):void 0,[t,T]),ae=o.useMemo(()=>T?n.filter(fe=>fe.routeId===T.tabKey):[],[n,T]),de=o.useMemo(()=>new Set(D.filter(fe=>Uu(fe,w,{isOpenConversation:fe.tabKey===_})).map(fe=>fe.tabKey)),[_,w,D]);lr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:_,dragOver:xe});const je=o.useCallback(fe=>{fe.streamSource==="agent-stream"&&fe.agentType&&v(fe.routeId,wc(),{agentType:fe.agentType,...fe.sessionId&&{targetSessionId:fe.sessionId}}).catch(()=>{})},[v]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...h,outline:xe?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(qx,{conversations:D,activeTabId:_,groupIndex:m,numGroups:x,unreadTabKeys:de,draggingTabRef:K,onFocus:u,onSelectTab:L,onConversationActivated:je,onPreviewReorder:I,onReorderTab:C,onCommitPreviewOrder:W,onClearPreviewOrder:P,onDragStateReset:se,onDragTabKeyChange:H,onMoveTab:N,onReceiveTab:g,onHideTab:S,isGroupActive:j??!1,allowTabShortcuts:A}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:be,onDragOver:we,onDragLeave:ge,onDrop:J,children:[xe&&s.jsx(Vx,{dropAction:ie,canSplit:!!(x<4&&N)}),T?s.jsx(mo,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!ce,ideEntry:ye,terminalRef:B,handleModalButton:Q.handleModalButton,handleRelaunch:Q.handleRelaunch,handleSendChat:Q.handleSendChat,isSendingChat:Q.isSendingChat,sendFeedbackMessage:Q.sendFeedbackMessage,handleFocusAgent:Q.handleFocusAgent,isFocusingAgent:Q.isFocusingAgent,actionLogs:ae,userName:d,isInputActive:!f||!!j}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(po,{conversationsCount:e.length,isSplitMode:f,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:M})})]})]})}function Xx({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:f,userName:x,focusedGroup:N,focusGroup:g,moveTabToGroup:h,splitTabRelative:k,closeGroup:b,handleResizeStart:p,groupActiveTabIds:y,setGroupActiveTab:S,groupTabOrders:j,setGroupTabOrder:A,toggleHiddenTab:M,onOpenNewSession:w,allowTabShortcuts:v=!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((_,T)=>{const D=t&&n.length===r?`${n[T]}%`:void 0;return s.jsxs(Nt.Fragment,{children:[t&&T>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:K=>p(T-1,K),onDoubleClick:()=>b(T),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(Yx,{style:t?{flexBasis:D??`${100/r}%`,flexGrow:D?0:1,flexShrink:D?0:1}:void 0,conversations:_,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:f,userName:x,groupIndex:T,isFocused:t&&N===T,onFocus:()=>g(T),isSplitMode:t,numGroups:r,onMoveTab:(K,L)=>{L==="left"&&T>0?h(K,T-1):L==="right"&&T<r-1?h(K,T+1):L==="split-left"&&r<4?k(K,T,"left"):L==="split-right"&&r<4&&k(K,T,"right")},onReceiveTab:K=>h(K,T),onActiveTabChange:K=>S(T,K),initialActiveTabId:y[T],initialTabOrder:j[T],onTabOrderChange:K=>A(T,K),onHideTab:M,onOpenNewSession:w,allowTabShortcuts:v,liveSessionInboxState:B})]},T)})})}function Cl({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?dt.onScreenshot("ide-page",(u,f)=>{if(u!==e)return;const x=new FileReader;x.onload=()=>i(x.result),x.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var u;return e?((u=dt.onStatus)==null?void 0:u.call(dt,(f,x)=>{f===e&&x!=null&&x.screenshotUsage&&l(x.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,t]),o.useEffect(()=>{const m=e?dt.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&t?m.startScreenshots(t):m.stopScreenshots(t),()=>{m.stopScreenshots(t)}},[n,r,t,e]);const d=o.useCallback(async(m,u)=>{const f=e?dt.get(e):null;return!f||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):f.sendInput(m,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:d}}const Tl="adhdev-dashboard-action-shortcuts",Jx=1200,Qx=[["toggleHiddenTabs","G H"],["openNewSession","N"],["setActiveTabShortcut","G S"],["selectPreviousGroupTab","G K"],["selectPreviousGroupTab","T ←"],["selectPreviousGroupTab","⌥+["],["selectPreviousGroupTab","Ctrl+Alt+["],["selectNextGroupTab","G J"],["selectNextGroupTab","T →"],["selectNextGroupTab","⌥+]"],["selectNextGroupTab","Ctrl+Alt+]"],["splitActiveTabDown","S ↓"],["splitActiveTabDown","⌘+⌥+-"],["splitActiveTabDown","Ctrl+Alt+-"],["splitActiveTabRight","S →"],["splitActiveTabRight","⌘+⌥+\\"],["splitActiveTabRight","⌘+⌥+="],["splitActiveTabRight","Ctrl+Alt+\\"],["focusLeftPane","F ←"],["focusLeftPane","⌘+⌥+←"],["focusLeftPane","⌘+⌥+["],["focusLeftPane","Ctrl+Alt+←"],["focusRightPane","F →"],["focusRightPane","⌘+⌥+→"],["focusRightPane","⌘+⌥+]"],["focusRightPane","Ctrl+Alt+→"],["focusUpPane","F ↑"],["focusUpPane","⌘+⌥+U"],["focusUpPane","Ctrl+Alt+↑"],["focusDownPane","F ↓"],["focusDownPane","⌘+⌥+J"],["focusDownPane","Ctrl+Alt+↓"],["moveActiveTabToLeftPane","M ←"],["moveActiveTabToLeftPane","⌘+⌥+⇧+←"],["moveActiveTabToLeftPane","⌘+⌥+,"],["moveActiveTabToLeftPane","Ctrl+Alt+Shift+←"],["moveActiveTabToRightPane","M →"],["moveActiveTabToRightPane","⌘+⌥+⇧+→"],["moveActiveTabToRightPane","⌘+⌥+."],["moveActiveTabToRightPane","Ctrl+Alt+Shift+→"],["moveActiveTabToUpPane","M ↑"],["moveActiveTabToUpPane","⌘+⌥+I"],["moveActiveTabToUpPane","Ctrl+Alt+Shift+↑"],["moveActiveTabToDownPane","M ↓"],["moveActiveTabToDownPane","⌘+⌥+K"],["moveActiveTabToDownPane","Ctrl+Alt+Shift+↓"],["triggerPrimaryApprovalAction","⌥+A"],["triggerSecondaryApprovalAction","⌥+D"],["toggleCliView","T"]];function Zx(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function rt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function Ml(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:rt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:rt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:rt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:rt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:rt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:rt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:rt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:rt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:rt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:rt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:rt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:rt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:rt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:rt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:rt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:rt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:rt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:rt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:rt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:rt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:rt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:rt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:rt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:rt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:rt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:rt("toggleCliView",e)}]}function Ta(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function an(e){const t=Object.fromEntries(Ml(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Tl)||"{}"),n={...t,...r};for(const[a,i]of Qx)n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function Al(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function eb({enabled:e=!0,onTrigger:t}){const r=Zx(),[n,a]=o.useState(()=>an(r)),[i,c]=o.useState(null),[l,d]=o.useState([]),m=o.useRef({parts:[],timer:null}),u=o.useCallback(h=>{const k=[];return h.metaKey&&k.push(r?"⌘":"Meta"),h.ctrlKey&&k.push("Ctrl"),h.altKey&&k.push(r?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&k.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(k.push(Al(h.key)),k.join("+"))},[r]),f=o.useCallback(h=>{a(h);try{localStorage.setItem(Tl,JSON.stringify(h))}catch{}},[]);o.useEffect(()=>{const h=an(r),k=Object.entries(n),b=Object.entries(h);k.length===b.length&&k.every(([p,y])=>h[p]===y)||f(h)},[n,r,f]);const x=o.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),N=o.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},Jx))},[]);o.useEffect(()=>{if(!i)return;const h=k=>{if(k.preventDefault(),k.stopPropagation(),k.key==="Escape"){c(null),d([]);return}const b=u(k);if(!b)return;const y=!(k.metaKey||k.ctrlKey||k.altKey)&&/^[A-Z0-9]$/.test(b);if(l.length===0&&y){d([b]);return}const j=[...l,b].slice(0,2).join(" "),A={...n};for(const[M,w]of Object.entries(A))w===j&&delete A[M];A[i]=j,f(A),c(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[n,u,f,i,l]),o.useEffect(()=>{if(!e||i)return;const h=k=>{if(k.defaultPrevented)return;const b=u(k);if(!b)return;const p=k.metaKey||k.ctrlKey||k.altKey;if(Ta(k.target))return;const y=m.current.parts,S=p?[b]:[...y.slice(-1),b].slice(-2),j=S.join(" "),A=S[S.length-1],M=Object.entries(n).filter(([,T])=>!!T),w=M.find(([,T])=>T===j);if(w){k.preventDefault(),x(),t(w[0]);return}if(M.some(([,T])=>T.startsWith(`${j} `))){k.preventDefault(),m.current.parts=S,N();return}const B=M.find(([,T])=>T===A);if(B){k.preventDefault(),x(),t(B[0]);return}if(M.some(([,T])=>T.startsWith(`${A} `))){k.preventDefault(),m.current.parts=[A],N();return}x()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[n,N,e,u,t,x,i]),o.useEffect(()=>()=>x(),[x]);const g=o.useMemo(()=>Ml(r),[r]);return{isMac:r,actionDefinitions:g,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:f}}function tb({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 Il(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function hi({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!Il(n):!0}function sb({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:Il(r)}const Rl=1e3,rb=4;function xi(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function bi(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function nb({detachDelayMs:e=Rl,stillnessThresholdPx:t=rb,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let i=null,c=null,l=null,d=null,m=null,u=!1;const f=()=>{m!=null&&(a(m),m=null)},x=()=>{f(),l=null},N=()=>{f(),i=null,c=null,l=null,d=null,u=!1},g=()=>{!i||!l||!d||u||m!=null||(m=n(()=>{m=null,!(!i||!l||!d||u)&&xi(d,c)&&(bi(l,d,t)||(u=!0,r({panelId:i,clientX:d.clientX,clientY:d.clientY})))},e))},h=b=>{if(!(!i||u)){if(!xi(b,c)){d={clientX:b.clientX,clientY:b.clientY},x();return}(!l||bi(l,b,t))&&(f(),l={clientX:b.clientX,clientY:b.clientY}),d={clientX:b.clientX,clientY:b.clientY},g()}},k=b=>{!i||u||(b&&(d={clientX:b.clientX,clientY:b.clientY}),x())};return{startDrag:b=>{f(),i=b.panelId,c=b.selfPanelBounds??null,l=null,d={clientX:b.clientX,clientY:b.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:k,markNoDropTarget:k,markDockTarget:k,endDrag:N,isDragging:()=>i!=null,hasDetached:()=>u,dispose:N}}function ab(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function _r(e){return e.isActive}function gi(e){return e.isVisible}const Ll=o.createContext(null);function yn(){const e=o.useContext(Ll);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Hr(e){return ct(e)||e.tabKey}function ob(e){return`remote:${e}`}function Rt(e){return e.startsWith("remote:")}function yi(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ib(e){e.preventDefault()}function Gn(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 qn(e,t){e.classList.remove(ca.className,la.className),e.classList.add(t==="light"?ca.className:la.className)}function vi(e){return e?Array.from(new Set(e.groups.map(t=>{var r,n;return(n=(r=t.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(t=>!!t&&t!==window))):[]}function cb(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 lb(e,t,r){var c;const n=[t];let a;for(const l of n){let d;for(const m of l){const u=e.addPanel({id:m.tabKey,component:"conversation",title:Hr(m),params:{kind:"conversation",tabKey:m.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return r??((c=t[0])==null?void 0:c.tabKey)??null}function wi(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])Rt(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!==Hr(n)&&a.api.setTitle(Hr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Hr(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function ji(e,t,r){var d,m;const n=r?ob(r):null;for(const u of[...e.panels])Rt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Pt(t,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=Bc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((m=e.panels.find(u=>!Rt(u.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 db({params:e,api:t}){var N;const r=yn(),n=o.useRef(null),[a,i]=o.useState(()=>_r(t)),[c,l]=o.useState(()=>gi(t)),d=r.conversationsByTabKey.get(e.tabKey),m=pn({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(_r(t)),l(gi(t));const g=[t.onDidActiveChange(h=>i(h.isActive)),t.onDidActiveGroupChange(h=>{if(!_r(t)&&!h.isActive){i(!1);return}i(_r(t))}),t.onDidVisibilityChange(h=>l(h.isVisible))];return()=>{for(const h of g)h.dispose()}},[t]);const u=o.useMemo(()=>d?r.ides.find(g=>g.id===d.routeId):void 0,[r.ides,d]),f=o.useMemo(()=>d?r.actionLogs.filter(g=>g.routeId===d.tabKey):[],[r.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(po,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const x=!Qe(d)&&$s(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(mo,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:x,ideEntry:u,terminalRef:n,handleModalButton:m.handleModalButton,handleRelaunch:m.handleRelaunch,handleSendChat:m.handleSendChat,isSendingChat:m.isSendingChat,handleFocusAgent:m.handleFocusAgent,isFocusingAgent:m.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((N=r.scrollToBottomRequest)==null?void 0:N.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:c})})}function ub({params:e}){var d;const t=yn(),r=o.useMemo(()=>Pt([...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)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=Cl({doId:a,targetSessionId:r?vc(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(nc,{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 mb(){const e=yn();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(po,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function fb(e){var N,g;cb(e);const t=yn(),r=o.useCallback(h=>{"button"in h&&h.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const h=Pt([...t.conversationsByTabKey.values()],e.params.routeId),k=((N=e.api.group.activePanel)==null?void 0:N.id)===e.api.id,b=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${k?" is-active":""}${b?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(h==null?void 0:h.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:h!=null&&h.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:h.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((g=e.api.group.activePanel)==null?void 0:g.id)===e.api.id,i=e.api.isGroupActive,c=un(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,d=c.isConnecting,m=c.isGenerating,u=c.isWaiting,f=c.unread,x=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:ct(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:h=>{var k;h.preventDefault(),r(h),t.openTabContextMenu({x:h.clientX,y:h.clientY,tabKey:n.tabKey,sourceDocument:((k=h.target)==null?void 0:k.ownerDocument)??document})},children:[f&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?s.jsx("div",{className:"tab-spinner"}):u?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):d?s.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:ct(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:rs(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:rs(n)}):s.jsx("span",{children:rs(n)})})]}),x&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:x,children:x})]})}function pb({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:f,registerActionHandlers:x,onActiveTabChange:N,onOpenNewSession:g,onRequestScrollToBottom:h,requestedActiveTabKey:k,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:p,scrollToBottomRequest:y,liveSessionInboxState:S,layoutProfile:j}){var Xe,Ve,st;const{theme:A}=no(),{sendCommand:M}=xt(),w=o.useRef(null),v=o.useRef(null),B=o.useRef(null),_=o.useRef(!1),T=o.useRef(!1),D=o.useRef(!1),K=o.useRef(null),L=o.useRef([]),[C,I]=o.useState(null),[W,P]=o.useState(0),$=o.useRef(typeof window>"u"?{}:Dh(j)),H=o.useMemo(()=>new Map(e.map(F=>[F.tabKey,F])),[e]),Q=o.useMemo(()=>{const F=w.current;return F?F.groups.some(U=>{try{const q=U.model.location.type;return q!=="floating"&&q!=="popout"?!1:U.panels.some(re=>H.has(re.id))}catch{return!1}}):!1},[H,W,e]),xe=o.useCallback(()=>{var F;(F=w.current)==null||F.focus()},[]),ie=o.useCallback((F,U)=>{h==null||h(F,U)},[h]),se=o.useCallback(F=>{const U=document,q=F.document;for(const ne of U.querySelectorAll('link[rel="stylesheet"]')){const ve=q.createElement("link");ve.rel="stylesheet",ve.href=ne.href,ne.crossOrigin&&(ve.crossOrigin=ne.crossOrigin),q.head.appendChild(ve)}for(const ne of U.querySelectorAll("style")){const ve=q.createElement("style");ve.textContent=ne.textContent,q.head.appendChild(ve)}const re=[];for(const ne of U.styleSheets)try{for(const ve of ne.cssRules)ve instanceof CSSStyleRule&&(ve.selectorText===":root"||ve.selectorText==="html")&&re.push(ve.cssText)}catch{}if(re.length>0){const ne=q.createElement("style");ne.textContent=re.join(`
|
|
52
|
-
`),q.head.appendChild(ne)}const E=U.documentElement.getAttribute("data-theme");E&&q.documentElement.setAttribute("data-theme",E),q.documentElement.style.colorScheme=E==="light"?"light":"dark",q.body.className=U.body.className;const X=U.documentElement.getAttribute("style");X&&q.documentElement.setAttribute("style",X);const Z=q.getElementById("dv-popout-window");Z instanceof HTMLElement&&(Z.classList.add("adhdev-dockview"),qn(Z,A))},[A]),be=o.useCallback(()=>{var U;const F=w.current;if(F)for(const q of F.groups)try{const re=(U=q.element)==null?void 0:U.ownerDocument;if(!re||re===document)continue;const E=re.getElementById("dv-popout-window");E instanceof HTMLElement&&(E.classList.add("adhdev-dockview"),qn(E,A));const X=document.documentElement.getAttribute("data-theme");X&&re.documentElement.setAttribute("data-theme",X),re.documentElement.style.colorScheme=X==="light"?"light":"dark",re.body.className=document.body.className;const Z=document.documentElement.getAttribute("style");Z?re.documentElement.setAttribute("style",Z):re.documentElement.removeAttribute("style")}catch{}},[A]),we=o.useCallback(F=>{const U=w.current;if(!U)return;const q=U.getPanel(F);q&&U.addPopoutGroup(q,{popoutUrl:"/popout.html",onDidOpen:({window:re})=>{se(re),pe();const E=H.get(F);re.document.title=E?`${ct(E)} — ADHDev`:"ADHDev — Popout"}})},[H,se]),ge=o.useCallback(F=>{const U=w.current,q=U==null?void 0:U.getPanel(F);if(!U||!q)return;const re=U.groups.filter(E=>{var X;try{return((X=E.element)==null?void 0:X.ownerDocument)===document}catch{return!0}});re.length>0?q.api.moveTo({group:re[0],position:"center"}):q.api.moveTo({position:"center"}),q.api.setActive()},[]),J=o.useCallback(F=>{var re;const U=w.current;if(!U)return!1;const q=U.getPanel(F);if(!q)return!1;try{return((re=q.group.element)==null?void 0:re.ownerDocument)!==document}catch{return!1}},[]),ce=o.useCallback(F=>{J(F)&&ge(F),u(F)},[J,ge,u]),ye=o.useCallback(F=>{const U=w.current,q=U==null?void 0:U.getPanel(F);!U||!q||U.addFloatingGroup(q,{width:600,height:500})},[]),ae=o.useCallback(F=>{var q;const U=(q=w.current)==null?void 0:q.getPanel(F);if(!U)return!1;try{return U.group.model.location.type==="floating"}catch{return!1}},[]),de=o.useCallback(()=>{var U,q;const F=(q=(U=w.current)==null?void 0:U.activePanel)==null?void 0:q.id;return!F||Rt(F)?null:H.has(F)?F:null},[H]),je=o.useCallback(F=>{const U=w.current,q=U==null?void 0:U.getPanel(F);if(!U||!q)return;const re=U.groups.filter(E=>{try{return E.model.location.type==="grid"}catch{return!0}});re.length>0?q.api.moveTo({group:re[0],position:"center"}):q.api.moveTo({position:"center"}),q.api.setActive()},[]),fe=o.useCallback(()=>{var X;const F=w.current;if(!F)return;const q=F.groups.filter(Z=>{var ne;try{return((ne=Z.element)==null?void 0:ne.ownerDocument)===document&&Z.model.location.type==="grid"}catch{return!1}})[0]||null,re=[...F.panels];for(const Z of re){const ne=(X=Z.group.element)==null?void 0:X.ownerDocument,ve=Z.group.model.location.type;ne===document&&ve==="grid"||(q&&q.id!==Z.group.id?Z.api.moveTo({group:q,position:"center"}):Z.api.moveTo({position:"center"}))}const E=F.activePanel;E&&(E.group.model.openPanel(E),E.api.setActive()),Gn(document)},[]),pe=o.useCallback(()=>{var U,q;const F=w.current;if(F)for(const re of F.groups){const E=(U=re.element)==null?void 0:U.ownerDocument;if(!E||E===document)continue;const X=E.getElementById("dv-popout-window");if(!(X instanceof HTMLElement))continue;let Z=null,ne=E.title||"ADHDev",ve="Popout workspace";const Ae=re.activePanel;if(Ae)if(Z=Ae.id,Rt(Ae.id)){const Ie=((q=Ae.params)==null?void 0:q.routeId)||Ae.id.slice(7),Ge=Pt([...H.values()],Ie);ne=Bc(Ge),ve=Ge!=null&&Ge.machineName?`Remote view · ${Ge.machineName}`:"Remote view"}else{const Ie=H.get(Ae.id);ne=Ie?ct(Ie):Ae.title||Ae.id,ve=Ie?rs(Ie):"Dockview panel"}E.title=`${ne} — ADHDev`;const Le=Array.from(E.querySelectorAll("#adhdev-popout-header"));for(const Ie of Le)Ie.remove();const Se=E.createElement("div");Se.id="adhdev-popout-header",E.body.appendChild(Se),Se.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(";")),Se.innerHTML=`
|
|
53
|
-
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
54
|
-
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
55
|
-
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${yi(ne)}</div>
|
|
56
|
-
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${yi(ve)}</div>
|
|
57
|
-
</div>
|
|
58
|
-
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
59
|
-
<button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
|
|
60
|
-
<button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
|
|
61
|
-
</div>
|
|
62
|
-
`,X.style.top="52px",X.style.height="calc(100% - 52px)";const _e=Se.querySelector("[data-adhdev-popout-focus]");_e&&(_e.onclick=()=>{window.focus()});const Ee=Se.querySelector("[data-adhdev-popout-dock]");Ee&&(Ee.disabled=!Z,Ee.style.opacity=Z?"1":"0.5",Ee.style.cursor=Z?"pointer":"default",Ee.onclick=()=>{var Ie;Z&&ge(Z),(Ie=E.defaultView)==null||Ie.focus()})}},[H,ge]),te=o.useCallback(F=>{var re;const U=w.current,q=U==null?void 0:U.getPanel(F);if(!(!U||!q)){q.group.model.openPanel(q),q.api.setActive(),ie(F,"dockview-shortcut");try{const E=q.group.model.location;E.type==="popout"?E.getWindow().focus():Gn((re=q.group.element)==null?void 0:re.ownerDocument)}catch{}}},[ie]),me=o.useCallback(F=>{const U=w.current,q=U==null?void 0:U.activePanel,re=(U==null?void 0:U.activeGroup)||(q==null?void 0:q.group);if(!U||!q||!re)return;const E=re.panels||[];if(E.length<=1)return;const X=E.findIndex(ve=>ve.id===q.id);if(X<0)return;const Z=(X+F+E.length)%E.length,ne=E[Z];ne&&(ne.group.model.openPanel(ne),ne.api.setActive(),Rt(ne.id)||ie(ne.id,"dockview-shortcut"))},[ie]),oe=o.useCallback(F=>{var _e;const U=w.current,q=(U==null?void 0:U.activeGroup)||((_e=U==null?void 0:U.activePanel)==null?void 0:_e.group);if(!U||!q)return;const re=U.groups||[],E=re.find(Ee=>Ee.id===q.id);if(!E)return;const X=E.element.getBoundingClientRect(),Z=X.left+X.width/2,ne=X.top+X.height/2,ve=(Ee,Ie,Ge,Ze)=>Math.max(0,Math.min(Ie,Ze)-Math.max(Ee,Ge)),Ae=Ee=>{const Ie=Ee.element.getBoundingClientRect(),Ge=Ie.left+Ie.width/2,Ze=Ie.top+Ie.height/2;let it=0,lt=0,ht=0,bt=!1;if(F==="left"?(bt=Ge<Z,it=Math.max(0,X.left-Ie.right),lt=Math.abs(Ze-ne),ht=ve(X.top,X.bottom,Ie.top,Ie.bottom)):F==="right"?(bt=Ge>Z,it=Math.max(0,Ie.left-X.right),lt=Math.abs(Ze-ne),ht=ve(X.top,X.bottom,Ie.top,Ie.bottom)):F==="above"?(bt=Ze<ne,it=Math.max(0,X.top-Ie.bottom),lt=Math.abs(Ge-Z),ht=ve(X.left,X.right,Ie.left,Ie.right)):(bt=Ze>ne,it=Math.max(0,Ie.top-X.bottom),lt=Math.abs(Ge-Z),ht=ve(X.left,X.right,Ie.left,Ie.right)),!bt)return Number.POSITIVE_INFINITY;const ze=ht>0?0:120;return it*3+lt+ze};let Le=null,Se=Number.POSITIVE_INFINITY;for(const Ee of re){if(Ee.id===E.id)continue;const Ie=Ae(Ee);Number.isFinite(Ie)&&(Ie>=Se||(Se=Ie,Le=Ee))}return Le||void 0},[]),Y=o.useCallback(F=>{var re;const U=oe(F);if(!U)return;const q=U.activePanel||U.panels[0];q&&(U.model.openPanel(q),q.api.setActive(),Rt(q.id)||ie(q.id,"dockview-focus"),Gn((re=U.element)==null?void 0:re.ownerDocument))},[oe,ie]),V=o.useCallback((F,U)=>{const q=w.current,re=q==null?void 0:q.activePanel,E=(q==null?void 0:q.activeGroup)||(re==null?void 0:re.group);if(!q||!re||!E)return;let X=oe(F);!X&&(U!=null&&U.createGroupIfMissing)&&(X=q.addGroup({referenceGroup:E,direction:F})),X&&(re.api.moveTo({group:X,position:"center"}),re.group.model.openPanel(re),re.api.setActive(),Rt(re.id)||ie(re.id,U!=null&&U.createGroupIfMissing?"dockview-split":"dockview-move"))},[oe,ie]),{isMac:le,tabShortcuts:ke,shortcutListening:ee,setShortcutListening:Pe,saveShortcuts:$e}=Nl({sortedTabKeys:e.map(F=>F.tabKey),onFocus:xe,onSelectTab:te}),Oe=o.useCallback(()=>{var q;const F=w.current;if(!F)return;const U=F.activePanel;if(U){if(Rt(U.id)){const re=((q=U.params)==null?void 0:q.routeId)||U.id.slice(7),E=Pt(e,re);E!=null&&E.tabKey&&Pe(E.tabKey);return}H.has(U.id)&&Pe(U.id)}},[H,te,Pe,e]),He=o.useCallback(F=>{const U=[];return F.metaKey&&U.push(le?"⌘":"Meta"),F.ctrlKey&&U.push("Ctrl"),F.altKey&&U.push(le?"⌥":"Alt"),F.shiftKey&&F.key.length!==1&&U.push(le?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(F.key)?null:(U.push(Al(F.key)),U.join("+"))},[le]),O=o.useCallback(F=>{var U,q;switch(F){case"splitActiveTabRight":V("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":V("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const re=de();re&&ye(re);return}case"popoutActiveTab":{const re=de();re&&we(re);return}case"dockActiveTab":{const re=de();if(!re)return;J(re)?ge(re):ae(re)&&je(re);return}case"focusLeftPane":Y("left");return;case"focusRightPane":Y("right");return;case"focusUpPane":Y("above");return;case"focusDownPane":Y("below");return;case"moveActiveTabToLeftPane":V("left");return;case"moveActiveTabToRightPane":V("right");return;case"moveActiveTabToUpPane":V("above");return;case"moveActiveTabToDownPane":V("below");return;case"selectPreviousGroupTab":me(-1);return;case"selectNextGroupTab":me(1);return;case"setActiveTabShortcut":Oe();return;case"hideCurrentTab":{const re=(q=(U=w.current)==null?void 0:U.activePanel)==null?void 0:q.id;re&&!Rt(re)&&ce(re);return}default:return}},[me,je,Y,ye,de,ce,ae,J,ge,V,we,Oe]);o.useEffect(()=>{if(!C)return;const F=C.sourceDocument,U=F.defaultView??window,q=re=>{const E=F.querySelector("[data-dockview-tab-context-menu]");E&&E.contains(re.target)||I(null)};return U.addEventListener("mousedown",q,!0),U!==window&&window.addEventListener("mousedown",()=>I(null),!0),()=>{U.removeEventListener("mousedown",q,!0),U!==window&&window.removeEventListener("mousedown",()=>I(null),!0)}},[C]);const Ce=o.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:H,hasDetachedConversationPanels:Q,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:g,liveSessionInboxState:S,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:ce,userName:m,scrollToBottomRequest:y,tabShortcuts:ke,openTabContextMenu:({x:F,y:U,tabKey:q,sourceDocument:re})=>I({x:F,y:U,tabKey:q,sourceDocument:re??document}),popoutTab:we,moveTabBackToMain:ge,isTabInPopout:J,floatTab:ye,isTabFloating:ae}),[n,t,H,Q,r,c,l,g,S,a,i,ce,m,y,ke,we,ge,J,ye,ae]),Te=C?tb({isTabInPopout:J(C.tabKey),isTabFloating:ae(C.tabKey),tabShortcut:ke[C.tabKey],actionShortcuts:f}):[],Re=o.useCallback(F=>{var re;const U=w.current;if((((re=U==null?void 0:U.activePanel)==null?void 0:re.id)??null)===F.id){F.group.model.openPanel(F);return}F.group.model.openPanel(F),F.api.setActive()},[]),Be=o.useCallback((F,U="requested-tab")=>{if(!F)return!1;const q=w.current;if(!q)return!1;const re=q.getPanel(F);return re?(Re(re),ie(F,U),p==null||p(),!0):!1},[Re,p,ie]),Fe=o.useCallback(()=>{if(D.current)return!1;const F=Be(K.current,"stored-layout-restore");return F&&(D.current=!0),F},[Be]),Ye=o.useCallback(()=>{var U;const F=w.current;F&&Ph(j,{activeTabId:((U=F.activePanel)==null?void 0:U.id)??null,layout:F.toJSON()})},[j]),tt=o.useCallback(()=>{Eh(j,$.current)},[j]),ut=o.useCallback(F=>{var re,E,X,Z;const U=w.current;if(!U)return{kind:"grid"};const q=U.toJSON();for(const ne of q.floatingGroups||[])if((E=(re=ne.data)==null?void 0:re.views)!=null&&E.includes(F)&&ne.position)return{kind:"floating",position:ne.position};for(const ne of q.popoutGroups||[])if((Z=(X=ne.data)==null?void 0:X.views)!=null&&Z.includes(F))return{kind:"popout",position:ne.position,popoutUrl:ne.url};return{kind:"grid"}},[]),ft=o.useCallback(F=>{const U=w.current;if(!U)return;const q=U.getPanel(F),re=$.current[F];if(!q||!re||re.kind==="grid")return;if(q.group.model.location.type===re.kind){delete $.current[F],tt();return}if(re.kind==="floating"){U.addFloatingGroup(q,{x:re.position.left??24,y:re.position.top??24,width:re.position.width,height:re.position.height}),delete $.current[F],tt();return}delete $.current[F],tt()},[tt]);o.useEffect(()=>(x==null||x({setShortcutForActiveTab:Oe,restoreHiddenTabToSavedLocation:ft,activateConversationTab:te,resetAllPanelsToMain:fe,activatePreviousTabInGroup:()=>me(-1),activateNextTabInGroup:()=>me(1),floatActiveTab:()=>{const F=de();F&&ye(F)},popoutActiveTab:()=>{const F=de();F&&we(F)},dockActiveTab:()=>{const F=de();F&&(J(F)?ge(F):ae(F)&&je(F))},splitActiveTabRight:()=>V("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>V("below",{createGroupIfMissing:!0}),focusLeftPane:()=>Y("left"),focusRightPane:()=>Y("right"),focusUpPane:()=>Y("above"),focusDownPane:()=>Y("below"),moveActiveTabToLeftPane:()=>V("left"),moveActiveTabToRightPane:()=>V("right"),moveActiveTabToUpPane:()=>V("above"),moveActiveTabToDownPane:()=>V("below")}),()=>x==null?void 0:x(null)),[me,je,ye,Y,de,ae,J,V,ge,we,x,fe,ft,te,Oe]),o.useEffect(()=>()=>{var F;(F=B.current)==null||F.call(B),B.current=null},[]);const pt=o.useCallback(F=>{var q,re;w.current=F.api,(q=B.current)==null||q.call(B),B.current=null;const U=_h(j);if(K.current=(U==null?void 0:U.activeTabId)??null,U!=null&&U.layout&&F.api.fromJSON(U.layout,{reuseExistingPanels:!1}),T.current=hi({hasStoredLayout:!!(U!=null&&U.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),T.current||(wi(F.api,e),ji(F.api,e,b)),F.api.totalPanels===0&&e.length>0){const E=lb(F.api,e,k);if(E){const X=F.api.getPanel(E);X&&Re(X)}}else!T.current&&!Be(k)&&Fe();if(_.current=!0,F.api.onDidActivePanelChange(E=>{var Z;if(K.current=(E==null?void 0:E.id)??null,D.current=!0,pe(),E&&Rt(E.id)){const ne=((Z=E.params)==null?void 0:Z.routeId)||E.id.slice(7),ve=Pt(e,ne);N((ve==null?void 0:ve.tabKey)??null),Ye();return}if(N((E==null?void 0:E.id)??null),Ye(),!E)return;const X=H.get(E.id);(X==null?void 0:X.streamSource)==="agent-stream"&&X.agentType&&M(X.routeId,wc(),{agentType:X.agentType,...X.sessionId&&{targetSessionId:X.sessionId}}).catch(()=>{})}),F.api.onDidLayoutChange(()=>{Ye(),pe(),P(E=>E+1)}),ab()){const E=Se=>({clientX:Se.clientX,clientY:Se.clientY}),X=Se=>{const _e=Se==null?void 0:Se.getBoundingClientRect();return _e?{left:_e.left,right:_e.right,top:_e.top,bottom:_e.bottom}:null},Z=Se=>{var Ee;const _e=(Ee=v.current)==null?void 0:Ee.getBoundingClientRect();return _e?Se.clientX<_e.left||Se.clientX>_e.right||Se.clientY<_e.top||Se.clientY>_e.bottom:!1},ne=nb({detachDelayMs:Rl,onDetach:({panelId:Se,clientX:_e,clientY:Ee})=>{var ht,bt;const Ie=F.api.getPanel(Se);if(!Ie)return;try{if(Ie.group.model.location.type!=="grid")return}catch{return}const Ge=(ht=v.current)==null?void 0:ht.getBoundingClientRect(),Ze=(bt=Ie.group.element)==null?void 0:bt.getBoundingClientRect(),it=Math.round(Math.min(Math.max((Ze==null?void 0:Ze.width)??600,360),720)),lt=Math.round(Math.min(Math.max((Ze==null?void 0:Ze.height)??500,260),640));F.api.addFloatingGroup(Ie,{x:Ge?Math.max(0,_e-Ge.left-32):void 0,y:Ge?Math.max(0,Ee-Ge.top-18):void 0,width:it,height:lt}),Ie.api.setActive(),Ye(),pe(),P(ze=>ze+1)}}),ve=[F.api.onWillDragPanel(Se=>{if(!(Se.nativeEvent.defaultPrevented||Se.nativeEvent.shiftKey)){try{if(Se.panel.group.model.location.type!=="grid")return}catch{return}ne.startDrag({panelId:Se.panel.id,selfPanelBounds:X(Se.panel.group.element),...E(Se.nativeEvent)})}}),F.api.onWillShowOverlay(Se=>{if(ne.hasDetached()){Se.preventDefault();return}ne.markDockTarget(E(Se.nativeEvent))}),F.api.onWillDrop(Se=>{if(ne.hasDetached()){Se.preventDefault(),ne.endDrag();return}ne.markDockTarget(E(Se.nativeEvent))}),F.api.onDidDrop(()=>ne.endDrag()),F.api.onUnhandledDragOverEvent(Se=>{ne.isDragging()&&ne.markSelfPanel(E(Se.nativeEvent))})],Ae=Se=>{if(!ne.isDragging())return;const _e=E(Se);Z(_e)&&ne.markNonSelfPanel(_e)},Le=()=>ne.endDrag();window.addEventListener("dragover",Ae,!0),window.addEventListener("drop",Le,!0),window.addEventListener("dragend",Le,!0),B.current=()=>{ne.dispose();for(const Se of ve)Se.dispose();window.removeEventListener("dragover",Ae,!0),window.removeEventListener("drop",Le,!0),window.removeEventListener("dragend",Le,!0)}}F.api.onDidAddGroup(E=>{requestAnimationFrame(()=>{var X,Z;try{const ne=(X=E.element)==null?void 0:X.ownerDocument;if(!ne||ne===document)return;(Z=ne.getElementById("dv-popout-window"))==null||Z.classList.add("adhdev-dockview");const ve=document.documentElement.getAttribute("data-theme");ve&&ne.documentElement.setAttribute("data-theme",ve),ne.body.className=document.body.className;const Ae=document.documentElement.getAttribute("style");Ae&&ne.documentElement.setAttribute("style",Ae)}catch{}pe(),P(ne=>ne+1)})}),N(((re=F.api.activePanel)==null?void 0:re.id)??null)},[Re,Be,H,r,d,j,N,Ye,k,b,M,pe,e]);o.useLayoutEffect(()=>{const F=w.current;if(!F||!_.current||T.current&&hi({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const U=L.current,q=new Set(U),re=e.map(Le=>Le.tabKey),E=new Set(re),X=sb({previousVisibleConversationCount:U.length,visibleConversationCount:e.length,ides:r});let Z=!1;for(const Le of U)E.has(Le)||X||($.current[Le]=ut(Le),Z=!0);Z&&tt(),X||(wi(F,e),ji(F,e,b));const ne=re.filter(Le=>!q.has(Le));let ve=!1;for(const Le of ne){const Se=F.getPanel(Le),_e=$.current[Le];if(!Se||!_e||_e.kind==="grid")continue;if(Se.group.model.location.type===_e.kind){delete $.current[Le],ve=!0;continue}if(_e.kind==="floating"){F.addFloatingGroup(Se,{x:_e.position.left??24,y:_e.position.top??24,width:_e.position.width,height:_e.position.height}),delete $.current[Le],ve=!0;continue}}if(ve&&tt(),L.current=re,k&&Be(k))return;!F.activePanel&&F.panels[0]&&Re(F.panels[0]),!!(F.activePanel&&F.getPanel(F.activePanel.id))||Fe()},[Re,Be,Fe,r,d,tt,ut,k,b,e]),o.useEffect(()=>{_.current&&Be(k)},[Be,k]),o.useEffect(()=>{const F=q=>{const re=q.target;if(!re)return;const E=re.querySelector("[data-tab-key]")||re.closest("[data-tab-key]");if(E){const X=E.getAttribute("data-tab-key");if(X&&q.dataTransfer){const Z=re.closest(".dv-tab")||E.closest(".dv-tab")||E;q.dataTransfer.effectAllowed="move",q.dataTransfer.setData("text/tab-key",X),Z instanceof HTMLElement&&q.dataTransfer.setDragImage(Z,Math.max(12,Math.round(Z.clientWidth/2)),Math.max(10,Math.round(Z.clientHeight/2)))}}};window.addEventListener("dragstart",F);const U=vi(w.current);for(const q of U)q.addEventListener("dragstart",F);return()=>{window.removeEventListener("dragstart",F);for(const q of U)q.removeEventListener("dragstart",F)}},[W]),o.useEffect(()=>{var U;const F=(U=v.current)==null?void 0:U.querySelector(".adhdev-dockview");F instanceof HTMLElement&&qn(F,A),be(),pe()},[pe,be,A]),o.useEffect(()=>{pe()},[pe]),o.useEffect(()=>{const F=U=>{if(U.defaultPrevented||ee)return;const q=He(U);if(!q)return;const re=U.metaKey||U.ctrlKey||U.altKey;Ta(U.target)&&!re||an(le).setActiveTabShortcut!==q||(U.preventDefault(),U.stopPropagation(),Oe())};return window.addEventListener("keydown",F,!0),()=>window.removeEventListener("keydown",F,!0)},[He,le,ee,Oe]),o.useEffect(()=>{const F=v.current;if(!F)return;const U=q=>{var ne,ve;if(!q.isTrusted)return;const re=(ve=(ne=q.target)==null?void 0:ne.closest)==null?void 0:ve.call(ne,".dv-scrollable");if(!re)return;q.preventDefault(),q.stopPropagation();const E=Math.abs(q.deltaX),X=Math.abs(q.deltaY),Z=E>X?q.deltaX:q.deltaY;re.dispatchEvent(new WheelEvent("wheel",{deltaY:Z,deltaMode:q.deltaMode,bubbles:!1,cancelable:!0}))};return F.addEventListener("wheel",U,{passive:!1,capture:!0}),()=>F.removeEventListener("wheel",U,{capture:!0})},[]),o.useEffect(()=>{const F=vi(w.current);if(F.length===0)return;const U=F.map(q=>{let re=[],E=null;const X=()=>{E!=null&&q.clearTimeout(E),E=null,re=[]},Z=()=>{E!=null&&q.clearTimeout(E),E=q.setTimeout(()=>{E=null,re=[]},1200)},ne=Ae=>{if(!Ae.ctrlKey&&!Ae.metaKey&&!Ae.altKey)return;const Le=He(Ae);if(!Le)return;const Se=Sl();for(const[_e,Ee]of Object.entries(Se))if(e.some(Ie=>Ie.tabKey===_e)&&Ee===Le){Ae.preventDefault(),te(_e);return}},ve=Ae=>{if(Ae.defaultPrevented||ee)return;const Le=He(Ae);if(!Le)return;const Se=Ae.metaKey||Ae.ctrlKey||Ae.altKey;if(Ta(Ae.target))return;const _e=an(le),Ee=Object.entries(_e).filter(([ze,he])=>!!he&&(ze==="splitActiveTabRight"||ze==="splitActiveTabDown"||ze==="floatActiveTab"||ze==="popoutActiveTab"||ze==="dockActiveTab"||ze==="focusLeftPane"||ze==="focusRightPane"||ze==="focusUpPane"||ze==="focusDownPane"||ze==="moveActiveTabToLeftPane"||ze==="moveActiveTabToRightPane"||ze==="moveActiveTabToUpPane"||ze==="moveActiveTabToDownPane"||ze==="selectPreviousGroupTab"||ze==="selectNextGroupTab"||ze==="setActiveTabShortcut"||ze==="hideCurrentTab")),Ie=Se?[Le]:[...re.slice(-1),Le].slice(-2),Ge=Ie.join(" "),Ze=Ie[Ie.length-1],it=Ee.find(([,ze])=>ze===Ge);if(it){Ae.preventDefault(),X(),O(it[0]);return}if(Ee.some(([,ze])=>ze.startsWith(`${Ge} `))){Ae.preventDefault(),re=Ie,Z();return}const ht=Ee.find(([,ze])=>ze===Ze);if(ht){Ae.preventDefault(),X(),O(ht[0]);return}if(Ee.some(([,ze])=>ze.startsWith(`${Ze} `))){Ae.preventDefault(),re=[Ze],Z();return}X()};return q.addEventListener("keydown",ne),q.addEventListener("keydown",ve),()=>{X(),q.removeEventListener("keydown",ne),q.removeEventListener("keydown",ve)}});return()=>{for(const q of U)q()}},[He,le,W,te,ee,O,e]);const Ne=A==="light"?ca:la,Ue=((st=(Ve=(Xe=w.current)==null?void 0:Xe.activePanel)==null?void 0:Ve.group.element)==null?void 0:st.ownerDocument)??document;return s.jsxs(Ll.Provider,{value:Ce,children:[s.jsx("div",{ref:v,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(wd,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:db,remote:ub},defaultTabComponent:fb,watermarkComponent:mb,onReady:pt,singleTabMode:"default",tabAnimation:"smooth",theme:Ne,popoutUrl:"/popout.html"})}),C&&rr.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:C.x,top:C.y},children:Te.map(F=>{if(F.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},F.id);let U=s.jsx(xu,{size:13,className:"shrink-0 opacity-70"}),q=()=>{};switch(F.id){case"dockInWindow":case"dockBackToGrid":U=s.jsx(gu,{size:13,className:"shrink-0 opacity-70"}),q=()=>{je(C.tabKey),I(null)};break;case"moveBackToMain":U=s.jsx(hu,{size:13,className:"shrink-0 opacity-70"}),q=()=>{ge(C.tabKey),I(null)};break;case"floatAsPanel":U=s.jsx(bu,{size:13,className:"shrink-0 opacity-70"}),q=()=>{ye(C.tabKey),I(null)};break;case"openInNewWindow":U=s.jsx(pu,{size:13,className:"shrink-0 opacity-70"}),q=()=>{we(C.tabKey),I(null)};break;case"setShortcut":q=re=>{re.stopPropagation(),Pe(C.tabKey),I(null)};break;case"removeShortcut":U=s.jsx(yt,{size:13,className:"shrink-0 opacity-70"}),q=()=>{const re={...ke};delete re[C.tabKey],$e(re),I(null)};break;case"hideTab":U=s.jsx(Ea,{size:13,className:"shrink-0 opacity-70"}),q=()=>{ce(C.tabKey),I(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${F.tone==="muted"?"text-text-muted":""}`,onMouseDown:ib,onClick:q,children:[U,s.jsx("span",{className:"flex-1 min-w-0",children:F.label}),F.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:F.shortcut}):null]},F.id)})}),C.sourceDocument.body),ee&&rr.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:()=>Pe(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:F=>F.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",le?"⌘+1":"Ctrl+1",", ",le?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),Ue.body)]})}const _l="adhdev-recent-launch-args-v1",hb=8;function xb(e){return String(e||"").trim().replace(/\s+/g," ")}function Pl(e,t){return`${e.trim()}::${t.trim()}`}function Dl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(_l)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function bb(e){if(!(typeof window>"u"))try{window.localStorage.setItem(_l,JSON.stringify(e))}catch{}}function El(e,t){var i;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((i=Dl().byKey[Pl(r,n)])==null?void 0:i.items)||[]}function $l(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),i=xb(r);if(!n||!a||!i)return;const c=Dl(),l=Pl(n,a),d=((u=c.byKey[l])==null?void 0:u.items)||[],m=[i,...d.filter(f=>f!==i)].slice(0,hb);c.byKey[l]={items:m},bb(c)}function Bl(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Ur({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 gb({savedSessionsLoading:e,savedSessionsLoaded:t,savedSessionsCount:r=0}){return e?"Refreshing saved history…":t?r>0?`${r} saved ${r===1?"history":"histories"} loaded. Open saved history to choose one.`:"No saved history found yet. New Hermes CLI conversations will appear here after ADHDev captures provider history.":"Start fresh, or open saved history when you want continuity."}function Kl({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:i,onRefresh:c,onOpenHistory:l,onClearSelection:d}){const m=i?wl(i):null,u=gb({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Ur,{title:"Saved history",description:Za(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:c,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:l,children:hp()})]}),children:[m?s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:m.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:m.providerSessionId}),s.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:d,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:u}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function Wl({setup:e,providerName:t,className:r=""}){return e?s.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${r}`,children:[s.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",t?` for ${t}`:""]}),e.instructions&&s.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&s.jsxs("span",{children:["Server: ",s.jsx("code",{children:e.serverName})]}),e.configFormat&&s.jsxs("span",{children:["Format: ",s.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&s.jsxs("span",{children:["Config path: ",s.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&s.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&s.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}function yb({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:i,onSelect:c}){return e==="mesh"?null:s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:r},{id:"ide",label:"IDE",enabled:n},{id:"acp",label:"ACP",enabled:a}].map(l=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===l.id?"btn-primary":"btn-secondary"}`,onClick:()=>c(l.id),disabled:!l.enabled||i,children:l.label},l.id))})]})}function Yn(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>ps(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>ps(a,"acp"))?"acp":null}function Pr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function vb({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:c,onListMeshes:l,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var ze,he;const u=ur(),f=o.useMemo(()=>[...e].sort(Fa),[e]),[x,N]=o.useState(((ze=f[0])==null?void 0:ze.id)||""),g=o.useMemo(()=>f.find(z=>z.id===x)||f[0],[x,f]),h=o.useMemo(()=>((g==null?void 0:g.workspaces)||[]).map(z=>({id:z.id,path:z.path,label:z.label})),[g]),k=(g==null?void 0:g.defaultWorkspaceId)||null,[b,p]=o.useState("workspace"),[y,S]=o.useState(""),[j,A]=o.useState(""),[M,w]=o.useState([]),[v,B]=o.useState(""),[_,T]=o.useState(!1),[D,K]=o.useState(null),[L,C]=o.useState(""),[I,W]=o.useState(Yn(f[0])),[P,$]=o.useState(""),[H,Q]=o.useState(""),[xe,ie]=o.useState([]),[se,be]=o.useState(""),[we,ge]=o.useState([]),[J,ce]=o.useState(!1),[ye,ae]=o.useState(!1),[de,je]=o.useState(""),[fe,pe]=o.useState(!1),[te,me]=o.useState(()=>gt()),[oe,Y]=o.useState(null),[V,le]=o.useState(!1),[ke,ee]=o.useState(""),[Pe,$e]=o.useState(null),[Oe,He]=o.useState(!1),[O,Ce]=o.useState(""),[Te,Re]=o.useState([]),[Be,Fe]=o.useState(!1),[Ye,tt]=o.useState(""),[ut,ft]=o.useState(!1),pt=o.useRef(null),Ne=o.useRef(0);o.useEffect(()=>{var z;!x&&((z=f[0])!=null&&z.id)&&N(f[0].id)},[x,f]),o.useEffect(()=>{!g||!(!g.workspaces||!g.availableProviders||!g.detectedIdes||!g.recentLaunches)||u(g.id,{minFreshMs:3e4}).catch(()=>{})},[u,g]);const Ue=o.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(z=>ps(z,"cli")),[g]),Xe=o.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(z=>ps(z,"acp")),[g]),Ve=o.useMemo(()=>((g==null?void 0:g.detectedIdes)||[]).map(z=>({id:z.type,label:z.name||z.type,meta:z.running?"Detected locally":"Available to open"})),[g]),st=o.useMemo(()=>I==="cli"?Ue.map(z=>({id:z.type,label:z.displayName||z.type,meta:"CLI provider"})):I==="acp"?Xe.map(z=>({id:z.type,label:z.displayName||z.type,meta:"ACP provider"})):Ve,[Xe,I,Ue,Ve]),F=o.useMemo(()=>M.find(z=>z.id===v)||null,[M,v]),U=o.useMemo(()=>Ue.find(z=>z.type===P)||null,[Ue,P]),q=o.useMemo(()=>xl(U==null?void 0:U.meshCoordinator,{meshId:(F==null?void 0:F.id)||"",workspace:(F==null?void 0:F.workspace)||""}),[U,F]),re=Pe||q,E=o.useCallback(async z=>{T(!0),C("");try{const R=await l(z);w(R),B(G=>{var ue;return R.some(De=>De.id===G)?G:((ue=R[0])==null?void 0:ue.id)||""}),K(z)}catch(R){w([]),B(""),K(z),C(R instanceof Error?R.message:"Could not load meshes")}finally{T(!1)}},[l]);o.useEffect(()=>{var R;if(!g)return;if(pt.current!==g.id){pt.current=g.id,p("workspace"),S(k||((R=h[0])==null?void 0:R.id)||"__home__"),A(""),w([]),B(""),K(null),C(""),W(Yn(g)),$(""),Q(""),be(""),ge([]),ae(!1),je(""),me(gt()),ee(""),$e(null);return}S(G=>{var ue;return G==="__custom__"||G==="__home__"||h.some(De=>De.id===G)?G:k||((ue=h[0])==null?void 0:ue.id)||"__home__"}),W(G=>G==="ide"&&Ve.length>0||G==="cli"&&Ue.length>0||G==="acp"&&Xe.length>0?G:Yn(g))},[Xe.length,Ue.length,k,Ve.length,g,h]),o.useEffect(()=>{!g||b!=="mesh"||D===g.id||_||E(g.id)},[E,D,_,g,b]),o.useEffect(()=>{b==="mesh"&&I!=="cli"&&Ue.length>0&&W("cli")},[I,Ue.length,b]),o.useEffect(()=>{var z;I&&(st.some(R=>R.id===P)||$(((z=st[0])==null?void 0:z.id)||""))},[I,st,P]),o.useEffect(()=>{$e(null)},[g==null?void 0:g.id,v,P,b]);const X=o.useCallback(async(z,R)=>{const G=Ne.current+1;return Ne.current=G,ce(!0),je(""),m(z,R).then(ue=>{Ne.current===G&&ge(ue)}).catch(ue=>{Ne.current===G&&(ge([]),je(ue instanceof Error?ue.message:"Could not load saved sessions"))}).finally(()=>{Ne.current===G&&(ce(!1),ae(!0))})},[m]),Z=o.useCallback((z,R)=>{ie(El(z,R))},[]);o.useEffect(()=>{Ne.current+=1,be(""),me(gt()),!g||!P||I==="ide"?ie([]):Z(g.id,P),ae(!1),ge([]),je(""),ce(!1)},[I,Z,X,g,P]),o.useEffect(()=>{if(!se)return;const z=we.find(R=>R.providerSessionId===se);z!=null&&z.canResume||be("")},[we,se]);const ne=y==="__custom__"?j.trim():y==="__home__"?"":((he=h.find(z=>z.id===y))==null?void 0:he.path)||"",ve=o.useMemo(()=>g?t.filter(z=>z.id!==g.id&&z.daemonId===g.id).map(z=>z.workspace):[],[t,g]),Ae=o.useMemo(()=>((g==null?void 0:g.recentLaunches)||[]).map(z=>z.workspace),[g]),Le=o.useCallback(z=>{const R=String(z.workspace||"").trim();if(!R)return;const G=h.find(ue=>Pr(ue.path)===Pr(R));if(G){S(G.id),A("");return}S("__custom__"),A(R)},[h]),Se=o.useCallback(z=>{const R=String(z.workspace||"").trim();if(!R)return{workspaceId:null,workspacePath:null};const G=h.find(ue=>Pr(ue.path)===Pr(R));return G?{workspaceId:G.id,workspacePath:null}:{workspaceId:null,workspacePath:R}},[h]),_e=o.useMemo(()=>we.find(z=>z.providerSessionId===se)||null,[we,se]),Ee=o.useMemo(()=>{var R;if(I!=="cli"||!g||!P)return null;const z=((R=Ue.find(G=>G.type===P))==null?void 0:R.displayName)||P;return{routeId:g.id,daemonId:g.id,providerSessionId:se||void 0,transport:"pty",mode:"chat",agentName:z,agentType:P,status:"idle",title:z,messages:[],ideType:P,workspaceName:ne,workspacePath:ne,displayPrimary:z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${g.id}:${P}`,machineName:Ct(g,{fallbackId:g.id})}},[I,Ue,ne,g,se,P]),Ie=o.useCallback(()=>{var R;if(!g)return;S("__custom__"),He(!0),tt("");const z=xn(g.platform,hn(j.trim(),ne,ve,Ae,g.defaultWorkspacePath,(R=h.find(G=>G.id===k))==null?void 0:R.path,h.map(G=>G.path)));Fe(!0),n(g.id,z).then(G=>{Ce(G.path),A(G.path),Re(G.directories)}).catch(G=>{tt(G instanceof Error?G.message:"Could not load folder")}).finally(()=>Fe(!1))},[j,k,Ae,ve,n,ne,g,h]),Ge=o.useCallback(z=>{g&&(Fe(!0),tt(""),n(g.id,z).then(R=>{Ce(R.path),A(R.path),Re(R.directories)}).catch(R=>{tt(R instanceof Error?R.message:"Could not load folder")}).finally(()=>Fe(!1)))},[n,g]),Ze=o.useCallback(async()=>{if(!g||!ne)return;ft(!0),ee("");const z=await a(g.id,ne);if(ft(!1),!z.ok){ee(z.error||"Could not save workspace");return}ee("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,ne,g]),it=o.useCallback(async()=>{if(!g)return;if(b==="mesh"){if(!v||!P)return;le(!0),ee(""),$e(null);const G=await d(g.id,v,P);if(le(!1),!G.ok){if(G.code==="mesh_coordinator_manual_mcp_setup_required"&&G.manualSetup){$e(G.manualSetup),ee("Manual MCP setup required before this provider can act as mesh coordinator.");return}ee(G.error||"Could not start mesh coordinator");return}r();return}if(!I||!P)return;le(!0),ee("");const z=H.trim()?H.trim().split(/\s+/).filter(Boolean):[],R=I==="ide"?await i(g.id,P,{workspacePath:ne||null}):await c(g.id,I,P,{workspaceId:y!=="__home__"&&y!=="__custom__"?y:null,workspacePath:y==="__custom__"&&ne||null,resumeSessionId:I==="cli"&&se?se:null,cliArgs:z});if(le(!1),!R.ok){ee(R.error||"Could not start session");return}I!=="ide"&&H.trim()&&($l(g.id,P,H),Z(g.id,P)),r()},[I,H,Z,r,i,d,c,ne,g,v,se,P,y,b]),lt=b==="mesh"?"Start mesh coordinator":I?Oc(I,I==="cli"&&!!se):"Start",ht=b==="mesh"?"Starting coordinator…":I?Fc(I,I==="cli"&&!!se):"Starting…",bt=f.length>5;return g?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(yt,{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(Ur,{title:"Machine",children:bt?s.jsx("select",{"aria-label":"Machine",value:g.id,onChange:z=>N(z.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:V,children:f.map(z=>s.jsx("option",{value:z.id,children:Ct(z,{fallbackId:z.id})},z.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:f.map(z=>{const R=Ct(z,{fallbackId:z.id}),G=g.id===z.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${R}`,"aria-pressed":G,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${G?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>N(z.id),disabled:V,title:R,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${z.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:R})]},z.id)})})}),s.jsxs(Ur,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:b==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ie,disabled:V,children:"Browse…"}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":"Launch target type",children:[{id:"workspace",label:"Workspace",desc:"Normal session"},{id:"mesh",label:"Mesh",desc:"Coordinator session"}].map(z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":b===z.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${b===z.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{p(z.id),ee(""),z.id==="mesh"&&g&&D!==g.id&&!_&&E(g.id)},disabled:V,children:[s.jsx("div",{className:"text-sm font-semibold",children:z.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:z.desc})]},z.id))}),b==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:y,onChange:z=>{const R=z.target.value;S(R),R==="__custom__"?Ie():ee("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:V,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),h.map(z=>s.jsxs("option",{value:z.id,children:[z.id===k?"⭐ ":"",mn(z.path,z.label)||z.path]},z.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y==="__home__"?"Launch without a workspace.":ne||"Select a workspace folder."}),y==="__custom__"&&ne&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ie,disabled:V,children:[s.jsx(us,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ze,disabled:V||ut,children:ut?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[_&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!_&&L&&s.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:L}),!_&&!L&&M.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker."}),M.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:M.map(z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":v===z.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>B(z.id),disabled:V,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:z.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[z.repoIdentity||"Repo mesh",typeof z.nodesCount=="number"?` · ${z.nodesCount} node${z.nodesCount===1?"":"s"}`:""]}),z.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",z.workspace]})]},z.id))}),F&&s.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),s.jsx(yb,{workspaceMode:b,activeKind:I,cliEnabled:Ue.length>0,ideEnabled:Ve.length>0,acpEnabled:Xe.length>0,busy:V,onSelect:W}),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:I==="ide"?"Choose IDE":I==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[st.map(z=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${P===z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(z.id),disabled:V,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:z.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:z.meta})]},z.id)),st.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."})]})]}),b==="mesh"&&re&&s.jsx(Wl,{setup:re,providerName:(U==null?void 0:U.displayName)||(U==null?void 0:U.name)||P}),b!=="mesh"&&I!=="ide"&&s.jsxs(Ur,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:H,onChange:z=>Q(z.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:V}),xe.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:xe.map(z=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>Q(z),disabled:V,title:z,children:z},z))})]}),b!=="mesh"&&I==="cli"&&s.jsx(Kl,{busy:V,savedSessionsLoading:J,savedSessionsError:de,selectedSession:_e,onRefresh:()=>{!g||!P||X(g.id,P)},onOpenHistory:()=>{!g||!P||(pe(!0),Bl({hasLoadedInitialResults:ye,isLoading:J})&&X(g.id,P))},onClearSelection:()=>be("")}),ke&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ke.includes("saved")||ke.includes("requested")||ke.includes("Manual MCP setup")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:ke})]}),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:V,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:it,disabled:V||(b==="mesh"?!v||!P||I!=="cli"||_:!I||!P||y==="__custom__"&&!ne),children:[s.jsx(Ba,{size:14}),V?ht:lt]})]})]})}),Oe&&s.jsx(gn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:O,directories:Te,busy:Be,error:Ye,onClose:()=>He(!1),onNavigate:Ge,onConfirm:z=>{A(z),Ce(z),S("__custom__"),He(!1)}}),fe&&Ee&&s.jsx(so,{activeConv:Ee,ides:[],isCreatingChat:!1,isRefreshingHistory:J,savedSessions:we,isSavedSessionsLoading:J,isResumingSavedSessionId:oe,savedHistoryFilters:te,missingWorkspaceResumePath:ne||null,onSavedHistoryFiltersChange:me,onClose:()=>pe(!1),onNewChat:()=>{be(""),pe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!g||!P||X(g.id,P)},onResumeSavedSession:z=>{if(!g||!P||oe||!z.canResume)return;const R=Se(z);be(z.providerSessionId),Le(z),Y(z.providerSessionId),pe(!1),le(!0),ee(""),c(g.id,"cli",P,{workspaceId:R.workspaceId,workspacePath:R.workspacePath,resumeSessionId:z.providerSessionId}).then(G=>{if(!G.ok){ee(G.error||"Could not resume session");return}r()}).finally(()=>{le(!1),Y(G=>G===z.providerSessionId?null:G)})}})]}):null}function wb(e,t){const{sendCommand:r}=xt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);o.useEffect(()=>{if(!e||!t){a(null);return}c(!0),r(e,"git_remote_url",{workspace:t}).then(d=>{const m=(d==null?void 0:d.result)??d;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>c(!1))},[e,t,r]);const l=jb(n);return{remoteUrl:n,githubUrl:l,loading:i}}function jb(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const r=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return r?`https://github.com/${r[1]}`:null}const Ol=5e3;function kb(e){return`git:${e}`}function Sb({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Ol}){return{type:"subscribe",topic:"workspace.git",key:kb(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function ho(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function hs(e,t){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const r=e;if(typeof r.error=="string"&&r.error.trim())return r.error;if(typeof r.message=="string"&&r.message.trim())return r.message}return t}function Nb(e){const t=ho(e);return(t==null?void 0:t.success)===!1?{status:null,error:hs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:hs(t,"Git status response did not include status")}}function Cb(e){const t=ho(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:hs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:hs(t,"Git diff summary response did not include diffSummary")}}function Xn(e){return e===void 0||typeof e=="boolean"}function Tb(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Xn(t.binary)&&Xn(t.truncated)&&Xn(t.staged)}function Mb(e){const t=ho(e);return(t==null?void 0:t.success)===!1?{diff:null,error:hs(t,"Git file diff request failed")}:Tb(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:hs(t,"Git file diff response did not include a valid diff object")}}function Ab({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Ol}){const{sendCommand:i,sendData:c}=xt(),l=typeof t=="string"?t.trim():"",d=!!(r&&e&&l),[m,u]=o.useState(null),[f,x]=o.useState(null),[N,g]=o.useState(!1),[h,k]=o.useState(null),b=o.useCallback(async()=>{if(!(!d||!e||!l)){g(!0),k(null);try{const y=Nb(await i(e,"git_status",{workspace:l}));if(y.error){u(null),x(null),k(y.error);return}if(u(y.status),!n){x(null);return}const S=Cb(await i(e,"git_diff_summary",{workspace:l}));if(S.error){x(null),k(S.error);return}x(S.diffSummary)}catch(y){k(hs(y,"Git status request failed"))}finally{g(!1)}}},[d,e,n,i,l]),p=o.useMemo(()=>l?Sb({workspace:l,includeDiffSummary:n,intervalMs:a}):null,[n,a,l]);return o.useEffect(()=>{if(!d||!e||!l||!p){u(null),x(null),g(!1),k(null);return}const y=c?Ht.subscribe({sendData:c},e,p,S=>{var j,A;S.workspace===l&&(u(S.status),x(S.diffSummary??null),k(((j=S.status)==null?void 0:j.error)||((A=S.diffSummary)==null?void 0:A.error)||null),g(!1))},{retryIntervalMs:1e3}):null;return b(),()=>{y==null||y()}},[d,e,b,p,c,l]),{status:m,diffSummary:f,loading:N,error:h,refresh:b}}const Ib={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},Rb={added:"text-emerald-400",modified:"text-orange-400",deleted:"text-red-400",renamed:"text-sky-400",copied:"text-sky-400",untracked:"text-zinc-400",conflict:"text-red-400 font-bold"};function ki(e){return e.split("/").pop()??e}function Lb(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function _b({files:e,truncated:t,onFileClick:r,selectedPath:n,className:a=""}){return e.length===0?s.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):s.jsxs("div",{className:`flex flex-col ${a}`,children:[s.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(i=>{const c=n===i.path,l=Ib[i.status]??"?",d=Rb[i.status]??"text-zinc-400",m=Lb(i.path),u=ki(i.path),f=i.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${c?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(i),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:i.status,children:l}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&s.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),s.jsx("span",{className:"text-text-primary",children:u}),i.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",ki(i.oldPath)]}),f]}),!i.binary&&(i.insertions>0||i.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[i.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",i.insertions]}),i.insertions>0&&i.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),i.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",i.deletions]})]}),i.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${i.path}-${i.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function Pb(e,t){let r="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?r="bg-emerald-500/10 text-emerald-300":e.startsWith("-")&&!e.startsWith("---")?r="bg-red-500/10 text-red-300":e.startsWith("@@")?r="text-sky-400":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(r="text-text-secondary"),s.jsx("div",{className:`px-3 ${r}`,children:s.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function Db({diff:e,binary:t,truncated:r,loading:n,error:a,className:i=""}){const c=o.useRef(null);if(o.useEffect(()=>{c.current&&(c.current.scrollTop=0)},[e]),n)return s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${i}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${i}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${i}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${i}`,children:"No diff available."});const l=e.split(`
|
|
63
|
-
`);return s.jsxs("div",{ref:c,className:`overflow-auto ${i}`,children:[s.jsx("div",{className:"py-1",children:l.map((d,m)=>Pb(d,m))}),r&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",s.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function Eb(e,t){const r=[`Branch: ${e||"unknown"}`];r.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const n={};for(const a of t.files)n[a.status]||(n[a.status]=[]),n[a.status].push(a.path);for(const[a,i]of Object.entries(n))r.push(`${a}: ${i.slice(0,5).join(", ")}${i.length>5?` (+${i.length-5} more)`:""}`);return r.join(`
|
|
64
|
-
`)}function Fl({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=xt(),{status:a,diffSummary:i,loading:c,error:l,refresh:d}=Ab({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=o.useState(null),[f,x]=o.useState(null),[N,g]=o.useState(""),[h,k]=o.useState(!1),[b,p]=o.useState(!1),[y,S]=o.useState(null),[j,A]=o.useState(null),{githubUrl:M}=wb(e,t),w=o.useCallback(async K=>{if(!((m==null?void 0:m.path)===K.path&&!m.loading)){u({path:K.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const L=await n(e,"git_diff_file",{workspace:t,path:K.path,staged:K.staged}),C=Mb(L);if(C.error||!C.diff){u({path:K.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C.error??"Failed to load diff"});return}u({path:K.path,diff:C.diff.diff,binary:C.diff.binary??!1,truncated:C.diff.truncated??!1,loading:!1,error:null})}catch(L){const C=L instanceof Error?L.message:"Failed to load diff";u({path:K.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C})}}},[e,n,m,t]),v=o.useCallback(K=>{g(""),k(!1),S(null),A(null),x(K)},[]),B=o.useCallback(()=>{x(null),S(null),p(!1)},[]),_=o.useCallback(async()=>{var K,L,C;if(f){p(!0),S(null);try{let I;f==="checkpoint"?I=await n(e,"git_checkpoint",{workspace:t,message:N,includeUntracked:h}):f==="stash"?I=await n(e,"git_stash_push",{workspace:t,message:N,includeUntracked:h}):f==="stash_pop"?I=await n(e,"git_stash_pop",{workspace:t}):f==="checkout_files"&&m&&(I=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const W=(I==null?void 0:I.result)??I;if((W==null?void 0:W.success)===!1||W!=null&&W.error){S((W==null?void 0:W.error)??"Action failed"),p(!1);return}f==="checkpoint"?A(`Checkpoint created: ${((L=(K=W==null?void 0:W.checkpoint)==null?void 0:K.commit)==null?void 0:L.slice(0,7))??"done"}`):f==="stash"?A(`Stashed as ${((C=W==null?void 0:W.stash)==null?void 0:C.stashRef)??"stash@{0}"}`):f==="stash_pop"?A("Stash restored"):(A("File reverted"),u(null)),x(null),await d()}catch(I){S(I instanceof Error?I.message:"Action failed")}finally{p(!1)}}},[f,n,e,t,N,h,m,d]),T=!!(a!=null&&a.hasConflicts),D=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:K=>{K.target===K.currentTarget&&r()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),M&&s.jsx("a",{href:`${M}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:d,disabled:c,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(yt,{className:"h-4 w-4"})})]}),a&&s.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[a.headCommit&&s.jsxs("span",{title:a.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&s.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&s.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&s.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&s.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&s.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&s.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),D===0&&!a.error&&s.jsx("span",{className:"text-emerald-500",children:"clean"}),i&&i.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[i.files.length," file",i.files.length!==1?"s":"",i.totalInsertions>0&&s.jsxs("span",{className:"text-emerald-500",children:[" +",i.totalInsertions]}),i.totalDeletions>0&&s.jsxs("span",{className:"text-red-400",children:[" -",i.totalDeletions]})]})]}),l&&s.jsx("div",{className:"shrink-0 border-b border-border/50 bg-red-500/10 px-4 py-2 text-xs text-red-400",children:l}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[c&&!i&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),i&&s.jsx(_b,{files:i.files,truncated:i.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:w}),!c&&!i&&!l&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?s.jsx(Db,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),j&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-emerald-500/10 px-4 py-2 text-xs text-emerald-400 flex items-center justify-between",children:[s.jsx("span",{children:j}),s.jsx("button",{onClick:()=>A(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>v("checkpoint"),disabled:T,title:T?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>v("stash"),disabled:T,title:T?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>v("stash_pop"),disabled:T||!(a!=null&&a.stashCount),title:T?"Resolve conflicts before restoring a stash":a!=null&&a.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>v("checkout_files"),disabled:!m,title:m?`Revert changes to ${m.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),i&&i.files.length>0&&s.jsx("button",{onClick:()=>{const K=Eb((a==null?void 0:a.branch)??null,i);navigator.clipboard.writeText(K),A("Copied to clipboard"),setTimeout(()=>A(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),f&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[f==="checkpoint"&&"Create checkpoint commit",f==="stash"&&"Stash changes",f==="stash_pop"&&"Restore latest stash?",f==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(f==="checkpoint"||f==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:N,onChange:K=>g(K.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-alt px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:h,onChange:K=>k(K.target.checked)}),"Include untracked files"]})]}),y&&s.jsx("p",{className:"text-xs text-red-400",children:y}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:B,disabled:b,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:_,disabled:b||(f==="checkpoint"||f==="stash")&&!N.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:b?"Working…":"Confirm"})]})]})})]})})}function $b({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=o.useState(!1),[i,c]=o.useState(!1),[l,d]=o.useState(!1),[m,u]=o.useState(!1),[f,x]=o.useState(!1),[N,g]=o.useState("quickstart"),[h,k]=o.useState("workspace"),b=o.useMemo(()=>!t&&!e,[t,e]),p=o.useCallback(w=>{a(w),w&&c(!1)},[]),y=o.useCallback(w=>{c(w),w&&a(!1)},[]),S=o.useCallback(()=>{g(r===0?"quickstart":"shortcuts"),k("workspace"),d(!0),a(!1),c(!1)},[r]),j=o.useCallback(()=>{d(!1)},[]),A=o.useCallback(()=>{u(!0)},[]),M=o.useCallback(()=>{u(!1)},[]);return o.useEffect(()=>{if(!b){x(!1);return}x(!0);const w=window.setTimeout(()=>{x(!1)},1e4);return()=>window.clearTimeout(w)},[b]),{inboxOpen:n,hiddenOpen:i,shortcutHelpOpen:l,newSessionOpen:m,guideNudgeVisible:f,guideTab:N,shortcutSection:h,isDesktopDashboard:b,setGuideTab:g,setShortcutSection:k,handleInboxOpenChange:p,handleHiddenOpenChange:y,handleOpenShortcutHelp:S,closeShortcutHelp:j,openNewSession:A,closeNewSession:M}}function Bb(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 Kb(e){return e instanceof Error?e.message:String(e||"")}function Wb(e){const t=Kb(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Ob({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:f,ides:x,actionLogs:N,sendDaemonCommand:g,setActionLogs:h,setCliViewModeOverrides:k,isStandalone:b,initialDataLoaded:p,userName:y,requestedMobileTabKey:S,onRequestedMobileTabConsumed:j,requestedMachineId:A,onRequestedMachineConsumed:M,requestedMobileSection:w,onRequestedMobileSectionConsumed:v,containerRef:B,isSplitMode:_,numGroups:T,groupSizes:D,groupedConvs:K,clearedTabs:L,focusedGroup:C,focusGroup:I,moveTabToGroup:W,splitTabRelative:P,closeGroup:$,handleResizeStart:H,groupActiveTabIds:Q,setGroupActiveTab:xe,groupTabOrders:ie,setGroupTabOrder:se,toggleHiddenTab:be,visibleConversations:we,requestedDesktopTabKey:ge,onRequestedDesktopTabConsumed:J,onDesktopActiveTabChange:ce,onRequestScrollToBottom:ye,onHideConversation:ae,onShowHiddenConversation:de,onShowAllHiddenConversations:je,scrollToBottomRequest:fe,machineEntries:pe,layoutProfile:te,onBrowseMachineDirectory:me,onSaveMachineWorkspace:oe,onLaunchMachineIde:Y,onLaunchMachineProvider:V,onListMachineMeshes:le,onLaunchMeshCoordinator:ke,onListMachineSavedSessions:ee,notifications:Pe,notificationUnreadCount:$e,liveSessionInboxState:Oe,onMarkNotificationRead:He,onMarkNotificationUnread:O,onDeleteNotification:Ce}){const Te=Nt.useRef(null),{inboxOpen:Re,hiddenOpen:Be,shortcutHelpOpen:Fe,newSessionOpen:Ye,guideNudgeVisible:tt,guideTab:ut,shortcutSection:ft,isDesktopDashboard:pt,setGuideTab:Ne,setShortcutSection:Ue,handleInboxOpenChange:Xe,handleHiddenOpenChange:Ve,handleOpenShortcutHelp:st,closeShortcutHelp:F,openNewSession:U,closeNewSession:q}=$b({isMobile:t,showMobileChatMode:e,visibleConversationCount:we.length}),[re,E]=Nt.useState(null),X=Nt.useCallback((he,z)=>{E({daemonId:he,workspace:z})},[]),Z=Nt.useCallback(he=>{var z;rr.flushSync(()=>{de(he)}),(z=Te.current)==null||z.restoreHiddenTabToSavedLocation(he.tabKey)},[de]),ne=Nt.useCallback(he=>{var R;const z=u.find(G=>ga(G,he))||f.find(G=>ga(G,he));z&&(f.some(G=>G.tabKey===z.tabKey)&&Z(z),ce(z.tabKey),(R=Te.current)==null||R.activateConversationTab(z.tabKey),ye(z.tabKey,"notification-open")),He(he.id),Xe(!1)},[Z,f,u,ce,He,ye]),ve=Nt.useCallback(()=>{var z;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((z=Te.current)==null||z.resetAllPanelsToMain(),Ve(!1))},[Ve]),Ae=Nt.useCallback(async he=>{var De;if(!r)return;const z=(De=r.modalButtons)==null?void 0:De[he];if(!z)return;const R=Is(r);if(!R)return;const G=z.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),ue=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(G);try{await g(R,"resolve_action",{button:z,action:ue?"approve":"reject",buttonIndex:he,...ss(r)})}catch(Me){Wb(Me)||console.error("[Shortcut approval] Failed:",Me)}},[r,g]),{isMac:Le,actionDefinitions:Se,actionShortcuts:_e,shortcutListening:Ee,shortcutListeningDraft:Ie,setShortcutListening:Ge,setShortcutListeningDraft:Ze,saveShortcuts:it}=eb({enabled:pt&&!Fe,onTrigger:he=>{var z,R,G,ue,De,Me,Ke,at,St,mt,Vt,pr,hr,xr,br,gr;if(he==="openShortcutHelp"){st();return}if(he==="openNewSession"){U();return}if(he==="hideCurrentTab"){r&&ae(r);return}if(he==="toggleHiddenTabs"){Ve(!Be);return}if(he==="openHistoryForActiveTab"){r&&!Qe(r)&&i(r);return}if(he==="openRemoteForActiveTab"){r&&!et(r)&&!Qe(r)&&c(r);return}if(he==="splitActiveTabRight"){(z=Te.current)==null||z.splitActiveTabRight();return}if(he==="splitActiveTabDown"){(R=Te.current)==null||R.splitActiveTabDown();return}if(he==="floatActiveTab"){(G=Te.current)==null||G.floatActiveTab();return}if(he==="popoutActiveTab"){(ue=Te.current)==null||ue.popoutActiveTab();return}if(he==="dockActiveTab"){(De=Te.current)==null||De.dockActiveTab();return}if(he==="focusLeftPane"){(Me=Te.current)==null||Me.focusLeftPane();return}if(he==="focusRightPane"){(Ke=Te.current)==null||Ke.focusRightPane();return}if(he==="focusUpPane"){(at=Te.current)==null||at.focusUpPane();return}if(he==="focusDownPane"){(St=Te.current)==null||St.focusDownPane();return}if(he==="moveActiveTabToLeftPane"){(mt=Te.current)==null||mt.moveActiveTabToLeftPane();return}if(he==="moveActiveTabToRightPane"){(Vt=Te.current)==null||Vt.moveActiveTabToRightPane();return}if(he==="moveActiveTabToUpPane"){(pr=Te.current)==null||pr.moveActiveTabToUpPane();return}if(he==="moveActiveTabToDownPane"){(hr=Te.current)==null||hr.moveActiveTabToDownPane();return}if(he==="triggerPrimaryApprovalAction"){Ae(0);return}if(he==="triggerSecondaryApprovalAction"){Ae(1);return}if(he==="triggerTertiaryApprovalAction"){Ae(2);return}if(he==="setActiveTabShortcut"){(xr=Te.current)==null||xr.setShortcutForActiveTab();return}if(he==="selectPreviousGroupTab"){(br=Te.current)==null||br.activatePreviousTabInGroup();return}if(he==="selectNextGroupTab"){(gr=Te.current)==null||gr.activateNextTabInGroup();return}!r||!et(r)||Qe(r)||he==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),lt=Nt.useCallback(()=>{F(),Ge(null),Ze([])},[F,Ge,Ze]),ht=Nt.useMemo(()=>ft==="all"?Se:Se.filter(he=>Bb(he)===ft),[Se,ft]),bt=Nt.useCallback(()=>{const he=Object.fromEntries(Se.map(z=>[z.id,""]));it(he)},[Se,it]),ze=Nt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const he=Object.fromEntries(Se.map(z=>[z.id,z.defaultShortcut]));it(he)},[Se,it]);return Nt.useEffect(()=>{const he=z=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?z.metaKey&&z.key.toLowerCase()==="w":z.ctrlKey&&z.key.toLowerCase()==="w")&&(z.preventDefault(),r&&ae&&ae(r))};return window.addEventListener("keydown",he),()=>window.removeEventListener("keydown",he)},[r,ae]),Nt.useEffect(()=>{if(!Fe||Ee)return;const he=z=>{z.key==="Escape"&&(z.preventDefault(),lt())};return window.addEventListener("keydown",he,!0),()=>window.removeEventListener("keydown",he,!0)},[lt,Fe,Ee]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(lp,{activeConv:r,wsStatus:n,isConnected:a,conversations:we,hiddenConversations:f,onOpenHistory:i,onHideConversation:ae,onShowConversation:Z,onShowAllHidden:je,onResetPanelsToMain:ve,notifications:Pe,notificationUnreadCount:$e,onOpenNotification:ne,onMarkNotificationRead:He,onMarkNotificationUnread:O,onDeleteNotification:Ce,inboxOpen:Re,onInboxOpenChange:Xe,hiddenOpen:Be,onHiddenOpenChange:Ve,onOpenNewSession:t?void 0:U,onOpenDashboardGuide:st,guideNudgeVisible:tt,actionShortcuts:_e,onOpenRemote:()=>{!r||et(r)||Qe(r)||c(r)},onStopCli:l,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:X}),e?s.jsx(Fx,{conversations:u,hiddenConversations:f,ides:x,actionLogs:N,sendDaemonCommand:g,setActionLogs:h,setCliViewModeOverrides:k,isStandalone:b,userName:y,requestedActiveTabKey:S,onRequestedActiveTabConsumed:j,requestedMachineId:A,onRequestedMachineConsumed:M,requestedMobileSection:w,onRequestedMobileSectionConsumed:v,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowAllHiddenConversations:je,onHideConversation:ae,onOpenNewSession:U,liveSessionInboxState:Oe}):t?s.jsx(Xx,{containerRef:B,isSplitMode:_,numGroups:T,groupSizes:D,groupedConvs:K,clearedTabs:L,ides:x,actionLogs:N,sendDaemonCommand:g,setActionLogs:h,isStandalone:b,hasRegisteredMachines:pe.length>0,userName:y,focusedGroup:C,focusGroup:I,moveTabToGroup:W,splitTabRelative:P,closeGroup:$,handleResizeStart:H,groupActiveTabIds:Q,setGroupActiveTab:xe,groupTabOrders:ie,setGroupTabOrder:se,toggleHiddenTab:be,onOpenNewSession:U,allowTabShortcuts:!1,liveSessionInboxState:Oe}):s.jsx(pb,{visibleConversations:we,clearedTabs:L,ides:x,actionLogs:N,sendDaemonCommand:g,setActionLogs:h,isStandalone:b,hasRegisteredMachines:pe.length>0,initialDataLoaded:p,userName:y,toggleHiddenTab:be,actionShortcuts:_e,registerActionHandlers:he=>{Te.current=he},onActiveTabChange:ce,requestedActiveTabKey:ge,onRequestedActiveTabConsumed:J,onRequestScrollToBottom:ye,scrollToBottomRequest:fe,onOpenNewSession:U,liveSessionInboxState:Oe,layoutProfile:te}),Ye&&s.jsx(vb,{machines:pe,ides:x,onClose:q,onBrowseDirectory:me,onSaveWorkspace:oe,onLaunchIde:Y,onLaunchProvider:V,onListMeshes:le,onLaunchMeshCoordinator:ke,onListSavedSessions:ee}),re&&s.jsx(Fl,{daemonId:re.daemonId,workspace:re.workspace,onClose:()=>E(null)}),Fe&&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:lt,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:he=>he.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:lt,"aria-label":"Close dashboard guide",children:s.jsx(yt,{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(he=>s.jsx("button",{type:"button",className:`btn btn-sm ${ut===he.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ne(he.id),children:he.label},he.id))}),ut==="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 ",Le?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),ut==="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."]})]})]})]}),ut==="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(he=>s.jsx("button",{type:"button",className:`btn btn-sm ${ft===he.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ue(he.id),children:he.label},he.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:bt,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:ze,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:ht.map(he=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ee===he.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:he.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:he.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:he.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:Ee===he.id?Ie.length>0?`${Ie.join(" ")} ...`:"Listening...":_e[he.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Ge(he.id),Ze([])},children:Ee===he.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const z={..._e};z[he.id]="",it(z)},children:"Disable"})]})]})},he.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Le?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const Jn=[{icon:"🦦",title:"Welcome to ADHDev",desc:"Monitor and control your AI coding agents from anywhere — web, mobile, or CLI.",visual:"🎉"},{icon:"💬",title:"Real-time chat",desc:"See what your AI agent is doing in real-time. Send messages, approve or reject actions — all from your browser or phone.",visual:"📱"},{icon:"🖥️",title:"Remote desktop",desc:"View and control your IDE screen via P2P connection. Click, type, scroll — just like being there.",visual:"🖱️"},{icon:"🚀",title:"Get started",desc:"Install the daemon and link it to your dashboard. It connects automatically.",code:"npm install -g @adhdev/daemon-standalone && adhdev-standalone"}];function Fb({onClose:e}){const[t,r]=o.useState(0),n=Jn[t],a=t===Jn.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(yt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Jn.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:`
|
|
65
|
-
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
66
|
-
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
67
|
-
`})]})}function Hb({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",d=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)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"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 Ub({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,c]=o.useState(()=>a||"native"),l=o.useMemo(()=>Uc(t),[t]),d=o.useMemo(()=>e?ro(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),m=o.useMemo(()=>d.find(h=>h.streamSource==="native"),[d]),u=o.useMemo(()=>d.filter(h=>h.streamSource==="agent-stream"),[d]),f=o.useMemo(()=>e?Pt(d,e.id):null,[d,e]);o.useEffect(()=>{a&&c(a)},[a]),o.useEffect(()=>{if(a||!f)return;const h=f.streamSource==="native"?"native":f.tabKey;!h||i===h||i==="native"&&c(h)},[i,f,a]),o.useEffect(()=>{var h;i!=="native"&&(u.some(k=>k.tabKey===i)||c(((h=u[0])==null?void 0:h.tabKey)||"native"))},[i,u]),o.useEffect(()=>{i==="native"&&(m||u[0]&&c(u[0].tabKey))},[i,m,u]);const x=o.useMemo(()=>i==="native"&&m?m:u.find(h=>h.tabKey===i)||f||m||u[0],[i,m,f,u]),N=o.useMemo(()=>u.map(h=>({tabKey:h.tabKey,title:$c(h)||n,status:h.status})),[u,n]),g=o.useCallback(h=>{if(h)return d.find(k=>ga(k,{sessionId:h,routeId:h,tabKey:h,providerSessionId:h}))},[d]);return{activeChatTab:i,setActiveChatTab:c,activeConv:x,conversations:d,extensionTabs:N,hasExtensions:N.length>0,resolveConversationByTarget:g}}function zb({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:i,setActionLogs:c,isStandalone:l,userName:d,onOpenHistory:m,onConversationChange:u,onClose:f}){const[x,N]=o.useState("split"),[g,h]=o.useState(()=>Yt(e)?"native":e.tabKey),k=o.useRef(null),b=o.useMemo(()=>t||r.find(I=>I.id===e.routeId),[e.routeId,t,r]),p=o.useMemo(()=>ot((b==null?void 0:b.type)||""),[b==null?void 0:b.type]),{conversations:y,extensionTabs:S,hasExtensions:j}=Ub({ideData:b,allIdes:r,connectionStates:n,ideName:p||"IDE",preferredTabKey:Yt(e)?void 0:e.tabKey}),A=o.useMemo(()=>b?Pt(y,b.id):null,[b,y]);o.useEffect(()=>{const I=k.current,W={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(k.current=W,!(I&&I.routeId===W.routeId&&I.tabKey===W.tabKey&&I.streamSource===W.streamSource)){if(Yt(e)){h("native");return}h(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(g==="native"){if(y.some(I=>I.streamSource==="native"))return;(A==null?void 0:A.streamSource)==="agent-stream"&&h(A.tabKey);return}if(!y.some(I=>I.tabKey===g)){if((A==null?void 0:A.streamSource)==="agent-stream"){h(A.tabKey);return}h("native")}},[y,g,A]);const M=o.useMemo(()=>g==="native"?y.find(I=>I.streamSource==="native")||e:y.find(I=>I.tabKey===g)||e,[e,y,g]),w=sl(M),v=o.useMemo(()=>w.status||w.modalMessage||w.modalButtons?{...M,...w.status?{status:w.status}:{},...w.modalMessage!==void 0?{modalMessage:w.modalMessage}:{},...w.modalButtons!==void 0?{modalButtons:w.modalButtons}:{}}:M,[M,w]),B=dr(v),_=pn({sendDaemonCommand:i,activeConv:v,setActionLogs:c,isStandalone:l}),{connScreenshot:T,screenshotUsage:D,handleRemoteAction:K}=Cl({doId:B,targetSessionId:vc(v),connState:v.connectionState||"new",viewMode:x}),L=o.useMemo(()=>a.filter(I=>I.routeId===v.tabKey),[a,v.tabKey]);o.useEffect(()=>{u==null||u(v)},[v,u]),o.useEffect(()=>{const I=W=>{W.key==="Escape"&&f()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[f]);const C=o.useCallback(I=>{I.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:f,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:C,children:[s.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Tt,{size:16})}),s.jsx("span",{className:"truncate",children:za(M)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:f,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(I=>{const W=x===I;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${W?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>N(I),title:I==="split"?"Split view":"Remote only",children:I==="split"?s.jsx(su,{size:15}):s.jsx(Tt,{size:15})},I)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>m(M),title:"Chat History",children:[s.jsx(Da,{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:f,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${x==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[x!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${x==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(Hb,{hasExtensions:j,ideName:p||"IDE",activeChatTab:g,extensionTabs:S,onSelectTab:h}),s.jsx(oc,{activeConv:v,onModalButton:_.handleModalButton}),s.jsx(va,{activeConv:v,ideEntry:b,showMetaChips:!1,handleSendChat:_.handleSendChat,isSendingChat:_.isSendingChat,sendFeedbackMessage:_.sendFeedbackMessage,handleFocusAgent:_.handleFocusAgent,isFocusingAgent:_.isFocusingAgent,actionLogs:L,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${x==="split"?"order-1 md:order-2":""}`,children:s.jsx(nc,{addLog:()=>{},connState:v.connectionState||"new",connScreenshot:T,screenshotUsage:D,transportType:v.transport,onAction:K})})]})]})})}function Vb({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=Qf(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 Gb({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(rp,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(so,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,missingWorkspaceResumePath:e.missingWorkspaceResumePath,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),t.conversation&&s.jsx(zb,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),r.open&&r.targetConv&&(et(r.targetConv)||Qe(r.targetConv))&&s.jsx(Vb,{activeConv:r.targetConv,canSaveAndStop:et(r.targetConv)&&!Qe(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(Hc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&s.jsx(Fb,{onClose:i.onClose})]})}function qb({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(cr,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[r?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(c=>{const l=Ct(c,{fallbackId:c.id}),d=n[c.id],m=c.version||c.daemonVersion||"unknown",u=c.versionUpdateRequired===!0;return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:l}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),u&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:u?"Update now":"Upgrade"})]},c.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:s.jsx(yt,{size:16})})]})}function Yb(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Xb(e){const t=e.machine;return typeof(t==null?void 0:t.cpus)!="number"||typeof(t==null?void 0:t.totalMem)!="number"||typeof(t==null?void 0:t.arch)!="string"||typeof(t==null?void 0:t.release)!="string"}function Jb(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>Xb(t)).map(t=>t.id)}}function Qb(){var jo,ko,So,No;const{sendCommand:e}=xt(),t=ur(),r=tl(),n=La(),a=Ds(),[i,c]=jd(),l=i.get("activeTab"),d=((jo=n.state)==null?void 0:jo.openRemoteForTabKey)||null,m=((ko=n.state)==null?void 0:ko.openMachineId)||null,u=((So=n.state)==null?void 0:So.mobileSection)||null,f=_c(),x=f.ides||[],N=f.initialLoaded??!0,{updateRouteChats:g,setToasts:h}=f,[k,b]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),p=f.toasts||[],y=f.wsStatus||"connected",S=f.isConnected??!0,j=f.connectionStates||{},A=f.showReconnected||!1,{layoutProfile:M,groupAssignments:w,updateGroupAssignments:v,focusedGroup:B,updateFocusedGroup:_,focusGroup:T,groupActiveTabIds:D,updateGroupActiveTabIds:K,setGroupActiveTab:L,groupTabOrders:C,updateGroupTabOrders:I,setGroupTabOrder:W,groupSizes:P,updateGroupSizes:$,isMobile:H,hasHydratedStoredLayout:Q,hydrateStoredLayout:xe,focusConversationTab:ie}=Kh(),[se,be]=o.useState(()=>io());o.useEffect(()=>th(be),[]);const we=o.useMemo(()=>Yb({isMobile:H,mobileViewMode:se}),[H,se]),[ge,J]=o.useState([]),[ce,ye]=o.useState({}),[ae,de]=o.useState({});lr("Dashboard",{ideCount:x.length,toastCount:p.length,focusedGroup:B,groupCount:Object.keys(w).length,actionLogCount:ge.length});const je=o.useMemo(()=>x.filter(qe=>qe.type==="adhdev-daemon").sort(Fa),[x]),fe=je[0],pe=!!fe;o.useEffect(()=>{const{metadataDaemonIds:qe,runtimeDaemonIds:It}=Jb(je);for(const Bs of qe)t(Bs,{minFreshMs:3e4}).catch(()=>{});for(const Bs of It)r(Bs,{minFreshMs:3e4}).catch(()=>{})},[t,r,je]);const te=(fe==null?void 0:fe.terminalBackend)||null,me=fe?Ct(fe,{fallbackId:fe.id}):null,oe=(fe==null?void 0:fe.id)||null,Y=o.useMemo(()=>mh(x,ce),[x,ce]),{hiddenTabs:V,hideTarget:le,toggleTarget:ke,showTarget:ee,showAllTabs:Pe}=uh(),{conversations:$e,visibleConversations:Oe,visibleTabKeys:He,resolveConversationBySessionId:O,resolveConversationByTarget:Ce}=Sh({ides:Y,connectionStates:j,clearedTabs:ae,hiddenTabs:V}),Te=o.useMemo(()=>new Map($e.map(qe=>[qe.tabKey,qe])),[$e]);Af(Oe,we),o.useEffect(()=>{Object.keys(ce).length!==0&&ye(qe=>fh(qe,x))},[x,ce]);const Re=o.useMemo(()=>Hu(x),[x]),{notifications:Be,unreadCount:Fe}=ex({conversations:$e,liveSessionInboxState:Re}),{handleMarkDashboardNotificationRead:Ye,handleMarkDashboardNotificationUnread:tt,handleDeleteDashboardNotification:ut}=tx({notifications:Be,sendDaemonCommand:e}),{containerRef:ft,normalizedGroupAssignments:pt,numGroups:Ne,isSplitMode:Ue,groupedConvs:Xe,moveTabToGroup:Ve,closeGroup:st,handleResizeStart:F,splitTabRelative:U}=Vh({groupAssignments:w,updateGroupAssignments:v,updateFocusedGroup:_,updateGroupActiveTabIds:K,updateGroupTabOrders:I,groupSizes:P,updateGroupSizes:$,isMobile:H,visibleConversations:Oe,visibleTabKeys:He}),{activeConv:q,openDesktopConversation:re,requestScrollToBottom:E,scrollToBottomRequest:X,setDesktopActiveTab:Z}=px({isMobile:H,conversations:$e,visibleConversations:Oe,groupActiveTabIds:D,focusedGroup:B,groupedConvs:Xe,setSearchParams:c});bx({activeConv:q,isMobile:H,liveSessionInboxState:Re,sendDaemonCommand:e});const{requestedDesktopTabKey:ne,requestedMobileTabKey:ve,consumeRequestedActiveTab:Ae}=Nh({isMobile:H,urlActiveTab:l,resolveConversationBySessionId:O,setSearchParams:c}),{remoteDialogConv:Le,remoteDialogIdeEntry:Se,remoteDialogActiveConv:_e,setRemoteDialogActiveConv:Ee,openRemoteDialog:Ie,closeRemoteDialog:Ge,cliStopDialogOpen:Ze,cliStopTargetConv:it,requestCliStop:lt,cancelCliStop:ht,confirmCliStop:bt}=vx({isMobile:H,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:ne,conversations:$e,ides:x,resolveConversationByTarget:Ce,activeConv:q,sendDaemonCommand:e}),{historyModalOpen:ze,openHistoryModal:he,closeHistoryModal:z,historyTargetConv:R,isSavedSessionHistoryTarget:G,isHistoryCreatingChat:ue,isHistoryRefreshingHistory:De,handleHistorySwitchSession:Me,handleHistoryNewChat:Ke,handleHistoryRefresh:at,savedHistorySessions:St,savedHistoryFilters:mt,setSavedHistoryFilters:Vt,missingWorkspaceResumePath:pr,isSavedHistoryLoading:hr,resumingSavedHistorySessionId:xr,handleRefreshSavedHistory:br,handleResumeSavedHistorySession:gr}=gx({activeConv:q,remoteDialogConv:Le,remoteDialogActiveConv:_e,ides:x,sendDaemonCommand:e,updateRouteChats:g,setToasts:h,setClearedTabs:de,setSearchParams:c}),Gl=o.useMemo(()=>Oe,[Oe]),yr=H&&se==="chat",ql=o.useMemo(()=>$e.filter(qe=>co(V,qe)),[$e,V]),yo=o.useCallback(qe=>{const It=new URLSearchParams(i);It.set("activeTab",qe),c(It,{replace:!0})},[i,c]),{trackPendingLaunch:Yl}=dx({ides:x,conversations:$e,onOpenSession:yo}),{handleBrowseMachineDirectory:Xl,handleSaveMachineWorkspace:Jl,handleLaunchMachineIde:Ql,handleLaunchMachineProvider:Zl,handleListMachineMeshes:ed,handleLaunchMeshCoordinator:td,handleListMachineSavedSessions:sd,setActiveCliViewMode:rd}=ux({sendDaemonCommand:e,trackPendingLaunch:Yl,onOpenSession:yo,activeConv:q,ides:x,setCliViewModeOverrides:ye});ph({visibleConversations:Oe,clearedTabs:ae,setClearedTabs:de,setActionLogs:J}),Ch({ides:x,sendDaemonCommand:e,setToasts:h,resolveConversationByTarget:Ce});const{isRefreshingHistory:nd,handleRefreshHistory:ad}=pl({sendDaemonCommand:e,activeConv:q,chats:(No=x.find(qe=>qe.id===(q==null?void 0:q.routeId)))==null?void 0:No.chats,updateRouteChats:g,setToasts:h,setClearedTabs:de});Oh({urlActiveTab:H&&!yr?l:null,conversations:$e,resolveConversationBySessionId:O,normalizedGroupAssignments:pt,hasHydratedStoredLayout:H&&!yr?Q:!0,hydrateStoredLayout:H&&!yr?xe:()=>{},focusConversationTab:ie,setSearchParams:c,historyModalOpen:ze,activeConv:q,isRefreshingHistory:nd,ides:x,handleRefreshHistory:ad});const od=o.useMemo(()=>!q||!et(q)||Qe(q)?null:$s(q),[q]),{versionMismatchDaemons:id,hasRequiredVersionDaemons:vo,appVersion:cd,versionBannerDismissed:ld,setVersionBannerDismissed:dd,upgradingDaemons:ud,handleBannerUpgrade:md}=Gh({ides:x,sendDaemonCommand:e}),wo=o.useCallback(qe=>{ee(qe),re(qe)},[re,ee]),fd=o.useCallback(qe=>{le(qe)},[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(np,{terminalBackend:te,isStandalone:pe,machineLabel:me,machineKey:oe}),(!ld||vo)&&s.jsx(qb,{daemons:id,targetVersion:cd,required:vo,upgradingDaemons:ud,onUpgrade:md,onDismiss:()=>dd(!0)}),s.jsx(Ob,{showMobileChatMode:yr,isMobile:H,activeConv:q,wsStatus:y,isConnected:S,onOpenHistory:qe=>{qe&&Ee(qe),he()},onOpenRemote:Ie,onStopCli:lt,activeCliViewMode:od,onSetActiveCliViewMode:rd,mobileChatConversations:Gl,ides:x,actionLogs:ge,sendDaemonCommand:e,setActionLogs:J,setCliViewModeOverrides:ye,isStandalone:pe,initialDataLoaded:N,userName:f.userName,requestedMobileTabKey:ve,onRequestedMobileTabConsumed:Ae,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:u,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:ft,isSplitMode:Ue,numGroups:Ne,groupSizes:P,groupedConvs:Xe,clearedTabs:ae,focusedGroup:B,focusGroup:T,moveTabToGroup:Ve,splitTabRelative:U,closeGroup:st,handleResizeStart:F,groupActiveTabIds:D,setGroupActiveTab:L,groupTabOrders:C,setGroupTabOrder:W,toggleHiddenTab:qe=>ke(Te.get(qe)||{tabKey:qe}),visibleConversations:Oe,hiddenConversations:ql,requestedDesktopTabKey:ne,onRequestedDesktopTabConsumed:Ae,onDesktopActiveTabChange:Z,onRequestScrollToBottom:E,onHideConversation:fd,onShowHiddenConversation:wo,onShowAllHiddenConversations:Pe,scrollToBottomRequest:X,machineEntries:je,layoutProfile:M,onBrowseMachineDirectory:Xl,onSaveMachineWorkspace:Jl,onLaunchMachineIde:Ql,onLaunchMachineProvider:Zl,onListMachineMeshes:ed,onLaunchMeshCoordinator:td,onListMachineSavedSessions:sd,notifications:Be,notificationUnreadCount:Fe,liveSessionInboxState:Re,onMarkNotificationRead:Ye,onMarkNotificationUnread:tt,onDeleteNotification:ut}),s.jsx("style",{children:`
|
|
68
|
-
body { overflow: hidden; overscroll-behavior: none; }
|
|
69
|
-
`}),s.jsx(Gb,{historyModal:{open:ze,targetConv:R,ides:x,isCreatingChat:ue,isRefreshingHistory:G?!1:De,savedSessions:St,savedHistoryFilters:mt,missingWorkspaceResumePath:pr||null,onSavedHistoryFiltersChange:Vt,isSavedSessionsLoading:hr,isResumingSavedSessionId:xr,onClose:z,onNewChat:Ke,onSwitchSession:Me,onRefreshHistory:G?br:at,onResumeSavedSession:gr},remoteDialog:{conversation:Le,ideEntry:Se,ides:x,connectionStates:j,actionLogs:ge,sendDaemonCommand:e,setActionLogs:J,isStandalone:pe,userName:f.userName,onOpenHistory:qe=>{qe&&Ee(qe),he()},onConversationChange:Ee,onClose:Ge},cliStopDialog:{open:Ze,targetConv:it,onCancel:ht,onStopNow:async()=>{await bt("hard")},onSaveAndStop:async()=>{await bt("save")}},connectionBanner:{wsStatus:y,showReconnected:A,loginUrl:f.connectionLoginUrl,onReconnect:f.retryServerConnection},toastOverlay:{toasts:p,onDismiss:qe=>h(It=>It.filter(Bs=>Bs.id!==qe)),onClick:qe=>{if(qe.targetKey){const It=Ce(qe.targetKey);It&&(ie(It.tabKey,pt),wo(It),E(It.tabKey,"toast-open"))}}},onboarding:{open:k,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}}})]})}function Zb({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,d]=o.useState(null),[m,u]=o.useState(null),[f,x]=o.useState(!1),[N,g]=o.useState(null),[h,k]=o.useState(!1),[b,p]=o.useState(""),y=o.useRef(null),S=o.useCallback(P=>{y.current=P},[]),j=o.useCallback((P,$,H=!1)=>{c(Q=>[...Q.slice(-100),{timestamp:Date.now(),level:P,message:$}]),setTimeout(()=>{var Q;return(Q=a.current)==null?void 0:Q.scrollIntoView({behavior:"smooth"})},100),H&&nt.showToast($,P==="error"||P==="warn"?"warning":"success")},[a]),A=o.useCallback(P=>{const $=P instanceof Error?P.message:String(P||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),M=o.useCallback(async(P,$)=>{var H;if(!e||l)return!1;d(P),j("info",`Launching ${ot(P)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const Q={ideType:P,enableCdp:!0};(H=$==null?void 0:$.workspace)!=null&&H.trim()?Q.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(Q.useDefaultWorkspace=!0);const xe=await r(e,"launch_ide",Q);return j(xe!=null&&xe.success?"info":"error",xe!=null&&xe.success?`${ot(P)} launched`:`Failed: ${xe==null?void 0:xe.error}`,!0),!!(xe!=null&&xe.success)}catch(Q){return j("error",`Launch error: ${Q.message}`,!0),!1}finally{d(null)}},[e,l,j,r]),w=o.useCallback(async P=>{if(!e)return{success:!1};const{cliType:$,dir:H,workspaceId:Q,useDefaultWorkspace:xe,useHome:ie,argsStr:se,model:be,resumeSessionId:we}=P;if(!$)return j("warn","Select a CLI or ACP provider first",!0),{success:!1};const ge=se?se.split(/\s+/).filter(Boolean):void 0,J=(H==null?void 0:H.trim())||(Q?"(saved id)":xe?"(default workspace)":ie?"(home)":"");j("info",`Launching ${$}${J?` in ${J}`:""}${be?` (model: ${be})`:""}...`),u($);try{const ce={cliType:$,cliArgs:ge,initialModel:be||void 0};H!=null&&H.trim()?ce.dir=H.trim():Q?ce.workspaceId=Q:xe?ce.useDefaultWorkspace=!0:ie&&(ce.useHome=!0),we&&(ce.resumeSessionId=we);const ye=await r(e,"launch_cli",ce),ae=(ye==null?void 0:ye.result)||ye;return ye!=null&&ye.success?(j("info",`${$} launched`,!0),(ae==null?void 0:ae.launchSource)==="home"?j("info","📂 Running in home directory (explicit choice)"):(ae==null?void 0:ae.launchSource)==="defaultWorkspace"&&j("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ae==null?void 0:ae.sessionId}):(j("error",`Failed: ${(ye==null?void 0:ye.error)||(ae==null?void 0:ae.error)}`,!0),(ye==null?void 0:ye.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&g({cliType:$,argsStr:se,model:be}),{success:!1,sessionId:ae==null?void 0:ae.sessionId})}catch(ce){return A(ce)?(j("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(j("error",`Launch error: ${ce.message}`,!0),{success:!1})}finally{u(null)}},[e,j,A,r]),v=o.useCallback(async(P,$,H,Q)=>e?P?$.trim()?w({cliType:P,dir:$,argsStr:H,model:Q}):(g({cliType:P,argsStr:H,model:Q}),{success:!1}):(j("warn","Select a provider",!0),{success:!1}):{success:!1},[e,j,w]),B=o.useCallback(async(P,$,H)=>{if(e&&window.confirm(`Stop ${P}?
|
|
70
|
-
This will terminate the process.`))try{const Q=await r(e,"stop_cli",{cliType:P,dir:$,targetSessionId:H});Q!=null&&Q.success?j("info",`${P} stopped`,!0):j("error",`Stop failed: ${(Q==null?void 0:Q.error)||"Unknown error"}`,!0)}catch(Q){j("error",`Stop failed: ${Q.message}`,!0)}},[e,j,r]),_=o.useCallback(async P=>{try{await r(P.daemonId,"restart_ide",{ideType:P.type}),j("info",`${ot(P.type)} restart initiated`,!0)}catch($){j("error",`Restart failed: ${$.message}`,!0)}},[j,r]),T=o.useCallback(async P=>{if(window.confirm(`Stop ${ot(P.type)}?
|
|
71
|
-
This will disconnect CDP and optionally kill the process.`))try{const $=await r(P.daemonId,"stop_ide",{ideType:P.type,killProcess:!0});$!=null&&$.success?j("info",`${ot(P.type)} stopped`,!0):j("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){j("error",`Stop failed: ${$.message}`,!0)}},[j,r]),D=o.useCallback(async()=>{if(e)try{const P=await r(e,"detect_ides",{});j("info",`Found ${((P==null?void 0:P.result)||[]).length} IDE(s)`,!0)}catch(P){j("error",`Detection failed: ${P.message}`,!0)}},[e,j,r]),K=o.useCallback(async P=>{if(!e||!P.trim())return!1;x(!0);try{const $=await r(e,"workspace_add",{path:P.trim()});return $!=null&&$.success?(j("info",`Workspace added: ${P.trim()}`),!0):(j("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return j("error",$.message),!1}finally{x(!1)}},[e,j,r]),L=o.useCallback(async P=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){x(!0);try{const $=await r(e,"workspace_remove",{id:P});$!=null&&$.success?j("info","Workspace removed",!0):j("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){j("error",$.message,!0)}finally{x(!1)}}},[e,j,r]),C=o.useCallback(async P=>{var $;if(e){x(!0);try{const H=await r(e,"workspace_set_default",P===null?{clear:!0}:{id:P});if(H!=null&&H.success){j("info",P?"Default workspace updated":"Default workspace cleared",!0);const Q=typeof H.defaultWorkspacePath=="string"?H.defaultWorkspacePath:"";Q&&(($=y.current)==null||$.call(y,Q))}else j("error",(H==null?void 0:H.error)||"workspace_set_default failed",!0)}catch(H){j("error",H.message,!0)}finally{x(!1)}}},[e,j,r]),I=o.useCallback(async P=>{var H;if(!e||!P.trim())return;const $=P.trim();x(!0);try{const Q=await r(e,"workspace_set_default",{path:$});Q!=null&&Q.success?(j("info","Default workspace set from history"),(H=y.current)==null||H.call(y,$)):j("error",(Q==null?void 0:Q.error)||"Could not set default (path missing on disk?)")}catch(Q){j("error",Q.message)}finally{x(!1)}},[e,j,r]),W=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:b}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:b})}catch(P){j("warn",`Live nickname updated, but account sync failed: ${P.message}`)}j("info",`Nickname set to "${b||"(cleared)"}"`),k(!1)}catch(P){j("error",`Failed: ${P.message}`)}},[e,b,t,j,n,r]);return{logs:i,launchingIde:l,launchingAgentType:m,workspaceBusy:f,launchPick:N,setLaunchPick:g,editingNickname:h,setEditingNickname:k,nicknameInput:b,setNicknameInput:p,addLog:j,handleLaunchIde:M,runLaunchCliCore:w,handleLaunchCli:v,handleStopCli:B,handleRestartIde:_,handleStopIde:T,handleDetectIdes:D,handleWorkspaceAdd:K,handleWorkspaceRemove:L,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:I,handleSaveNickname:W,setOnDefaultWorkspaceChanged:S}}function eg({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var _;const{workspaceBusy:l,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=i,[f,x]=o.useState(!1),[N,g]=o.useState(""),[h,k]=o.useState([]),[b,p]=o.useState(!1),[y,S]=o.useState(""),j=o.useCallback(async T=>{p(!0),S("");try{const D=await bn(c,e,T);g(D.path),k(D.directories)}catch(D){S(D instanceof Error?D.message:"Could not load folder")}finally{p(!1)}},[e,c]),A=o.useCallback(()=>{x(!0);const T=[...r.map(K=>K.workspace),...n.map(K=>K.workspace),...a.map(K=>K.workspace)],D=xn(t.platform,hn(T,t.defaultWorkspacePath,(t.workspaces||[]).map(K=>K.path)));j(D)},[a,n,r,j,t.defaultWorkspacePath,t.platform,t.workspaces]),M=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,w=t.availableMem??t.freeMem??t.totalMem,v=M&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-w)/t.totalMem*100))):0,B=((_=t.loadavg)==null?void 0:_[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(kr,{icon:s.jsx(Ji,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?Yu(t.uptime):"Waiting…"}),s.jsx(kr,{icon:s.jsx(Tt,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(kr,{icon:s.jsx($a,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(kr,{icon:s.jsx(nu,{size:16}),label:"ACPs",value:`${a.length}`})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),s.jsxs("div",{className:"flex gap-6",children:[s.jsx(Po,{value:M?Math.min(Math.round(B/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:M?`${B.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Po,{value:v,max:100,label:"Memory",color:"#3b82f6",detail:M?`${Cn(t.totalMem-w)} / ${Cn(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Cn(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(us,{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:T=>void u(T.target.value===""?null:T.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(T=>s.jsx("option",{value:T.id,children:T.label||T.path},T.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:A,children:"Select workspace…"}),s.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(t.workspaces||[]).length>0&&s.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(t.workspaces||[]).map(T=>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:[T.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:mn(T.path,T.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:T.path,children:T.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void m(T.id),children:"Remove"})]},T.id))})]}),f&&s.jsx(gn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:N,directories:h,busy:b,error:y,confirmLabel:"Add workspace",onClose:()=>x(!1),onNavigate:T=>{j(T)},onConfirm:T=>{(async()=>{if(!T)return;await d(T)&&x(!1)})()}})]})}function tg(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 sg(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(d=>d.type===a);n.push({type:a,displayName:(l==null?void 0:l.displayName)||a,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[a]||{}})}return n}function Qn(e){if(!e||typeof e!="object")return!1;const t=e;return(t.sourceMode==="normal"||t.sourceMode==="no-upstream")&&typeof t.disableUpstream=="boolean"&&(t.explicitProviderDir===null||typeof t.explicitProviderDir=="string")&&typeof t.userDir=="string"&&typeof t.upstreamDir=="string"&&Array.isArray(t.providerRoots)}function Si(e){if(!e||typeof e!="object")return null;if(Qn(e))return e;const t=e,r=t.result;return Qn(r)?r:Qn(t.sourceConfig)?t.sourceConfig:null}function rg(e){const t=e.trim();return t||null}const Ni=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],ng=[{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 ag({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[d,m]=o.useState([]),[u,f]=o.useState(""),[x,N]=o.useState([]),[g,h]=o.useState(""),k=o.useRef(null),b=o.useRef(null),p=w=>{m(v=>v.includes(w)?v.filter(B=>B!==w):[...v,w])},y=()=>m([...Ni]),S=()=>m([]);o.useEffect(()=>{var w;(w=k.current)==null||w.scrollIntoView({behavior:"smooth"})},[x]),o.useEffect(()=>()=>{b.current&&clearInterval(b.current)},[]);const j=o.useCallback(()=>{b.current&&clearInterval(b.current),b.current=setInterval(async()=>{try{const w=await r(e,"provider_auto_fix_status",{providerType:t.type});(w==null?void 0:w.running)===!1&&a==="running"&&(i("done"),N(v=>[...v,`
|
|
72
|
-
✅ Auto-fix completed!`]),b.current&&clearInterval(b.current))}catch{}},3e3)},[e,t.type,r,a]),A=async()=>{if(d.length!==0){i("running"),N(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${d.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),h("");try{const w=await r(e,"provider_auto_fix",{providerType:t.type,functions:d,agent:c,...u?{comment:u}:{}});w!=null&&w.success&&(w!=null&&w.started||w!=null&&w.running)?(N(v=>[...v,"✅ Agent started. Monitoring progress..."]),j()):(i("error"),h((w==null?void 0:w.error)||"Failed to start auto-fix"))}catch(w){i("error"),h((w==null?void 0:w.message)||"Connection failed")}}},M=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),N(w=>[...w,`
|
|
73
|
-
⚠️ Auto-fix cancelled.`]),i("done"),b.current&&clearInterval(b.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:w=>w.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:ng.map(w=>s.jsxs("button",{onClick:()=>l(w.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===w.value?w.color+"66":"var(--border-subtle)",background:c===w.value?w.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===w.value?w.color:"var(--text-primary)"},children:w.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:w.desc})]},w.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:y,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:S,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Ni.map(w=>s.jsxs("button",{onClick:()=>p(w),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(w)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(w)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(w)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(w)?"☑ ":"☐ ",w]},w))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",s.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:u,onChange:w=>f(w.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[x.map((w,v)=>s.jsx("div",{className:w.startsWith("✅")?"text-green-400":"",style:w.startsWith("❌")||w.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:w},v)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:k})]}),g&&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:g})]})]}),s.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[s.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&d.length>0&&`${d.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),s.jsxs("div",{className:"flex gap-2",children:[a==="config"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:A,disabled:d.length===0,className:"machine-btn",style:{background:d.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:d.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:d.length>0?"#a78bfa":void 0,opacity:d.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&s.jsx("button",{onClick:M,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"),N([]),h("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function og({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var j;const i=t.filter(A=>A.category==="ide"),[c,l]=o.useState(((j=i[0])==null?void 0:j.type)||""),[d,m]=o.useState(""),[u,f]=o.useState(""),[x,N]=o.useState(!1),[g,h]=o.useState(""),[k,b]=o.useState(!1),p=A=>{const M=A.toLowerCase().replace(/[^a-z0-9-]/g,"");m(M),(!u||u===y(d))&&f(y(M))},y=A=>A.split("-").map(M=>M.charAt(0).toUpperCase()+M.slice(1)).join(" "),S=async()=>{if(!(!d||!u||!c)){N(!0),h("");try{const A=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:c});A!=null&&A.success||A!=null&&A.created?(b(!0),a==null||a(d)):h((A==null?void 0:A.error)||"Failed to create provider")}catch(A){h((A==null?void 0:A.message)||"Connection failed")}N(!1)}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:A=>A.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:k?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:d})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(A=>s.jsxs("button",{onClick:()=>l(A.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===A.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===A.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:A.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===A.type?"#a78bfa":"var(--text-secondary)"},children:A.displayName})]},A.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:d,onChange:A=>p(A.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:u,onChange:A=>f(A.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),g&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:g})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:k?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:S,disabled:!d||!u||x,className:"machine-btn",style:{background:d&&u?"rgba(34,197,94,0.12)":void 0,borderColor:d&&u?"rgba(34,197,94,0.3)":void 0,color:d&&u?"#86efac":void 0,opacity:!d||!u||x?.4:1},children:x?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Ci(e){return e==="cli"||e==="acp"}function ig(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 cg(e){switch(e){case"detected":return"bg-green-500/[0.10] border-green-500/25 text-green-400";case"not_detected":return"bg-red-500/[0.10] border-red-500/25 text-red-400";case"enabled_unchecked":return"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400";case"disabled":default:return"bg-white/[0.04] border-white/[0.10] text-text-muted"}}function Ti(e){if(!e)return"No result yet";const t=e.stage||"check",r=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${t}: ${r} — ${n}`:`${t}: ${r}`}function lg({machineId:e,providers:t,sendDaemonCommand:r}){var K;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,d]=o.useState(null),[m,u]=o.useState("all"),[f,x]=o.useState(null),[N,g]=o.useState(!1),[h,k]=o.useState(null),[b,p]=o.useState("normal"),[y,S]=o.useState(""),[j,A]=o.useState(!1),M=o.useCallback(async()=>{if(e)try{const L=await r(e,"get_provider_source_config",{}),C=Si(L);C&&(k(C),p(C.sourceMode),S(C.explicitProviderDir||""))}catch{}},[e,r]),w=o.useCallback(async()=>{if(e){c(!0);try{const L=await r(e,"get_provider_settings",{}),C=tg(L);if(C){const I=sg(C,t,{filterSchema:W=>W.filter(P=>P.key!=="enabled")});I.sort((W,P)=>W.category.localeCompare(P.category)||W.displayName.localeCompare(P.displayName)),a(I)}}catch{}c(!1)}},[e,t,r]);o.useEffect(()=>{n.length===0&&w(),h||M()},[]);const v=async(L,C,I)=>{d(`${L}.${C}`),a(W=>W.map(P=>P.type===L?{...P,values:{...P.values,[C]:I}}:P));try{const W=await r(e,"set_provider_setting",{providerType:L,key:C,value:I});W!=null&&W.success||w()}catch{w()}d(null)},B=async(L,C)=>{await v(L,"enabled",C),await w()},_=async L=>{d(`${L}.detect`);try{await r(e,"detect_provider",{providerType:L})}finally{await w(),d(null)}},T=async L=>{await v(L,"executablePath",""),await v(L,"executableArgs",""),await w()},D=async()=>{A(!0);try{const L=await r(e,"set_provider_source_config",{providerSourceMode:b,providerDir:rg(y)}),C=Si(L);C?(k(C),p(C.sourceMode),S(C.explicitProviderDir||"")):await M(),await w()}catch{await M()}A(!1)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between items-center mb-4",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(L=>s.jsx("button",{onClick:()=>u(L),className:`machine-btn text-[10px] px-2 py-0.5 ${m===L?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:L.toUpperCase()},L))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>g(!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:w,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. Running CLI sessions refresh provider scripts/config; process binary changes still apply on next launch."})]}),s.jsx("button",{onClick:M,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:b,onChange:L=>p(L.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:y,onChange:L=>S(L.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void D(),disabled:j,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:j?"Applying…":"Apply + Reload"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(h==null?void 0:h.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(h==null?void 0:h.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((K=h==null?void 0:h.providerRoots)==null?void 0:K.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(L=>L.category===m).length>1&&(()=>{const L=n.filter(P=>P.category===m),C=new Map;for(const P of L)for(const $ of P.schema){if($.type!=="boolean")continue;const H=C.get($.key),Q=!!(P.values[$.key]??$.default);H?(H.onCount+=Q?1:0,H.total+=1):C.set($.key,{label:$.label||$.key,onCount:Q?1:0,total:1})}const I=[...C.entries()].filter(([,P])=>P.total===L.length);if(I.length===0)return null;const W=async(P,$)=>{for(const H of L)await v(H.type,P,$)};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 (",L.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:I.map(([P,$])=>{const H=$.onCount===$.total,Q=$.onCount===0;return s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:$.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",$.onCount,"/",$.total,")"]}),s.jsx("button",{onClick:()=>void W(P,!0),disabled:H,className:`machine-btn text-[9px] px-1.5 py-px ${H?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void W(P,!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"})]},P)})})]})})(),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(L=>m==="all"||L.category===m).map(L=>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:L.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:L.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:L.category==="acp"?"rgba(139,92,246,0.08)":L.category==="cli"?"rgba(59,130,246,0.08)":L.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:L.category==="acp"?"#a78bfa":L.category==="cli"?"#60a5fa":L.category==="ide"?"#86efac":"var(--status-warning)"},children:L.category}),Ci(L.category)&&(()=>{const C=t.find(P=>P.type===L.type),I=(C==null?void 0:C.enabled)===!0||L.values.enabled===!0,W=(C==null?void 0:C.machineStatus)||(I?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${cg(W)}`,children:ig(W)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void B(L.type,!I),disabled:l===`${L.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${I?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:I?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void _(L.type),disabled:!I||l===`${L.type}.detect`,title:I?"Run detection for the configured executable":"Enable this provider before detection",className:`machine-btn text-[9px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${I?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void T(L.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),L.category==="ide"&&s.jsx("button",{onClick:()=>x(t.find(C=>C.type===L.type)||{type:L.type,name:L.displayName,displayName:L.displayName,icon:L.icon,category:L.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(L.category)&&(()=>{const C=t.find(I=>I.type===L.type);return s.jsxs("div",{className:"mb-2.5 grid gap-1 rounded-lg border border-white/[0.06] bg-bg-primary/40 px-3 py-2 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Detection:"})," ",Ti(C==null?void 0:C.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Ti(C==null?void 0:C.lastVerification)]}),s.jsx("div",{className:"text-[9px] text-text-muted",children:"Supported catalog entry only becomes launchable after Enable + Detect succeeds. Custom executable path/args below are machine-local overrides."})]})})(),s.jsx("div",{className:"flex flex-col gap-2",children:L.schema.map(C=>s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[C.label||C.key,l===`${L.type}.${C.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),C.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:C.description})]}),s.jsx("div",{className:"shrink-0",children:C.type==="boolean"?s.jsx("button",{onClick:()=>v(L.type,C.key,!(L.values[C.key]??C.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:L.values[C.key]??C.default?"#8b5cf6":"var(--border-subtle)"},children:s.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:L.values[C.key]??C.default?21:3}})}):C.type==="number"?s.jsx("input",{type:"number",value:Number(L.values[C.key]??C.default??0)||0,min:C.min,max:C.max,onChange:I=>{const W=parseInt(I.target.value)||0;C.min!==void 0&&W<C.min||C.max!==void 0&&W>C.max||v(L.type,C.key,W)},className:"machine-input w-20 text-center text-[11px]"}):C.type==="select"&&C.options?s.jsx("select",{value:String(L.values[C.key]??C.default??""),onChange:I=>v(L.type,C.key,I.target.value),className:"machine-input text-[11px]",children:C.options.map(I=>s.jsx("option",{value:I,children:I},I))}):s.jsx("input",{type:"text",value:String(L.values[C.key]??C.default??""),onBlur:I=>v(L.type,C.key,I.target.value),className:"machine-input w-[120px] text-[11px]"})})]},C.key))})]},L.type))}),f&&s.jsx(ag,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>x(null)}),N&&s.jsx(og,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>g(!1),onCreated:()=>{g(!1),w()}})]})}const dg=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function ug({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function mg(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function fg(e){return e.trim().toLowerCase()}function vn(e,t){const r=fg(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function xo(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Ps(e,t=220){const r=xo(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function pg(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 hg(e,t){return e.filter(r=>vn([r.level,r.message],t))}function Mi(e){return`${e.timestamp}:${e.level}:${e.message}`}function xg(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const c of e.entries)n.set(Mi(c),c);for(const c of t.entries)n.set(Mi(c),c);const a=Array.from(n.values()).sort((c,l)=>c.timestamp-l.timestamp).slice(-r),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 bg(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 gg(e,t){return e.split(`
|
|
74
|
-
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>vn([r],t))}function yg(e,t){return e.filter(r=>vn([r.level,r.category,r.stage,r.interactionId,xo(r.payload)],t))}function vg(e,t){return e.filter(r=>vn([r.kind,r.topic,r.interactionId,xo(r.payload)],t))}function Ai(e){return e==="warn"||e==="error"}function wg({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){return{all:e.length+t.length+r.length+n.length,info:e.filter(a=>a.level!=="debug").length+r.filter(a=>a.level!=="debug").length+n.length,issues:e.filter(a=>Ai(a.level)).length+r.filter(a=>Ai(a.level)).length}}function jg({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(`
|
|
75
|
-
`)):t.length>0&&a.push(["[daemon logs]",...t].join(`
|
|
76
|
-
`)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${Ps(i.payload,500)}`.trim())].join(`
|
|
77
|
-
`)),n.length>0&&a.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${Ps(i.payload,500)}`.trim())].join(`
|
|
78
|
-
`)),a.join(`
|
|
79
|
-
|
|
80
|
-
`)}function kg({machineId:e,sendDaemonCommand:t}){const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[d,m]=o.useState([]),[u,f]=o.useState([]),[x,N]=o.useState(null),[g,h]=o.useState(!0),[k,b]=o.useState("info"),[p,y]=o.useState("all"),[S,j]=o.useState(!0),[A,M]=o.useState(!0),[w,v]=o.useState(""),[B,_]=o.useState(""),[T,D]=o.useState(0),K=o.useRef(0),L=o.useRef(0),C=o.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),I=o.useRef([]),W=o.useCallback(()=>{const se={entries:[],kind:"empty",rawText:"",lastTs:0};C.current=se,K.current=0,n([]),l(""),i("empty"),j(!0)},[]),P=o.useCallback(()=>{I.current=[],L.current=0,m([]),M(!0)},[]),$=o.useCallback(se=>{se!==k&&(W(),b(se))},[k,W]),H=o.useCallback(se=>{y(be=>be===se?be:se)},[]),Q=o.useCallback(()=>{W(),P(),f([]),N(null),v(""),_(""),Cs.clear()},[W,P]),xe=o.useCallback(()=>{D(se=>se+1)},[]),ie=o.useCallback(async()=>{if(!e)return;const se=K.current,be=L.current,[we,ge]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:k,since:se}),t(e,"get_debug_trace",ug({count:120,since:be,category:p}))]);if(we.status==="fulfilled"){const J=we.value,ce=(J==null?void 0:J.result)||J,ye=pg(ce),ae=xg(C.current,ye,300);C.current=ae,K.current=ae.lastTs,j(!1),v((J==null?void 0:J.success)===!1?String((J==null?void 0:J.error)||"Could not load daemon logs"):""),i(ae.kind),l(ae.rawText),n(ae.entries)}else j(!1),v(we.reason instanceof Error?we.reason.message:"Could not load daemon logs");if(ge.status==="fulfilled"){const J=ge.value,ce=(J==null?void 0:J.result)||J;if((J==null?void 0:J.success)===!1)_(String((J==null?void 0:J.error)||"Could not load daemon trace"));else if(Array.isArray(ce==null?void 0:ce.trace)){const ye=ce.trace,ae=bg(I.current,ye,120),de=ye.reduce((je,fe)=>Math.max(je,Number(fe.ts||0)),be);I.current=ae,de>be&&(L.current=de),_(""),m(ae)}else _("");M(!1)}else M(!1),_(ge.reason instanceof Error?ge.reason.message:"Could not load daemon trace");f(Cs.list({limit:120})),N(Date.now())},[k,e,t,p]);return o.useEffect(()=>{P()},[P,p]),o.useEffect(()=>{if(!e||(ie(),!g))return;const se=setInterval(()=>{ie()},3e3);return()=>clearInterval(se)},[g,ie,e,T]),{daemonLogs:r,daemonLogKind:a,daemonRawText:c,debugTrace:d,webEvents:u,lastUpdatedAt:x,autoRefresh:g,logLevel:k,traceCategory:p,daemonLoading:S,traceLoading:A,daemonFetchError:w,traceFetchError:B,setAutoRefresh:h,setLogLevel:$,setTraceCategory:H,refresh:xe,clear:Q}}function Sg({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:i,daemonRawLineCount:c,traceCount:l,webEventCount:d}){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:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function Ii(e){return e==="warn"||e==="error"}function Ng(e){const t=e.toLowerCase();return/\[(err|error)\]/i.test(e)||t.includes(" error ")||t.includes(" failed")?"error":/\[(wrn|warn|warning)\]/i.test(e)||t.includes(" warning ")||t.includes(" timeout")?"warn":/\[(dbg|debug)\]/i.test(e)?"debug":"info"}function Cg(e,t){const r=e.match(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\b/);if(r){const n=Date.parse(r[0]);if(Number.isFinite(n))return n}return Number.MAX_SAFE_INTEGER-1e5+t}function Ri(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function Tg(e){const t=Ps(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function Mg(e){const t=Ps(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function Ag({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:Mg(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:Tg(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:Cg(i,c),severity:Ng(i),message:i,raw:i})}),a.sort((i,c)=>i.ts!==c.ts?i.ts-c.ts:Ri(i.source)-Ri(c.source))}function Ig(e){return`${e.source}:${e.severity}:${e.message}`}function Rg(e){const t=e.filter(n=>Ii(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!Ii(n.severity))continue;const a=Ig(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 Lg(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Li(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${Lg(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function _g({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
|
|
81
|
-
`)),a.push(["[source status]",...r.map(c=>`${c.label}: ${c.status} - ${c.detail}`)].join(`
|
|
82
|
-
`)),t.latestIssue&&a.push(["[latest issue]",Li(t.latestIssue)].join(`
|
|
83
|
-
`)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(c=>`${c.count}x ${c.severity.toUpperCase()} ${c.source} ${c.message}`)].join(`
|
|
84
|
-
`));const i=e.slice(-n);return a.push(["[timeline]",...i.length>0?i.map(Li):["No diagnostic events captured."]].join(`
|
|
85
|
-
`)),a.join(`
|
|
86
|
-
|
|
87
|
-
`)}function Pg(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Dg(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Eg({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:i,quickFilter:c,searchQuery:l,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f}){const x=mg(n,i),N=hg(e,l),g=gg(t,l),h=yg(x,l),k=vg(a,l),b=Pg(N,c),p=c==="all"?g:[],y=Dg(h,c),S=c==="issues"?[]:k,j=wg({daemonLogs:N,daemonRawLines:g,trace:h,webEvents:k}),A=Ag({daemonLogs:b,daemonRawLines:p,trace:y,webEvents:S}),M=Rg(A),w=Sg({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f,daemonLogKind:r,daemonLogsCount:N.length,daemonRawLineCount:g.length,traceCount:h.length,webEventCount:k.length});return{filteredDaemonLogs:N,filteredDaemonRawLines:g,filteredTraceEntries:h,filteredWebEvents:k,visibleDaemonLogs:b,visibleDaemonRawLines:p,visibleTraceEntries:y,visibleWebEvents:S,quickFilterCounts:j,diagnosticEvents:A,diagnosticsSummary:M,sourceStates:w}}function $g(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Hl(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Ma(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 Zn(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function bo(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function Bg({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ma(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Hl(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:bo(e.source)}),e.category&&e.stage&&s.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&s.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&s.jsxs("span",{children:["ix=",e.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function Kg({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:c,onCopyVisible:l,onToggleAutoRefresh:d,onRefresh:m,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(f=>s.jsx("button",{type:"button",onClick:()=>a(f.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===f.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:f.label},f.id))}),s.jsx("input",{value:r,onChange:f=>i(f.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:l,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function Wg({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:dg.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 Og({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:i,daemonFetchError:c,traceFetchError:l}){var u,f;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((f=e.latestIssue)==null?void 0:f.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 ${Zn(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 ${Zn(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[bo(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:Hl(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 ${Zn(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: ",$g(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(x=>s.jsxs("div",{children:[x.label,": ",x.status]},x.id))})]})]})}function Fg({patterns:e}){return e.length===0?null:s.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[s.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",bo(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function Hg({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:i,visibleTraceEntries:c,visibleWebEvents:l,quickFilter:d,searchQuery:m}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,timeline:!u.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(u=>s.jsx(Bg,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,daemon:!u.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${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:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&i.map((u,f)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${f}`)),e.daemonLogKind!=="text"&&a.map((u,f)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Ma(u.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:u.message})]},`log-${f}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,trace:!u.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&c.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children: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(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ma(u.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.level.toUpperCase()}),s.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Ps(u.payload,360)||"No payload"})]},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,web:!u.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[l.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),l.map(u=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.kind}),u.topic&&s.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Ps(u.payload,360)||"No payload"})]},u.id))]})]})]})}function Ug({machineId:e,sendDaemonCommand:t}){const r=kg({machineId:e,sendDaemonCommand:t}),[n,a]=o.useState("info"),[i,c]=o.useState(""),[l,d]=o.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=o.useRef(null),u=o.useRef(!1),f=o.useMemo(()=>Eg({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&&f.diagnosticEvents.length>0){const g=u.current?"smooth":"instant";setTimeout(()=>{var h;(h=m.current)==null||h.scrollIntoView({behavior:g}),u.current=!0},50)}},[f.diagnosticEvents.length,r.autoRefresh]);const x=o.useCallback(async()=>{var h;const g=jg({daemonLogs:f.visibleDaemonLogs,daemonRawLines:f.visibleDaemonRawLines,trace:f.visibleTraceEntries,webEvents:f.visibleWebEvents});if(!g.trim()){nt.showToast("No visible logs to copy.","info");return}try{await((h=navigator.clipboard)==null?void 0:h.writeText(g)),nt.showToast("Copied visible logs to clipboard.","success")}catch(k){nt.showToast(k instanceof Error?k.message:"Could not copy visible logs","warning")}},[f.visibleDaemonLogs,f.visibleDaemonRawLines,f.visibleTraceEntries,f.visibleWebEvents]),N=o.useCallback(async()=>{var h;const g=_g({events:f.diagnosticEvents,summary:f.diagnosticsSummary,sources:f.sourceStates});try{await((h=navigator.clipboard)==null?void 0:h.writeText(g)),nt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(k){nt.showToast(k instanceof Error?k.message:"Could not copy diagnostic bundle","warning")}},[f.diagnosticEvents,f.diagnosticsSummary,f.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(Kg,{quickFilter:n,quickFilterCounts:f.quickFilterCounts,searchQuery:i,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{N()},onCopyVisible:()=>{x()},onToggleAutoRefresh:()=>r.setAutoRefresh(g=>!g),onRefresh:r.refresh,onClear:r.clear}),s.jsx(Wg,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(Og,{diagnosticsSummary:f.diagnosticsSummary,diagnosticEventsCount:f.diagnosticEvents.length,sourceStates:f.sourceStates,searchQuery:i,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(Fg,{patterns:f.diagnosticsSummary.repeatedPatterns}),s.jsx(Hg,{streams:r,sectionsOpen:l,setSectionsOpen:d,diagnosticEvents:f.diagnosticEvents,visibleDaemonLogs:f.visibleDaemonLogs,visibleDaemonRawLines:f.visibleDaemonRawLines,visibleTraceEntries:f.visibleTraceEntries,visibleWebEvents:f.visibleWebEvents,quickFilter:n,searchQuery:i}),s.jsx("div",{ref:m})]})}function zg(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 Ul(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 Vg(e){var a;const t=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=Ul((i==null?void 0:i.meta)||void 0),d=((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")&&(d||l)?r.push(i):n.push(i)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function Gg(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function ea(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 ta(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function sa(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function _i(e){if(!e)return"unknown";const t=Date.now()-e,r=Math.max(0,Math.round(t/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function qg(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Yg(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 Xg(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 Jg({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,d]=o.useState(!1),m=ch(e,{enabled:!!e,includeSessions:!0,limit:Ho,intervalMs:lf}),u=m.diagnostics,f=m.loading,x=m.applyDiagnostics,N=o.useMemo(()=>zg({diagnostics:u,loading:f,refreshing:l,error:n}),[u,f,l,n]),g=o.useMemo(()=>new Map(t.map(_=>[_.sessionId||_.id,_])),[t]),h=o.useCallback(async()=>{if(e){d(!0);try{const _=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Ho}),T=ta(_);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");x(T.diagnostics||T.result||null),a("")}catch(_){const T=_ instanceof Error?_.message:"Could not load hosted runtime diagnostics";a(T)}finally{d(!1)}}},[x,e,r]);o.useEffect(()=>{!e||u||f||l||h()},[u,f,e,h,l]);const k=o.useCallback(async(_,T)=>{const D=`${_}:${T.sessionId}`;if(!(_==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
|
|
88
|
-
This will terminate the hosted runtime.`))){c(D);try{const K=await r(e,_,{sessionId:T.sessionId}),L=ta(K);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Session host action failed");const C=_==="session_host_resume_session"?"resumed":_==="session_host_restart_session"?"restarted":"stopped";nt.showToast(`Session host ${C}: ${T.displayName}`,"success"),await h()}catch(K){const L=K instanceof Error?K.message:"Session host action failed";nt.showToast(L,"warning"),a(L)}finally{c(K=>K===D?null:K)}}},[e,h,r]),b=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
89
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const T=await r(e,"session_host_prune_duplicate_sessions",{}),D=ta(T);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Duplicate prune failed");const K=D.result||{},L=Array.isArray(K.prunedSessionIds)?K.prunedSessionIds.length:0,C=typeof K.duplicateGroupCount=="number"?K.duplicateGroupCount:0;nt.showToast(`Pruned ${L} duplicate runtime(s) across ${C} group(s)`,"success"),await h()}catch(T){const D=T instanceof Error?T.message:"Duplicate prune failed";nt.showToast(D,"warning"),a(D)}finally{c(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,h,r]),p=o.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((_,T)=>(T.lastActivityAt||0)-(_.lastActivityAt||0)),[u==null?void 0:u.sessions]),y=o.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:Vg(p),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,p]),S=y.liveRuntimes,j=y.recoverySnapshots,A=y.inactiveRecords,M=o.useMemo(()=>Xg(S),[S]),w=o.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),v=o.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(_=>_.level==="warn"||_.level==="error")||null,[u==null?void 0:u.recentLogs]),B=(_,T)=>{var H;const D=i===`session_host_resume_session:${_.sessionId}`,K=i===`session_host_restart_session:${_.sessionId}`,L=i===`session_host_stop_session:${_.sessionId}`,C=Ul(_.meta),I=g.get(_.sessionId),W=_.attachedClients.length===1?"1 client":`${_.attachedClients.length} clients`,P=T==="recovery"?"Recover":"Resume",$=Gg(T);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:_.displayName||(I==null?void 0:I.cliName)||_.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Yg(_.lifecycle)}`,children:_.lifecycle}),C&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:_.workspaceLabel||(I==null?void 0:I.runtimeWorkspaceLabel)||_.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:_.runtimeKey}),_.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",_.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((H=_.writeOwner)==null?void 0:H.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:qg(_.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(Gi,{size:11})," ",W]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",_i(_.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",$]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="recovery"&&(_.lifecycle==="interrupted"||_.lifecycle==="failed"||_.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{k("session_host_resume_session",_)},children:D?`${P}ing…`:P}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{k("session_host_restart_session",_)},children:K?"Restarting…":"Restart"}),T==="live"&&(_.lifecycle==="running"||_.lifecycle==="starting"||_.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:()=>{k("session_host_stop_session",_)},children:L?"Stopping…":"Stop"})]})]})},_.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(Ot,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:pp()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[M>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{b()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${M})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${N.toneClass}`,children:N.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:f||l,children:[s.jsx(cr,{size:13}),f||l?"Refreshing…":"Refresh"]})]})]}),n&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(ar,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:j.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:_i(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:sa(u.hostStartedAt)})]})]}),v&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(ar,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:v.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[sa(v.timestamp),v.sessionId?` · ${v.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($a,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ea("live")}),S.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:S.map(_=>B(_,"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(Ot,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ea("recovery")}),j.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:j.map(_=>B(_,"recovery"))})]}),A.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ea("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:A.map(_=>B(_,"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"}),w.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:w.map(_=>{var D;const T=p.find(K=>K.sessionId===_.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(T==null?void 0:T.displayName)||((D=g.get(_.sessionId))==null?void 0:D.cliName)||_.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[_.action,_.lifecycle?` · ${_.lifecycle}`:"",_.detail?` · ${_.detail}`:"",_.error?` · ${_.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${_.success===!1?"text-red-300":"text-text-secondary"}`,children:sa(_.timestamp)})]},`${_.sessionId}:${_.timestamp}:${_.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Qg({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 ra({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 na({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 Zg({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),d=r.slice(0,4),u=er(e,"0.9.74");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(ra,{icon:s.jsx(Ut,{size:13}),children:"Current Chats"}),s.jsx(na,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(f=>{const x=Na(f);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(f),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:ct(f)}),x>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:dn(x)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:fs(f)})]},f.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ra,{icon:s.jsx(Ji,{size:13}),children:"Recent Launches"}),s.jsx(na,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(f=>{const{metaText:x,updatedLabel:N}=jl(f);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(f),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:f.label}),N&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:N})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:x})]},f.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ra,{icon:s.jsx(ar,{size:13}),children:"Daemon Update"}),s.jsx(na,{className:"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u?"Daemon update required":"Version mismatch detected"}),s.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:u?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(cr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function ey(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function ty({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:d=>{const m=d.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(d=>s.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",mn(d.path,d.label)]},d.id)),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),t==="__custom__"&&(a?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:l,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:d=>c(d.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:t==="__custom__"?r?s.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:t===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const sy={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 Dr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function aa({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const f=Ds(),{handleLaunchIde:x,handleStopCli:N,handleRestartIde:g,handleStopIde:h,handleDetectIdes:k,launchingIde:b,launchingAgentType:p,addLog:y}=c,[S,j]=o.useState(null),A=o.useCallback(R=>{R&&f(Xt(R))},[f]),M=sy[e],w=e==="ide",v=e==="acp",B=o.useMemo(()=>n.filter(R=>ps(R,e)),[e,n]),_=o.useMemo(()=>new Map(B.map(R=>[R.type,R.displayName||R.type])),[B]),[T,D]=o.useState(""),[K,L]=o.useState(""),[C,I]=o.useState([]),[W,P]=o.useState(""),[$,H]=o.useState(""),[Q,xe]=o.useState([]),[ie,se]=o.useState(!1),[be,we]=o.useState(!1),[ge,J]=o.useState(""),[ce,ye]=o.useState(!1),[ae,de]=o.useState(()=>gt()),[je,fe]=o.useState(null),[pe,te]=o.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[me,oe]=o.useState(m||""),[Y,V]=o.useState([]),[le,ke]=o.useState(!1),[ee,Pe]=o.useState(""),[$e,Oe]=o.useState([]),[He,O]=o.useState(!1),[Ce,Te]=o.useState(""),Re=o.useRef(null),[Be,Fe]=o.useState(null),Ye=o.useRef("__home__"),[tt,ut]=o.useState("__home__"),[ft,pt]=o.useState(!1),Ne=o.useRef(0),Ue=Y.filter(R=>!a.some(G=>G.type===R&&wt(G.status)!=="stopped")),Xe=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!pe&&te(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(m){te("__custom__"),oe(m);return}d&&(te(d),oe(""))},[d,m]),o.useEffect(()=>{w||T&&(B.some(R=>R.type===T)||(D(""),H("")))},[B,w,T]);const Ve=(()=>{if(pe==="__custom__")return me.trim();if(!pe)return"";const R=(t.workspaces||[]).find(G=>G.id===pe);return(R==null?void 0:R.path)||""})(),st=o.useCallback(R=>{const G=Xe.current[R];G&&(clearTimeout(G),delete Xe.current[R]),V(ue=>ue.includes(R)?ue.filter(De=>De!==R):ue)},[]),F=o.useRef(new Set),U=o.useCallback(async R=>{if(l){O(!0),Te("");try{const G=await bn(l,r,R);Pe(G.path),oe(G.path),Oe(G.directories)}catch(G){Te(G instanceof Error?G.message:"Could not load folder")}finally{O(!1)}}},[r,l]),q=o.useCallback(()=>{if(!l)return;te("__custom__"),ke(!0);const R=a.map(ue=>ue.workspace),G=xn(t.platform,hn(me.trim(),Ve,m,R,t.defaultWorkspacePath,(t.workspaces||[]).map(ue=>ue.path)));U(G)},[me,m,U,t.defaultWorkspacePath,t.platform,t.workspaces,a,Ve,l]),re=o.useCallback(R=>{const G=String(R.workspace||"").trim();if(!G)return;const ue=(t.workspaces||[]).find(De=>Dr(De.path)===Dr(G));if(ue){te(ue.id),oe("");return}te("__custom__"),oe(G)},[t.workspaces]),E=o.useCallback(R=>{const G=String(R.workspace||"").trim();if(!G)return{workspaceId:null,workspacePath:"",useHome:!0};const ue=(t.workspaces||[]).find(De=>Dr(De.path)===Dr(G));return ue?{workspaceId:ue.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:G,useHome:!1}},[t.workspaces]),X=o.useCallback(async R=>{if(!l||!R||e!=="cli"){xe([]),se(!1),we(!1),J("");return}const G=Ne.current+1;Ne.current=G,se(!0),J("");try{const ue=await l(r,"list_saved_sessions",{providerType:R,kind:"cli",limit:30});if(Ne.current!==G)return;const De=(ue==null?void 0:ue.result)??ue;xe(Array.isArray(De==null?void 0:De.sessions)?De.sessions:[])}catch(ue){if(Ne.current!==G)return;xe([]),J(ue instanceof Error?ue.message:"Could not load saved sessions")}finally{Ne.current===G&&(se(!1),we(!0))}},[e,r,l]),Z=o.useMemo(()=>{if(e!=="cli"||!T)return null;const R=_.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:$||void 0,transport:"pty",mode:"chat",agentName:R,agentType:T,status:"idle",title:R,messages:[],ideType:T,workspaceName:Ve,workspacePath:Ve,displayPrimary:R,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,_,Ve,$,T]),ne=o.useCallback(R=>{if(e==="ide"||!R){I([]);return}I(El(r,R))},[e,r]);o.useEffect(()=>{Ne.current+=1,H(""),ne(T),we(!1),xe([]),J(""),se(!1)},[e,ne,X,T]);const ve=o.useMemo(()=>Q.find(R=>R.providerSessionId===$)||null,[Q,$]);o.useEffect(()=>{if(!$)return;const R=Q.find(G=>G.providerSessionId===$);R!=null&&R.canResume||H("")},[Q,$]);const Ae=o.useCallback((R,G)=>{Re.current=G,Ye.current=R.selectedWorkspaceKey||"__home__",ut(R.selectedWorkspaceKey||"__home__"),Fe(R)},[]),Le=o.useCallback(()=>{Re.current&&(pt(!0),Re.current().finally(()=>{Re.current=null,pt(!1),Fe(null)}))},[]),Se=o.useCallback(R=>{if(!R)return;V(ue=>ue.includes(R)?ue:[...ue,R]);const G=Xe.current[R];G&&clearTimeout(G),Xe.current[R]=setTimeout(()=>{V(ue=>ue.includes(R)?ue.filter(De=>De!==R):ue),delete Xe.current[R]},2e4)},[]);o.useEffect(()=>{for(const G of a)wt(G.status)!=="stopped"&&(Y.includes(G.type)&&!F.current.has(G.type)&&(F.current.add(G.type),y("info",`${_.get(G.type)||G.type} launched`,!0)),st(G.type));const R=new Set(a.filter(G=>wt(G.status)!=="stopped").map(G=>G.type));F.current.forEach(G=>{!Y.includes(G)&&!R.has(G)&&F.current.delete(G)})},[y,st,a,Y,_]),o.useEffect(()=>()=>{Object.values(Xe.current).forEach(clearTimeout),Xe.current={}},[]);const[_e,Ee]=o.useState({}),[Ie,Ge]=o.useState(null);o.useEffect(()=>{if(!w||!r||!l)return;(async()=>{try{const G=await l(r,"get_ide_extensions",{}),ue=(G==null?void 0:G.result)||G;ue!=null&&ue.success&&(ue!=null&&ue.ideExtensions)&&Ee(ue.ideExtensions)}catch{}})()},[w,r,l]);const Ze=R=>w?ot(R.type):e==="cli"?R.cliName:R.acpName,it=w?t.detectedIdes||[]:[],lt=o.useCallback(async R=>{const G=(R==null?void 0:R.type)||T,ue=(R==null?void 0:R.workspacePath)??Ve;if(w){await x(G,ue?{workspace:ue}:void 0)&&Se(G);return}const De=await c.runLaunchCliCore({cliType:G,dir:R!=null&&R.workspaceId?void 0:ue||void 0,workspaceId:(R==null?void 0:R.workspaceId)||void 0,useHome:(R==null?void 0:R.useHome)||!(R!=null&&R.workspaceId)&&!ue,argsStr:(R==null?void 0:R.argsStr)??(K||void 0),model:(R==null?void 0:R.model)??(v&&W||void 0),resumeSessionId:(R==null?void 0:R.resumeSessionId)||!v&&e==="cli"&&G===T&&$||void 0});if(De.success||De.pending){const Me=(R==null?void 0:R.argsStr)??K;!w&&(Me!=null&&Me.trim())&&($l(r,G,Me),ne(G)),Se(G),De.success&&De.sessionId&&A(De.sessionId)}},[c,x,v,w,K,W,ne,Se,r,A,Ve,$,T]),ht=Oc(w?"ide":v?"acp":"cli",!w&&!v&&!!$),bt=Fc(w?"ide":v?"acp":"cli",!w&&!v&&!!$),ze=()=>{var Me;const R=w?ot(T):_.get(T)||T,G=!w&&!v&&!!$,{options:ue,selectedKey:De}=ls({machine:t,currentWorkspaceId:pe&&pe!=="__custom__"?pe:null,currentWorkspacePath:Ve});Ae({title:G?eo(R):ns("start-fresh",R),description:G?to():as("start-fresh"),confirmLabel:ht,busyLabel:bt,workspaceOptions:ue,selectedWorkspaceKey:De,details:[{label:"Mode",value:M.label},{label:"Provider",value:R},...!w&&e==="cli"&&$?[{label:"Resume",value:((Me=Q.find(Ke=>Ke.providerSessionId===$))==null?void 0:Me.title)||$}]:[],...!w&&K.trim()?[{label:"Arguments",value:K.trim()}]:[],...v&&W.trim()?[{label:"Model",value:W.trim()}]:[]]},async()=>{const Ke=ue.find(at=>at.key===Ye.current);Ke!=null&&Ke.workspaceId?(te(Ke.workspaceId),oe("")):Ke!=null&&Ke.workspacePath?(te("__custom__"),oe(Ke.workspacePath)):(te(""),oe("")),await lt({workspaceId:(Ke==null?void 0:Ke.workspaceId)??null,workspacePath:(Ke==null?void 0:Ke.workspacePath)??"",useHome:!(Ke!=null&&Ke.workspaceId)&&!(Ke!=null&&Ke.workspacePath)})})},he=R=>{w?h(R):N(R.type,R.workspace,R.id)},z=o.useCallback(async(R,G,ue=!1)=>{if(R.mode===G){ue&&R.sessionId&&A(R.sessionId);return}if(!l||!R.sessionId){ue&&R.sessionId&&A(R.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:R.sessionId,cliType:R.type,mode:G}),ue&&A(R.sessionId)}catch(De){const Me=ol(De);al(De)?console.warn(Me?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",De instanceof Error?De.message:String(De)):console.error("Failed to switch CLI view mode:",De)}},[r,A,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${M.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",M.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:w?it.length>0?it.map(R=>{const G=a.find(at=>(at.type||"").toLowerCase()===(R.type||"").toLowerCase()&&wt(at.status)!=="stopped"),ue=R.running||!!G,De=!!G&&G.cdpConnected,Me=Y.includes(R.type||R.id||""),Ke=T===(R.type||"");return s.jsxs("button",{onClick:()=>{if(De&&G){const at=G.sessionId;at?f(Xt(at),{state:{openRemoteForTabKey:at}}):f("/dashboard",{state:{openRemoteForTabKey:G.id}});return}Me||D(at=>at===(R.type||"")?"":R.type||"")},disabled:!!b||Me,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${De?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ke?"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:b&&b!==R.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(R.type)}),ue&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${De?"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:R.name||ot(R.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${De?"text-green-400":Me?"text-orange-400":Ke?"text-accent-primary":"text-text-muted"}`,children:De?"Open Session":Me?"Starting...":Ke?"Configure":"Select"})]})]},R.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:k,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(eu,{size:14})," Scan System"]})]}):B.length>0?B.map(R=>{const G=T===R.type,ue=Y.includes(R.type),Me=!!a.find(Ke=>Ke.type===R.type&&wt(Ke.status)!=="stopped");return s.jsxs("button",{onClick:()=>D(Ke=>Ke===R.type?"":R.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${G?"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:R.icon}),Me&&s.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:R.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ue?"text-orange-400":G?"text-accent-primary":"text-text-muted"}`,children:ue?"Starting...":G?"Configure":"Select"})]})]},R.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."})]})}),T&&(w?it.find(R=>R.type===T):B.find(R=>R.type===T))&&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:w?ot(T):_.get(T)||T})]}),s.jsx(ty,{machine:t,selectedWorkspace:pe,resolvedWorkspacePath:Ve,customPath:me,canBrowse:!!l,onWorkspaceChange:te,onCustomPathChange:oe,onOpenBrowseDialog:q}),!w&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&s.jsx(Kl,{busy:!!p||!!b||Y.includes(T),savedSessionsLoading:ie,savedSessionsError:ge,savedSessionsLoaded:be,savedSessionsCount:Q.length,selectedSession:ve,onRefresh:()=>void X(T),onOpenHistory:()=>{T&&(ye(!0),Bl({hasLoadedInitialResults:be,isLoading:ie})&&X(T))},onClearSelection:()=>H("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value:W,onChange:R=>P(R.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:K,onChange:R=>L(R.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),C.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:C.map(R=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>L(R),title:R,children:R},R))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:ze,disabled:!!p||!!b||Y.includes(T),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:p===T||b===T?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+Y.filter(R=>!a.some(G=>G.type===R&&wt(G.status)!=="stopped")).length,")"]}),a.length===0&&Ue.length===0?s.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",M.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ue.map(R=>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(R)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:w?ot(R):_.get(R)||R}),s.jsx("div",{className:"text-[11px] text-text-muted",children:p===R?"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:${R}`)),a.map(R=>{const G=w?R:null,ue=!w&&!v?R:null,De=wt(R.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(R.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ze(R),(G==null?void 0:G.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",G.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[s.jsx("span",{className:"truncate",children:R.workspace||"—"}),u&&R.git&&R.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:Me=>{Me.stopPropagation(),u(R.daemonId??r,R.workspace)},children:s.jsx(Rs,{git:R.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Rs,{git:R.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(ue==null?void 0:ue.mode)&&s.jsx("span",{className:ue.mode==="chat"?"text-violet-400":"text-text-secondary",children:ue.mode==="chat"?"Chat view":"Terminal view"})]}),ue&&(ue.runtimeKey||ue.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ue.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 ",ue.runtimeKey]}),s.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Me;(Me=navigator.clipboard)==null||Me.writeText(`adhdev attach ${ue.runtimeKey}`),j(ue.runtimeKey||null),window.setTimeout(()=>{j(Ke=>Ke===ue.runtimeKey?null:Ke)},1200)},children:S===ue.runtimeKey?"Copied":"Copy"})]}),ue.runtimeWriteOwner&&s.jsx("span",{style:{color:ue.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ue.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:ey(ue.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 ${De==="stopped"?"bg-red-500/[0.08] text-red-500":De==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:De}),w&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Me=R.sessionId;if(Me){f(Xt(Me),{state:{openRemoteForTabKey:Me}});return}f("/dashboard",{state:{openRemoteForTabKey:R.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:s.jsx(Tt,{size:13})}),s.jsx("button",{onClick:()=>{const Me=R.workspace||"",{options:Ke,selectedKey:at}=ls({machine:t,currentWorkspacePath:Me});Ae({title:ns("restart-ide",ot(R.type)),description:as("restart-ide"),confirmLabel:Ls("restart-ide"),busyLabel:_s("restart-ide"),workspaceOptions:Ke,selectedWorkspaceKey:at,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ot(R.type)}]},async()=>{const St=Ke.find(Vt=>Vt.key===Ye.current),mt=(St==null?void 0:St.workspacePath)??"";if(mt&&mt!==Me){await lt({type:R.type,workspacePath:mt});return}await g(R)})},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(cr,{size:14})})]}),v&&s.jsx("button",{onClick:()=>{const Me=R.sessionId;Me&&A(Me)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!R.sessionId,children:s.jsx(Ut,{size:14})}),ue&&De!=="stopped"&&s.jsxs(s.Fragment,{children:[ue.mode&&s.jsx(Ja,{mode:ue.mode,onChange:Me=>void z(ue,Me,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Me=R.sessionId;Me&&A(Me)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!R.sessionId,children:ue.mode==="chat"?s.jsx(Ut,{size:14}):s.jsx(Tt,{size:13})})]}),De==="stopped"?s.jsx("button",{onClick:()=>{const Me=R.workspace||"",Ke=w?ot(R.type):Ze(R),{options:at,selectedKey:St}=ls({machine:t,currentWorkspacePath:Me});Ae({title:ns("restart-stopped",Ke),description:as("restart-stopped"),confirmLabel:Ls("restart-stopped"),busyLabel:_s("restart-stopped"),workspaceOptions:at,selectedWorkspaceKey:St,details:[{label:"Mode",value:M.label},{label:"Provider",value:Ke}]},async()=>{const mt=at.find(Vt=>Vt.key===Ye.current);await lt({type:R.type,workspaceId:(mt==null?void 0:mt.workspaceId)??null,workspacePath:(mt==null?void 0:mt.workspacePath)??"",useHome:!(mt!=null&&mt.workspaceId)&&!(mt!=null&&mt.workspacePath)})})},disabled:Y.includes(R.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:Y.includes(R.type)?"⏳":s.jsx(Ba,{size:14})}):s.jsx("button",{onClick:()=>he(R),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(yt,{size:14})})]})]}),G&&G.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:G.aiAgents.map(Me=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${ic(Me.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Me.name," · ",wt(Me.status)]},Me.id))}),G&&(_e[G.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:(_e[G.type]||[]).map(Me=>s.jsxs("button",{disabled:Ie===`${G.type}.${Me.type}`,onClick:async()=>{const Ke=`${G.type}.${Me.type}`;Ge(Ke);try{await l(r,"set_ide_extension",{ideType:G.type,extensionType:Me.type,enabled:!Me.enabled}),Ee(at=>({...at,[G.type]:(at[G.type]||[]).map(St=>St.type===Me.type?{...St,enabled:!St.enabled}:St)}))}catch(at){console.error("Extension toggle failed:",at)}finally{Ge(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Me.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Me.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Me.name,s.jsx("span",{className:"text-[9px] font-normal",children:Me.enabled?"ON":"OFF"})]},Me.type))})]})]},R.id)})]}),le&&l&&s.jsx(gn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ee,directories:$e,busy:He,error:Ce,confirmLabel:"Use this folder",onClose:()=>ke(!1),onNavigate:R=>{U(R)},onConfirm:R=>{oe(R),te("__custom__"),ke(!1)}}),Be&&s.jsx(fo,{title:Be.title,description:Be.description,details:Be.details,workspaceOptions:Be.workspaceOptions,selectedWorkspaceKey:tt,onWorkspaceChange:R=>{Ye.current=R,ut(R)},confirmLabel:Be.confirmLabel,busyLabel:Be.busyLabel,busy:ft,onConfirm:Le,onCancel:()=>{Re.current=null,Fe(null)}}),ce&&Z&&s.jsx(so,{activeConv:Z,ides:[],isCreatingChat:!1,isRefreshingHistory:ie,savedSessions:Q,isSavedSessionsLoading:ie,isResumingSavedSessionId:je,savedHistoryFilters:ae,missingWorkspaceResumePath:Ve||null,onSavedHistoryFiltersChange:de,onClose:()=>ye(!1),onNewChat:()=>{H(""),ye(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{X(T)},onResumeSavedSession:R=>{if(!R.canResume||je)return;const G=E(R);H(R.providerSessionId),re(R),fe(R.providerSessionId),ye(!1),lt({type:R.providerType,workspaceId:G.workspaceId,workspacePath:G.workspacePath,useHome:G.useHome,resumeSessionId:R.providerSessionId}).finally(()=>{fe(ue=>ue===R.providerSessionId?null:ue)})}})]})}const Pi=[{id:"ide",label:"IDE",helper:"Open a graphical workspace and attach CDP"},{id:"cli",label:"CLI",helper:"Launch a terminal-first workspace on this machine"},{id:"acp",label:"ACP",helper:"Launch an ACP-backed workspace on this machine"}];function ry({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:f,onOpenGitDialog:x}){var k;const[N,g]=o.useState(d);o.useEffect(()=>{g(d)},[d]);const h=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:Pi.map(b=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${N===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>g(b.id),children:[s.jsx("span",{children:b.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${N===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:h[b.id]})]},b.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(k=Pi.find(b=>b.id===N))==null?void 0:k.helper})]}),N==="ide"&&s.jsx(aa,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),N==="cli"&&s.jsx(aa,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),N==="acp"&&s.jsx(aa,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x})]})}function ny({onNicknameSynced:e}={}){var oe,Y,V,le,ke,ee,Pe,$e,Oe,He;const{id:t}=kd(),r=Ds(),n=La(),{sendCommand:a}=xt(),i=ur(),c=tl(),l=_c(),d=l.ides||[],m=l.initialLoaded??!0,u=d.find(O=>O.id===t&&O.type==="adhdev-daemon"),f=d.some(O=>O.type==="adhdev-daemon"),x=t?(oe=l.connectionRetryStatuses)==null?void 0:oe[t]:void 0,N=!!(x!=null&&x.blocked),[g,h]=o.useState("workspace"),[k,b]=o.useState(null),p=o.useCallback((O,Ce)=>{b({daemonId:O,workspace:Ce})},[]),[y,S]=o.useState("ide"),j=o.useRef(null),[A,M]=o.useState(null),w=o.useRef("__home__"),[v,B]=o.useState("__home__"),[_,T]=o.useState(!1),D=o.useRef(null);o.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||i(t,{minFreshMs:3e4}).catch(()=>{})},[i,u,t]),o.useEffect(()=>{if(!t||!u||g!=="overview")return;const O=u.machine;(typeof(O==null?void 0:O.cpus)!="number"||typeof(O==null?void 0:O.totalMem)!="number"||typeof(O==null?void 0:O.arch)!="string"||typeof(O==null?void 0:O.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[g,c,u,t]),ih(t&&g==="overview"?[t]:[],{enabled:g==="overview",intervalMs:nf});const K=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},L=Zb({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:D});o.useEffect(()=>nt.onToast(Ce=>{l.setToasts(Re=>{if(Re.some(Ye=>Ye.message===Ce.message&&Ce.timestamp-Ye.timestamp<3e3))return Re;const Fe={id:Ce.id,message:Ce.message,type:Ce.type,timestamp:Ce.timestamp,targetKey:Ce.targetKey,actions:Ce.actions};return[...Re.slice(-4),Fe]});const Te=Ce.duration||5e3;setTimeout(()=>l.setToasts(Re=>Re.filter(Be=>Be.id!==Ce.id)),Te)}),[l]);const C=(u==null?void 0:u.availableProviders)||[],I={};for(const O of C)I[O.type]=O.icon;const W=O=>I[O]||"",P=u?{id:u.id,hostname:cc(u,{fallbackId:u.id}),platform:((Y=u.machine)==null?void 0:Y.platform)||"unknown",arch:((V=u.machine)==null?void 0:V.arch)||"",cpus:((le=u.machine)==null?void 0:le.cpus)||0,totalMem:((ke=u.machine)==null?void 0:ke.totalMem)||0,freeMem:(ee=u.machine)==null?void 0:ee.freeMem,availableMem:(Pe=u.machine)==null?void 0:Pe.availableMem,loadavg:($e=u.machine)==null?void 0:$e.loadavg,uptime:(Oe=u.machine)==null?void 0:Oe.uptime,release:((He=u.machine)==null?void 0:He.release)||"",cdpConnected:!!u.cdpConnected,machineNickname:u.machineNickname||null,p2p:u.p2p?{screenshotActive:!1,...u.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:u.detectedIdes||[],workspaces:u.workspaces||[],defaultWorkspaceId:u.defaultWorkspaceId??u.activeWorkspaceId??null,defaultWorkspacePath:u.defaultWorkspacePath??u.activeWorkspacePath??null}:null,$=d.filter(O=>O.daemonId===t&&O.type!=="adhdev-daemon").filter(O=>!or(O)&&!ks(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,version:O.version||"",instanceId:O.instanceId||"",status:O.status,workspace:O.workspace||null,terminals:O.terminals||0,aiAgents:sm(O.aiAgents||(O.agents||[]).map(Ce=>({id:Ce.name,name:Ce.name,status:Ce.status,version:Ce.version}))),activeChat:O.activeChat||null,chats:O.chats||[],childSessions:O.childSessions||[],cdpConnected:O.cdpConnected||!1,daemonId:t})),H=d.filter(O=>O.daemonId===t&&or(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,cliName:O.cliName||O.type,status:O.status,workspace:O.workspace||"",activeChat:O.activeChat||null,providerSessionId:O.providerSessionId,mode:O.mode,runtimeKey:O.runtimeKey,runtimeDisplayName:O.runtimeDisplayName,runtimeWorkspaceLabel:O.runtimeWorkspaceLabel,runtimeWriteOwner:O.runtimeWriteOwner||null,runtimeAttachedClients:O.runtimeAttachedClients||[],daemonId:t})),Q=d.filter(O=>O.daemonId===t&&ks(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,acpName:O.cliName||O.type,status:O.status,workspace:O.workspace||"",activeChat:O.activeChat||null,providerSessionId:O.providerSessionId,daemonId:t})),xe=u?Ct(u,{fallbackId:t}):"",ie="workspace",se=n.state,be=se==null?void 0:se.initialMachineTab,we=se==null?void 0:se.initialWorkspaceCategory,ge=se==null?void 0:se.initialWorkspaceId,J=se==null?void 0:se.initialWorkspacePath,ce=be==="ides"||be==="clis"||be==="acps"?"workspace":be||ie,ye=be==="ides"?"ide":be==="clis"?"cli":be==="acps"?"acp":we,ae=[...$.map(O=>{var Ce,Te,Re,Be,Fe;return{id:`ide:${O.type}:${O.workspace||""}`,label:((Ce=O.activeChat)==null?void 0:Ce.title)||O.type,kind:"ide",providerType:O.type,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:((Fe=(Be=(Re=(Te=O.activeChat)==null?void 0:Te.messages)==null?void 0:Re.at)==null?void 0:Be.call(Re,-1))==null?void 0:Fe.timestamp)||0}}),...H.map(O=>{var Ce,Te,Re,Be,Fe;return{id:`cli:${O.type}:${O.workspace||""}`,label:((Ce=O.activeChat)==null?void 0:Ce.title)||O.cliName,kind:"cli",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:((Fe=(Be=(Re=(Te=O.activeChat)==null?void 0:Te.messages)==null?void 0:Re.at)==null?void 0:Be.call(Re,-1))==null?void 0:Fe.timestamp)||0}}),...Q.map(O=>{var Ce,Te,Re,Be,Fe;return{id:`acp:${O.type}:${O.workspace||""}`,label:((Ce=O.activeChat)==null?void 0:Ce.title)||O.acpName,kind:"acp",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:ms(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:((Fe=(Be=(Re=(Te=O.activeChat)==null?void 0:Te.messages)==null?void 0:Re.at)==null?void 0:Be.call(Re,-1))==null?void 0:Fe.timestamp)||0}})].sort((O,Ce)=>(Ce.lastLaunchedAt||0)-(O.lastLaunchedAt||0)),de=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(O=>({id:O.id,label:O.title||O.providerName||O.providerType,kind:O.kind,providerType:O.providerType,providerSessionId:O.providerSessionId,subtitle:ms(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace,summaryMetadata:O.summaryMetadata,lastLaunchedAt:O.lastLaunchedAt})):ae,je=o.useMemo(()=>{var Ce;const O=((Ce=l.connectionStates)==null?void 0:Ce[t||""])||void 0;return d.filter(Te=>Te.daemonId===t&&Te.type!=="adhdev-daemon").flatMap(Te=>ro(Te,{connectionStates:t&&O?{[t]:O}:void 0,defaultConnectionState:O})).filter(Te=>!(Te.transport==="pty"&&Te.mode==="terminal")).sort((Te,Re)=>Na(Re)-Na(Te))},[d,l.connectionStates,t]),fe=o.useCallback(O=>{const Ce=uo(O);Ce&&r(Xt(Ce))},[r]),pe=o.useCallback(()=>{j.current&&(T(!0),j.current().finally(()=>{j.current=null,T(!1),M(null)}))},[]),te=o.useCallback(O=>{if(!P)return;const{options:Ce,selectedKey:Te}=ls({machine:P,currentWorkspacePath:O.workspace}),Re=async()=>{S(O.kind),h("workspace")};j.current=async()=>{const Be=Ce.find(tt=>tt.key===w.current),Fe=(Be==null?void 0:Be.workspacePath)??null,Ye=(Be==null?void 0:Be.workspaceId)??null;if(O.kind==="ide"&&O.providerType){await L.handleLaunchIde(O.providerType,Fe?{workspace:Fe}:void 0);return}if((O.kind==="cli"||O.kind==="acp")&&O.providerType){await L.runLaunchCliCore({cliType:O.providerType,dir:Ye?void 0:Fe||"",workspaceId:Ye||void 0,model:O.kind==="acp"&&dc(O.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:O.providerSessionId});return}await Re()},w.current=Te,B(Te),M({title:O.kind==="ide"?ns("restart-ide",O.label):O.providerSessionId?eo(O.label):ns("start-fresh",O.label),description:O.kind==="ide"?as("restart-ide"):O.providerSessionId?to():as("start-fresh"),confirmLabel:O.kind==="ide"?Ls("restart-ide"):O.providerSessionId?tn(!0):Ls("start-fresh"),busyLabel:O.kind==="ide"?_s("restart-ide"):O.providerSessionId?Qa(!0):_s("start-fresh"),workspaceOptions:Ce,details:[{label:"Mode",value:O.kind.toUpperCase()},...O.providerType?[{label:"Provider",value:O.providerType}]:[]]})},[L,P]);if(o.useEffect(()=>{h(ce)},[ie,ce,t]),o.useEffect(()=>{ye&&S(ye)},[ye,t]),!P)return m?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:K,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 me=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tt,{size:14})," Workspace"]}),count:$.length+H.length+Q.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ot,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(cn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(tu,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Qd,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:K,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:[L.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:L.nicknameInput,onChange:O=>L.setNicknameInput(O.target.value),onKeyDown:O=>{O.key==="Enter"&&L.handleSaveNickname(),O.key==="Escape"&&L.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:L.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:()=>L.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:()=>{L.setEditingNickname(!0),L.setNicknameInput(P.machineNickname||"")},title:"Click to set nickname",children:xe}),N?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),l.retryConnection&&t&&s.jsx("button",{onClick:()=>l.retryConnection(t),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[P.platform," · ",P.arch]}),s.jsxs("span",{children:[P.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),P.p2p.available&&s.jsxs("span",{children:["P2P ",P.p2p.state==="connected"?"connected":P.p2p.state]}),P.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:P.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:me.map(O=>s.jsxs("button",{onClick:()=>h(O.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${g===O.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[O.label,O.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${g===O.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:O.count})]},O.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[g==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(Zg,{machineEntry:u,providers:C,recentLaunches:de,currentConversations:je,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:te,onOpenConversation:fe}),s.jsx(ry,{machine:P,machineId:t,providers:C,ideSessions:$,cliSessions:H,acpSessions:Q,actions:L,getIcon:W,initialCategory:y,initialWorkspaceId:ge,initialWorkspacePath:J,sendDaemonCommand:a,onOpenGitDialog:p})]}),g==="providers"&&s.jsx(lg,{machineId:t,providers:C,sendDaemonCommand:a}),g==="overview"&&s.jsx(eg,{machineId:t,machine:P,ideSessions:$,cliSessions:H,acpSessions:Q,actions:L,sendDaemonCommand:a}),g==="session-host"&&s.jsx(Jg,{machineId:t,cliSessions:H,sendDaemonCommand:a}),g==="logs"&&s.jsx(Ug,{machineId:t,sendDaemonCommand:a})]})})}),L.launchPick&&P&&s.jsx(Qg,{machine:P,launchPick:L.launchPick,actions:L}),A&&s.jsx(fo,{title:A.title,description:A.description,details:A.details,workspaceOptions:A.workspaceOptions,selectedWorkspaceKey:v,onWorkspaceChange:O=>{w.current=O,B(O)},confirmLabel:A.confirmLabel,busyLabel:A.busyLabel,busy:_,onConfirm:pe,onCancel:()=>{j.current=null,M(null)}}),k&&s.jsx(Fl,{daemonId:k.daemonId,workspace:k.workspace,onClose:()=>b(null)}),s.jsx(Hc,{toasts:l.toasts||[],onDismiss:O=>l.setToasts(Ce=>Ce.filter(Te=>Te.id!==O)),onClickToast:O=>{O.targetKey&&r(Xt(O.targetKey))}}),s.jsx("style",{children:`
|
|
90
|
-
@keyframes toast-in {
|
|
91
|
-
from { opacity: 0; transform: translateX(40px); }
|
|
92
|
-
to { opacity: 1; transform: translateX(0); }
|
|
93
|
-
}
|
|
94
|
-
`})]})}function ay({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const i=a.id.toLowerCase(),c=a.name.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||c.includes("hermes")}),n=xl(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(jt,{title:"Hermes MCP Config",description:"Hermes does not auto-import repo-local .mcp.json. Add this YAML under mcp_servers in Hermes config, then start a fresh Hermes session.",children:s.jsx(Wl,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function oy(){const{sendCommand:e}=xt(),{ides:t}=Jt(),r=t.find(D=>D.daemonMode||D.type==="adhdev-daemon"),n=(r==null?void 0:r.id)||"",a=[];if(r){const D=r.availableProviders||[];for(const K of D)K.category==="cli"&&a.push({id:K.type||K.id,name:K.displayName||K.name||K.type,meshCoordinator:K.meshCoordinator})}const[i,c]=o.useState([]),[l,d]=o.useState(null),[m,u]=o.useState(!0),[f,x]=o.useState(null),[N,g]=o.useState(!1),[h,k]=o.useState(""),[b,p]=o.useState(""),[y,S]=o.useState(!1),[j,A]=o.useState(""),M=i.find(D=>D.id===l)||null,w=o.useCallback(async()=>{if(n){u(!0);try{const D=await e(n,"list_meshes");D!=null&&D.success?(c(D.meshes||[]),x(null)):x((D==null?void 0:D.error)||"Failed to load meshes")}catch(D){x((D==null?void 0:D.message)||"Failed to load meshes")}finally{u(!1)}}},[n,e]);o.useEffect(()=>{w()},[w]);async function v(){var D;if(!(!n||!h.trim()))try{const K=await e(n,"create_mesh",{name:h.trim(),repoIdentity:b.trim()||void 0});K!=null&&K.success?(g(!1),k(""),p(""),await w(),d(((D=K.mesh)==null?void 0:D.id)||null)):x((K==null?void 0:K.error)||"Create failed")}catch(K){x((K==null?void 0:K.message)||"Create failed")}}async function B(D){if(!(!n||!confirm("Delete this mesh?")))try{await e(n,"delete_mesh",{meshId:D}),d(null),await w()}catch(K){x((K==null?void 0:K.message)||"Delete failed")}}async function _(){if(!(!n||!l||!j.trim()))try{const D=await e(n,"add_mesh_node",{meshId:l,workspace:j.trim()});D!=null&&D.success?(S(!1),A(""),await w()):x((D==null?void 0:D.error)||"Add node failed")}catch(D){x((D==null?void 0:D.message)||"Add node failed")}}async function T(D){if(!(!n||!l))try{await e(n,"remove_mesh_node",{meshId:l,nodeId:D}),await w()}catch(K){x((K==null?void 0:K.message)||"Remove node failed")}}return n?M?s.jsxs(Zs,{icon:s.jsx(vr,{}),title:M.name,subtitle:M.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>d(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>B(M.id),children:"Delete"})]}),children:[f&&s.jsx(js,{variant:"error",className:"mb-4",children:f}),s.jsxs(jt,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[s.jsx("div",{className:"flex justify-end mb-3",children:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>S(!0),children:"+ Add Node"})}),y&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),s.jsx("button",{onClick:()=>S(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(yt,{size:16})})]}),s.jsx(_n,{label:"Workspace Path",children:s.jsx(Pn,{value:j,onChange:D=>A(D.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:D=>{D.key==="Enter"&&_()},autoFocus:!0})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:_,disabled:!j.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>S(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),M.nodes.length===0?s.jsx(sn,{icon:s.jsx(us,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:M.nodes.map(D=>s.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium",children:D.workspace.split("/").pop()}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:D.workspace})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:()=>T(D.id),children:s.jsx(yt,{size:14})})]},D.id))})]}),s.jsx(ay,{meshId:M.id,availableCliAgents:a})]}):s.jsxs(Zs,{icon:s.jsx(vr,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>g(!0),children:"+ Create Mesh"}),children:[f&&s.jsx(js,{variant:"error",className:"mb-4",children:f}),N&&s.jsx(jt,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(_n,{label:"Name",children:s.jsx(Pn,{value:h,onChange:D=>k(D.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(_n,{label:"Repo Identity (optional)",children:s.jsx(Pn,{value:b,onChange:D=>p(D.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:v,disabled:!h.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(!1),children:"Cancel"})]})]})}),m?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):i.length===0?s.jsx(sn,{icon:s.jsx(vr,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(D=>s.jsxs("button",{className:"text-left w-full p-4 rounded-xl border border-border-subtle bg-bg-panel hover:border-accent-primary/40 transition-colors",onClick:()=>d(D.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:D.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:D.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[D.nodes.length," node(s)"]})]},D.id))})]}):s.jsx(Zs,{icon:s.jsx(vr,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function go(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function iy(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=go();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Dt(e,t){return await fetch(iy(e),{credentials:"same-origin",...t})}function zl(){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 cy{constructor(){Je(this,"adapters",new Map);Je(this,"states",new Map);Je(this,"runtimeListeners",new Map);Je(this,"screenshotCallbacks",new Map);Je(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 Dt(`${a.pathname}${a.search}`);if(!i.ok){let l=`Runtime snapshot unavailable (${i.status})`;try{const d=await i.json();d!=null&&d.error&&(l=d.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 Kt=new cy;function ly(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=go();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Er=ly(),Di=3e3,dy=3e4;let Lt=null,uy=0;const on=new Map;let Zt=null,sr=null;function Ei(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Vs(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function my(e){return e==="connected"?"connected":e}async function zr(e,t,r){const n=Vc(e,r||{}),a=Lt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++uy}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{on.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);on.set(i,{resolve:m=>{clearTimeout(d),c(m)},reject:m=>{clearTimeout(d),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 Aa(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 fy(e,t,r){const n=Lt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Vc(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 py{constructor(t){Je(this,"daemonId");Je(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 zr(this.daemonId,t,r)}async sendInput(t,r){return zr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Zt&&(clearInterval(Zt),Zt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await zr(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());Kt.emitScreenshot(this.daemonId,a)}}catch{}};r(),Zt=setInterval(r,2e3)}stopScreenshots(t){Zt&&(clearInterval(Zt),Zt=null)}}let At=null;function hy(e){return(!At||At.daemonId!==e)&&(At=new py(e)),At}function xy({children:e}){const t=o.useRef(nr()),r=nr();t.current=r;const{setUserName:n}=Jt(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),d=o.useCallback((h,k)=>{l(h),sr==null||sr(h,k)},[]),m=o.useRef(null),u=o.useRef(),f=o.useRef(Di),x=o.useRef(!0),N=o.useRef(!1),g=o.useRef("initial_connect");return o.useEffect(()=>{x.current=!0,N.current=!1;function h(){var p,y;if(!x.current||((p=m.current)==null?void 0:p.readyState)===WebSocket.OPEN||((y=m.current)==null?void 0:y.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Er}...`),Vs("connect_attempt",{url:Er,reason:g.current,delayMs:f.current});let b;try{b=new WebSocket(Er)}catch(S){console.error("[Standalone WS] Failed to create WebSocket:",S),k();return}m.current=b,b.onopen=()=>{if(!x.current){b.close();return}d("connected"),f.current=Di,Vs("open",{url:Er,reason:g.current}),Ht.resubscribeAll({sendData:Aa}),console.log("[Standalone WS] Connected")},Lt=b,b.onmessage=S=>{var j,A;try{const M=JSON.parse(S.data);if((M.type==="command_result"||M.type==="error")&&M.requestId){const w=on.get(M.requestId);w&&(on.delete(M.requestId),M.type==="error"?w.reject(new Error(((j=M.data)==null?void 0:j.message)||"Command failed")):w.resolve(M.data));return}if(M.type==="session_output"){const w=M.sessionId||M.cliId||M.cliType;w&&Kt.emitSessionOutput(w,typeof M.data=="string"?M.data:"",typeof M.seq=="number"?M.seq:void 0);return}if(M.type==="runtime_snapshot"){Kt.emitRuntimeSnapshot(M.sessionId,typeof M.text=="string"?M.text:"",typeof M.seq=="number"?M.seq:0,!!M.truncated,typeof M.cols=="number"?M.cols:void 0,typeof M.rows=="number"?M.rows:void 0);return}if(M.type==="topic_update"){const w=M.update;w&&Ht.publish(w);return}if(M.type==="status"||M.type==="initial_state"){const w=M.data;if(!w)return;const{injectEntries:v,markLoaded:B,getIdes:_}=t.current,T=w.instanceId||"standalone",D=_().find(C=>C.id===T),K=hy(T);Kt.register(T,K),Kt.setState(T,"connected"),d("connected",T),Kt.emitStatus(T,w);const L=en(w,{daemonId:T,existingDaemon:D,existingEntries:_()});Ei("ws_status",{type:M.type,daemonId:T,sessions:(w.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(w.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Ei("entries",{daemonId:T,entries:L.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),L.length>0&&v(L,{authoritativeDaemonIds:[T]}),B(),c.current!==T&&((A=i.current)==null||A.call(i),c.current=T,i.current=Ht.subscribe({sendData:Aa},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const I=t.current.getIdes(),W=I.find($=>$.id===T),P=en(C.status,{daemonId:T,existingDaemon:W,existingEntries:I,timestamp:C.timestamp});P.length>0&&t.current.injectEntries(P,{authoritativeDaemonIds:[T]}),C.userName&&a.current&&a.current(C.userName)}))}}catch(M){console.error("[Standalone WS] Parse error:",M)}},b.onclose=S=>{x.current&&(At==null||At.stopScreenshots(),At&&Kt.setState(At.daemonId,"disconnected"),d("disconnected"),m.current=null,g.current=`close:${S.code}${S.wasClean?":clean":":unclean"}`,Vs("close",{code:S.code,reason:S.reason||"",wasClean:S.wasClean}),k())},b.onerror=S=>{N.current||!x.current||(g.current="error",Vs("error",{message:S instanceof Event?"event":String(S),readyState:b.readyState}),console.warn("[Standalone WS] Error, will reconnect:",S))}}function k(){if(!x.current)return;clearTimeout(u.current);const b=f.current;console.log(`[Standalone WS] Reconnecting in ${b}ms...`),Vs("schedule_reconnect",{reason:g.current,delayMs:b}),u.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,dy),h()},b)}return h(),()=>{var b;x.current=!1,N.current=!0,(b=i.current)==null||b.call(i),i.current=null,c.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Lt=null),At&&(At.stopScreenshots(),Kt.unregister(At.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function by({children:e}){const[t,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(sr=(c,l)=>{r(c),l&&a(l)},()=>{sr=null}),[]);const i=o.useMemo(()=>{const c=t==="connected",l=my(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(Od,{connectionOverrides:i,children:s.jsx(xy,{children:e})})}const Vl="adhdev_standalone_font_preferences",ds={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},wn=[{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"}],ir=[{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"}],gy=new Set(wn.map(e=>e.id)),yy=new Set(ir.map(e=>e.id));function $t(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Vr("chat",t.chat),code:Vr("code",t.code),terminal:Vr("terminal",t.terminal)}}function Vr(e,t){const r=ds[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"?gy:yy).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Gr(e,t){var a;const r=Vr(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?wn:ir;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function vy(e){const t=$t(e),r=Gr("chat",t.chat),n=Gr("code",t.code),a=Gr("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function ts(e,t=document.documentElement){const r=$t(e),n=vy(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function Ia(e){const t=$t(e);try{localStorage.setItem(Vl,JSON.stringify(t))}catch{}return t}function wy(){try{const e=localStorage.getItem(Vl);if(e)return $t(JSON.parse(e))}catch{}return ds}function jy(){return ts(wy())}function Gs(e,t){var n;const r=e==="chat"?wn:ir;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const ky=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Vi,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(Ot,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Ms,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(cn,{}),label:"Settings"}];function Sy({children:e}){const t=Ds(),r=La(),n=o.useMemo(()=>ky.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(qi,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Yi,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(_p,{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.74"]}),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 Ny=[{icon:s.jsx(Ot,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ut,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Xi,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Tt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Ms,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(qi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Cy=[{icon:s.jsx(ru,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Vi,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(ln,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Jd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Gi,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Zd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Ty=[{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 My(){return s.jsxs(Zs,{icon:s.jsx(Yi,{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.74"]}),children:[s.jsx(jt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),s.jsx(jt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Ny.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(jt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Gc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Yc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:qc.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(jt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Cy.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(jt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:Ty.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(sn,{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(fu,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function oa(e,t,r){return{...e,[t]:r}}function ia({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:Gr(e,n)})]})]})]})}function Ay({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:d}){const m=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(ia,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:wn,onChange:u=>i(oa(e,"chat",u))}),s.jsx(ia,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:ir,onChange:u=>i(oa(e,"code",u))}),s.jsx(ia,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:ir,onChange:u=>i(oa(e,"terminal",u))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Gs("chat",e.chat.preset)," · Code: ",Gs("code",e.code.preset)," · Terminal: ",Gs("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Gs("chat",ds.chat.preset)," / ",Gs("code",ds.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:d,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function Iy(){const{ides:e}=Jt(),t=e.find(J=>J.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=xt(),{userName:a}=Jt(),[i,c]=o.useState(a||""),[l,d]=o.useState(null),[m,u]=o.useState(null),[f,x]=o.useState(ds),[N,g]=o.useState(!1),[h,k]=o.useState(""),[b,p]=o.useState(""),[y,S]=o.useState("127.0.0.1"),[j,A]=o.useState(""),[M,w]=o.useState(""),[v,B]=o.useState(""),[_,T]=o.useState(""),[D,K]=o.useState(""),[L,C]=o.useState(!1),I=async()=>{const ce=await(await Dt("/auth/session")).json();d(ce)},W=async()=>{const ce=await(await Dt("/api/v1/standalone/preferences")).json();u(ce),S(ce.standaloneBindHost);const ye=$t(ce.standaloneFontPreferences);x(ye),ts(ye),Ia(ye)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([I(),W()]).catch(J=>{T(J instanceof Error?J.message:String(J))})},[]),o.useEffect(()=>{ts(f)},[f]);const P=J=>{const ce=J.target.value.trim();t!=null&&t.id&&ce!==a&&n(t.id,"set_user_name",{userName:ce}).catch(console.error)},[$,H]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),Q=J=>{H(J);try{localStorage.setItem("adhdev_sound",J?"1":"0")}catch{}},xe=async()=>{k(""),p(""),g(!0);try{const J=$t(f),ce=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:J})}),ye=await ce.json();if(!ce.ok)throw new Error((ye==null?void 0:ye.error)||"Failed to save standalone font preferences");const ae=$t(ye.standaloneFontPreferences);u(ye),x(ae),ts(ae),Ia(ae),p("Standalone chat fonts saved for this self-hosted dashboard.")}catch(J){k(J instanceof Error?J.message:String(J))}finally{g(!1)}},ie=()=>{const J=$t(m==null?void 0:m.standaloneFontPreferences);k(""),p(""),x(J),ts(J)},se=()=>{k(""),p(""),x(ds),ts(ds)},be=async()=>{T(""),K(""),C(!0);try{const J=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:y})}),ce=await J.json();if(!J.ok)throw new Error((ce==null?void 0:ce.error)||"Failed to save standalone network preference");u(ce),S(ce.standaloneBindHost),K(ce.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(J){T(J instanceof Error?J.message:String(J))}finally{C(!1)}},we=async()=>{if(T(""),K(""),M.trim().length<4){T("Password must be at least 4 characters.");return}if(M!==v){T("New password and confirmation do not match.");return}C(!0);try{const J=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:j,newPassword:M})}),ce=await J.json();if(!J.ok)throw new Error((ce==null?void 0:ce.error)||"Failed to save password");d(ce),await W(),A(""),w(""),B(""),K(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),zl()}catch(J){T(J instanceof Error?J.message:String(J))}finally{C(!1)}},ge=async()=>{T(""),K(""),C(!0);try{const J=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:j,clear:!0})}),ce=await J.json();if(!J.ok)throw new Error((ce==null?void 0:ce.error)||"Failed to clear password");d(ce),await W(),A(""),w(""),B(""),K("Standalone password disabled.")}catch(J){T(J instanceof Error?J.message:String(J))}finally{C(!1)}};return s.jsxs(Zs,{icon:s.jsx(cn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(js,{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(js,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(jt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.74"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(jt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:y==="127.0.0.1",onChange:()=>S("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:y==="0.0.0.0",onChange:()=>S("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:()=>{be()},disabled:L,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:L?"Saving…":"Save default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(jt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),_&&s.jsx(js,{variant:"error",children:_}),D&&s.jsx(js,{variant:"success",children:D}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:j,onChange:J=>A(J.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:M,onChange:J=>w(J.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:v,onChange:J=>B(J.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{we()},disabled:L,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:L?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ge()},disabled:L,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),s.jsx(jt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(J=>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 ${J.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:J.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:J.type})]},J.type))})}),s.jsx(jt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Fp,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(jt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(Vp,{})]}),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(eh,{})]}),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(Ay,{value:f,savedValue:$t(m==null?void 0:m.standaloneFontPreferences),saving:N,error:h,notice:b,onChange:x,onSave:()=>{xe()},onResetToSaved:ie,onResetToDefaults:se})]}),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(rh,{})]})]})}),s.jsx(jt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Kp,{}),s.jsx(es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(mu,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:$,onChange:Q})]})}),s.jsx(jt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Xd,{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:J=>c(J.target.value),onBlur:P,onKeyDown:J=>{J.key==="Enter"&&J.currentTarget.blur()}})]})})})]})}Rp();Qp();jy();const Ry=Ui({baseUrl:"",getToken:go});function Ly({children:e}){const[t,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,d]=o.useState(""),[m,u]=o.useState(!1),f=async()=>{a(!0),d("");try{const g=await(await Dt("/auth/session")).json();r(g)}catch(N){d(N instanceof Error?N.message:String(N))}finally{a(!1)}};o.useEffect(()=>{f()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let N=!1;return(async()=>{try{const g=await Dt("/api/v1/standalone/preferences");if(!g.ok)return;const h=await g.json();if(N)return;const k=$t(h.standaloneFontPreferences);ts(k),Ia(k)}catch{}})(),()=>{N=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const x=async N=>{N.preventDefault(),u(!0),d("");try{const g=await Dt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),h=await g.json();if(!g.ok)throw new Error((h==null?void 0:h.error)||"Login failed");r(h),c(""),zl()}catch(g){d(g instanceof Error?g.message:String(g))}finally{u(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:x,children:[s.jsx("input",{type:"password",value:i,onChange:N=>c(N.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 $i(){const{ides:e,initialLoaded:t}=Jt();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(da,{to:`/machines/${r.id}`,replace:!0}):s.jsx(da,{to:"/dashboard",replace:!0})}function _y(){const e=o.useMemo(()=>({sendCommand:zr,sendData:Aa,sendPtyInput:fy}),[]);return s.jsx(Sd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Ud,{client:Ry,children:s.jsx(Ly,{children:s.jsx(by,{children:s.jsx(Vd,{value:e,children:s.jsx(Sy,{children:s.jsxs(Nd,{children:[s.jsx(Gt,{path:"/dashboard",element:s.jsx(Qb,{})}),s.jsx(Gt,{path:"/machine",element:s.jsx($i,{})}),s.jsx(Gt,{path:"/machines/:id",element:s.jsx(ny,{})}),s.jsx(Gt,{path:"/machines",element:s.jsx($i,{})}),s.jsx(Gt,{path:"/about",element:s.jsx(My,{})}),s.jsx(Gt,{path:"/settings",element:s.jsx(Iy,{})}),s.jsx(Gt,{path:"/mesh",element:s.jsx(oy,{})}),s.jsx(Gt,{path:"*",element:s.jsx(da,{to:"/dashboard",replace:!0})})]})})})})})})})}Vf({connectionManager:Kt});Cd(document.getElementById("root")).render(s.jsx(_y,{}));
|