@adhdev/daemon-standalone 0.9.11 → 0.9.13
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 +81 -44
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-CWraVFQO.js +76 -0
- package/public/index.html +1 -1
- package/public/assets/index-BbUILAkr.js +0 -76
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-Bv6gUGuY.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Hl=Object.defineProperty;var Fl=(e,s,r)=>s in e?Hl(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var Ge=(e,s,r)=>Fl(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as ua,a as ma,b as li,c as di,u as Ms,R as St,d as zs,t as Ul,e as zl,D as Vl,f as Fn,g as Un,h as fa,i as Gl,k as ql,B as Yl,l as Xl,m as Yt,N as zn,n as Jl}from"./vendor-BRZ4K-AC.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.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 Ql(e={}){const s=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>s&&r.splice(0,r.length-s),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 ks=Ql();function ro(e){const s={};for(const r of e)r.transport&&(s[r.transport]=(s[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:s}}function Zl(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function ed(e,s){return Object.prototype.hasOwnProperty.call(e,s)}function ui(e,s){if(!e)return s??null;if(!s)return e??null;const r=ed(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:s.messages,a=e.activeModal||(e.status==="waiting_approval"?s.activeModal:null),i={...s,...e,activeModal:a,inputContent:e.inputContent??s.inputContent};return r?{...i,messages:n}:i}function Bs(e,s){const r=Zl(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(s==null?void 0:s.parentSessionId)??null,providerSessionId:e.providerSessionId??(s==null?void 0:s.providerSessionId),providerName:r??(s==null?void 0:s.providerName)??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??e.providerName??e.providerType,title:e.title??(s==null?void 0:s.title)??r??(s==null?void 0:s.providerName)??e.providerName??e.providerType,workspace:e.workspace??(s==null?void 0:s.workspace)??null,mode:e.mode??(s==null?void 0:s.mode),capabilities:e.capabilities??(s==null?void 0:s.sessionCapabilities)??(s==null?void 0:s.capabilities)??[],cdpConnected:e.cdpConnected??(s==null?void 0:s.cdpConnected),activeChat:ui(e.activeChat,s==null?void 0:s.activeChat),controlValues:e.controlValues??(s==null?void 0:s.controlValues),providerControls:e.providerControls??(s==null?void 0:s.providerControls),summaryMetadata:e.summaryMetadata??(s==null?void 0:s.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:e.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:e.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:e.lastMessageHash??(s==null?void 0:s.lastMessageHash),unread:e.unread??(s==null?void 0:s.unread),lastSeenAt:e.lastSeenAt??(s==null?void 0:s.lastSeenAt),inboxBucket:e.inboxBucket??(s==null?void 0:s.inboxBucket),completionMarker:e.completionMarker??(s==null?void 0:s.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(s==null?void 0:s.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(s==null?void 0:s.surfaceHidden),resume:e.resume??(s==null?void 0:s.resume),runtimeKey:e.runtimeKey??(s==null?void 0:s.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(s==null?void 0:s.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(s==null?void 0:s.runtimeWorkspaceLabel)}}function mi(e,s,r){if(!(s!=null&&s.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(s)?s:e;if(!(e!=null&&e.length))return s;const n=s.map(a=>{const i=e.find(c=>c.id===a.id);return i?Bs(a,i):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(s.map(i=>i.id));for(const i of e)a.has(i.id)||n.push(i)}return n}function no(e){return!!e&&typeof e=="object"&&"text"in e}function pa(e,s){const r=(s==null?void 0:s.joiner)??" ",n=(s==null?void 0:s.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(i=>typeof i=="string"?i:no(i)?String(i.text||""):"").join(r):no(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Vs(e){return pa(e,{normalizeWhitespace:!0})}const fi=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}),pi=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function ao(e){var r,n;let s=0;return e.activeChat!==void 0&&(s+=4),(r=e.childSessions)!=null&&r.length&&(s+=2),e.workspace&&(s+=1),e.machine&&(s+=1),(n=e.agents)!=null&&n.length&&(s+=1),s}function hi(e,s,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=s.version??r.version??e.version,i=s.serverVersion??e.serverVersion??r.serverVersion,c=s.versionMismatch===!0||e.versionMismatch===!0,l=s.versionUpdateRequired===!0||e.versionUpdateRequired===!0,u=s.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),i&&(n.serverVersion=i),u&&(n.versionUpdateReason=u),a&&i&&a===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((s.versionMismatch===!0||c&&a&&i&&a!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function td(e){let s=2166136261;for(let r=0;r<e.length;r+=1)s^=e.charCodeAt(r),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}function dn(e){if(!e||typeof e!="object")return"";const s=e,r=td(Vs(s.content).slice(0,512));return[String(s.id||""),String(s._localId||""),String(s._turnKey||""),String(s.index??""),String(s.role||""),String(s.receivedAt??s.timestamp??""),r].join(":")}function sd(e,s){if(!Array.isArray(e))return e;if(s!=null&&s.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=dn(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:dn(e[0]),last:dn(e[e.length-1])}}function Vn(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Gn(e,s,r){if(!e||!s||typeof e!="object"||typeof s!="object")return;if(Vn(e)&&Vn(s)){const c=e.messages;Array.isArray(c)&&c===s.messages&&r.add(c)}if(Array.isArray(e)&&Array.isArray(s)){const c=Math.min(e.length,s.length);for(let l=0;l<c;l+=1)Gn(e[l],s[l],r);return}const n=e,a=s,i=new Set([...Object.keys(n),...Object.keys(a)]);for(const c of i)c!=="messages"&&Gn(n[c],a[c],r)}function Ks(e,s){return Array.isArray(e)?e.map(r=>Ks(r,s)):!e||typeof e!="object"?e:Vn(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?sd(a,s):Ks(a,s)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Ks(n,s)]))}function rd(e,s){try{const r=new WeakSet;return Gn(e,s,r),JSON.stringify(Ks(e,r))===JSON.stringify(Ks(s,r))}catch{return!1}}function qn(e,s,r){return rd(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function xi(e){var s;return e.daemonId||((s=e.id)==null?void 0:s.split(":")[0])||e.id}function nd(e,s,r){s[r]!==void 0&&(e[r]=s[r])}function oo(e,s,r,n){var l;const a=(l=s.chats)!=null&&l.length?s.chats:e.chats,i=mi(e.childSessions,s.childSessions,{preserveMissing:n}),c=ui(s.activeChat,e.activeChat);return hi(e,s,{...e,...s,chats:a,childSessions:i,activeChat:c,_lastUpdate:r})}function ad(e,s,r){var a,i;const n={};s.status&&s.status!==e.status&&(n.status=s.status),s.cdpConnected!==void 0&&(n.cdpConnected=s.cdpConnected),s.childSessions!==void 0&&(n.childSessions=mi(e.childSessions,s.childSessions,{preserveMissing:r})),(a=s.chats)!=null&&a.length&&!((i=e.chats)!=null&&i.length)&&(n.chats=s.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"])nd(n,s,c);return s.machineNickname!==void 0&&s.machineNickname!==e.machineNickname&&(n.machineNickname=s.machineNickname),s.versionMismatch===!0&&(n.versionMismatch=!0),n}function od(e,s,r,n){const a=ad(e,s,n),i=Object.keys(a).length>0?hi(e,s,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return qn(e,i,r)}function id(e){const s=new Set(e.map(a=>a.id)),r=new Set,n=new Set;for(const a of e){const i=xi(a);i&&r.add(i),i&&a.type!=="adhdev-daemon"&&n.add(i)}return{incomingIds:s,incomingDaemonIds:r,daemonIdsWithSessionEntries:n}}function cd(e,s,r,n,a,i){return!a.has(s)||!i.has(s)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function ld(e,s,r,n){return!!(r.has(s)&&e.transport&&!n.has(s))}function dd(e,s,r){var f,d;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(h=>({...h,_lastUpdate:n}));const i=new Map;for(const h of s)i.set(h.id,h);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:u}=id(e);for(const h of e){const m=i.get(h.id);if(!m){i.set(h.id,{...h,_lastUpdate:n});continue}const k=ao(h),S=ao(m),p=xi(h),x=!a.has(p);if(k>S){const N=oo(m,h,n,x);i.set(h.id,qn(m,N,n));continue}if(k<S){i.set(h.id,od(m,h,n,x));continue}const v=h.timestamp||n,g=m._lastUpdate||m.timestamp||0;if(v>=g){const N=oo(m,h,n,x);i.set(h.id,qn(m,N,n));continue}(f=h.chats)!=null&&f.length&&!((d=m.chats)!=null&&d.length)&&i.set(h.id,{...m,chats:h.chats})}for(const[h,m]of i){const k=m.daemonId||h.split(":")[0];if(!l.has(k))continue;if(a.has(k)&&!c.has(h)){i.delete(h);continue}const S=n-(m._lastUpdate||m.timestamp||0);cd(m,k,S,c,a,u)&&i.delete(h)}for(const[h,m]of i){const k=m.daemonId||h.split(":")[0];if(ld(m,k,l,u))continue;n-(m._lastUpdate||m.timestamp||0)>3e5&&m.status!=="online"&&i.delete(h)}return Array.from(i.values())}function ud(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function md({children:e,connectionOverrides:s}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[u,f]=o.useState(void 0),d=o.useRef(r);o.useEffect(()=>{d.current=r},[r]);const h=o.useCallback((v,g)=>{n(N=>{let M=!1;const y=N.map(C=>C.id!==v||C.chats===g?C:(M=!0,{...C,chats:g}));return M?y:N})},[]),m=o.useCallback((v,g)=>{n(N=>{const M=N.length===0?v:dd(v,N,g),y=!ud(N,M);return y&&ks.record({kind:"dashboard.entries_applied",payload:{incoming:ro(v),next:ro(M)}}),y?M:N})},[]),k=o.useCallback(()=>i(!0),[]),S=o.useMemo(()=>({injectEntries:m,markLoaded:k,getIdes:()=>d.current}),[m,k]),p=s,x=o.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(p==null?void 0:p.wsStatus)??"connected",isConnected:(p==null?void 0:p.isConnected)??!0,connectionStates:(p==null?void 0:p.connectionStates)??{},connectionTransports:(p==null?void 0:p.connectionTransports)??{},showReconnected:(p==null?void 0:p.showReconnected)??!1,retryConnection:p==null?void 0:p.retryConnection,retryServerConnection:p==null?void 0:p.retryServerConnection,isP2PActive:(p==null?void 0:p.isP2PActive)??!1,p2pStates:(p==null?void 0:p.p2pStates)??{},userRole:p==null?void 0:p.userRole,userName:u,setUserName:f}),[r,h,a,c,p==null?void 0:p.wsStatus,p==null?void 0:p.isConnected,p==null?void 0:p.connectionStates,p==null?void 0:p.connectionTransports,p==null?void 0:p.showReconnected,p==null?void 0:p.retryConnection,p==null?void 0:p.retryServerConnection,p==null?void 0:p.isP2PActive,p==null?void 0:p.p2pStates,p==null?void 0:p.userRole,u]);return t.jsx(pi.Provider,{value:S,children:t.jsx(fi.Provider,{value:x,children:e})})}function cs(){return o.useContext(fi)}function Gs(){return o.useContext(pi)}function bi(e){const{baseUrl:s,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${s}${l.startsWith("/")?"":"/"}${l}`}function i(l){const u=r==null?void 0:r(),f=a(l),d=l.startsWith("http")?new URL(f):new URL(f,typeof window<"u"?window.location.origin:"http://localhost");return u&&d.searchParams.set("token",u),!l.startsWith("http")&&!s?`${d.pathname}${d.search}${d.hash}`:d.toString()}async function c(l,u={}){const f={"Content-Type":"application/json",...u.headers||{}},d=r==null?void 0:r();d&&(f.Authorization=`Bearer ${d}`);const h=a(l),m=new AbortController,k=setTimeout(()=>m.abort(),15e3);try{const S=await fetch(h,{...u,headers:f,signal:m.signal});if(S.status===401)throw n==null||n(),new Error("Unauthorized");if(!S.ok){const p=await S.json().catch(()=>({error:S.statusText}));throw new Error(p.error||`API Error: ${S.status}`)}return S.json()}finally{clearTimeout(k)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,u,f={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:f})}),execTerminal:(l,u,f)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:f})}),sendAgentMessage:(l,u,f)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:f})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,f)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:f?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,u,f={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:f})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const fd=bi({baseUrl:"http://localhost:3847"}),pd=o.createContext(fd);function hd({client:e,children:s}){return t.jsx(pd.Provider,{value:e,children:s})}const xd={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},gi=o.createContext(xd);function bd({value:e,children:s}){return t.jsx(gi.Provider,{value:e,children:s})}function jt(){return o.useContext(gi)}function gd(e){let s=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)s^=n.charCodeAt(a),s=Math.imul(s,16777619)>>>0;s^=255,s=Math.imul(s,16777619)>>>0}return s.toString(16).padStart(8,"0")}function yd(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function yi(e){return e?gd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),yd(e.content)]):""}const $e={size:18};function vi({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function ha({size:e=$e.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polyline",{points:"15 18 9 12 15 6"})})}function ls({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),t.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),t.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),t.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function wi({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"9",cy:"7",r:"4"}),t.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),t.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function vd({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function wd({size:e=$e.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.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 ji({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),t.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"}),t.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),t.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function jd({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),t.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),t.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),t.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Yr({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"3"}),t.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 ki({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),t.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function kd({size:e=$e.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Ft({size:e=$e.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.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 Ct({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function xa({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),t.jsx("polyline",{points:"14 2 14 8 20 8"}),t.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),t.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Sd({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"11",cy:"11",r:"8"}),t.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Ss({size:e=$e.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.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 er({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"23 4 23 10 17 10"}),t.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function qs({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),t.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Ys({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M12 22v-5"}),t.jsx("path",{d:"M9 8V2"}),t.jsx("path",{d:"M15 8V2"}),t.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function Si({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),t.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Ni({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.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"}),t.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Ci({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function Nd({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),t.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),t.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function ba({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"4 17 10 11 4 5"}),t.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Cd({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function ga({size:e=$e.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Ii({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function wt({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Id({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.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"}),t.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),t.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Md({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),t.jsx("path",{d:"M12 2v6"}),t.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Ad({size:e=$e.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.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 Td({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),t.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 Xr({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),t.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Ld({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"5"}),t.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),t.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),t.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),t.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),t.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),t.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),t.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),t.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function Rd({size:e=$e.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Pd({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function _d({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),t.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Dd({size:e=$e.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Ed({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),t.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 $d({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.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"}),t.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 Bd({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),t.jsx("path",{d:"M13 2h9v9"}),t.jsx("path",{d:"M22 2L13 11"})]})}function Kd({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"9 14 4 9 9 4"}),t.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Od({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),t.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),t.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),t.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),t.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),t.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),t.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),t.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),t.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),t.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function Wd({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),t.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 Hd({size:e=$e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),t.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),t.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const un=new Map;function io(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function Fd(e){if(!Array.isArray(e)||e.length===0)return"0:empty";const s=e[e.length-1];return`${e.length}:${yi(s)}`}function Ud(e,s){return!e&&s}function co(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function Mi(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function zd(e,s,r){return Number(e.receivedAt||r[Kr(e,s)]||0)||0}function Ai(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Vd(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function dr(e,s){if(!e)return s;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||s}catch{return e.split(/[\\/]/).filter(Boolean).pop()||s}}function mn(e){if(typeof e.uri=="string"&&e.uri)return e.uri;if(typeof e.data=="string"&&e.data&&typeof e.mimeType=="string"&&e.mimeType)return`data:${e.mimeType};base64,${e.data}`}function lo(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):Ai(e)?t.jsx(ua,{remarkPlugins:[ma,li,di],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function ur({parts:e,renderAsPreformatted:s}){return t.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return t.jsx("div",{children:lo(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=mn(r);return a?t.jsx("img",{src:a,alt:dr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=mn(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=mn(r);return a?t.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:dr(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||dr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=dr(r.resource.uri,"resource");if(r.resource.text)return t.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[t.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),lo(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return t.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function Kr(e,s){const r=e,n=pa(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:${s}`].filter(Boolean).join("|")}const Gd=o.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(ua,{remarkPlugins:[ma],children:s.text}),t.jsx("span",{className:"action-time",children:Mi(s.timestamp)})]})},(e,s)=>e.log===s.log),qd=o.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var C,j,w;const u=(s.role||"").toLowerCase(),f=u==="user"||u==="human",d=s.kind||(u==="tool"?"tool":"standard"),h=Vd(s.content)?s.content:null,m=!!(h!=null&&h.some(b=>b.type!=="text")),k=pa(s.content,{joiner:`
|
|
4
|
+
`});if(d==="thought"){const b=typeof((C=s.meta)==null?void 0:C.label)=="string"?s.meta.label:"Thought";return t.jsxs("div",{className:"self-start chat-msg-thought",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx(Ad,{size:13}),t.jsx("span",{children:b})]}),t.jsx("div",{className:"chat-msg-body",children:k})]})}if(d==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),m&&h?t.jsx("div",{className:"tool-text w-full",children:t.jsx(ur,{parts:h,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:k})]});if(d==="terminal"){const b=(j=s.meta)!=null&&j.isRunning?"⏳":"✅",E=typeof((w=s.meta)==null?void 0:w.label)=="string"?s.meta.label:"Ran command";return t.jsxs("div",{className:"self-start chat-msg-terminal",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx("span",{children:b}),t.jsx("span",{children:E})]}),m&&h?t.jsx("div",{className:"chat-msg-body",children:t.jsx(ur,{parts:h,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:k})]})}if(d==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:m&&h?t.jsx(ur,{parts:h,renderAsPreformatted:!1}):k.slice(0,100)});const S=s.meta,x=(typeof(S==null?void 0:S.renderMode)=="string"?S.renderMode.trim():"")==="preformatted",v=k,g=!1,N=v,M=x,y=!M&&Ai(N);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${f?"self-end":"self-start"}`,children:(v||m||f)&&t.jsxs("div",{className:`chat-bubble ${f?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${v||m?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:f?a||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:Mi(r)})]}),(v||m)&&t.jsx("div",{className:"chat-markdown",children:m&&h?t.jsx(ur,{parts:h,renderAsPreformatted:M}):M?t.jsx("pre",{className:"chat-preformatted",children:N}):y?t.jsx(ua,{remarkPlugins:[ma,li,di],children:N}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:N})}),g]})})},(e,s)=>e.message===s.message&&e.receivedAt===s.receivedAt&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isTextExpanded===s.isTextExpanded),Yd=o.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},emptyState:f,onLoadMore:d,isLoadingMore:h,hasMoreHistory:m,hiddenLiveCount:k=0,loadError:S,scrollToBottomRequestNonce:p,isVisible:x=!0},v){const g=o.useRef(null),N=o.useRef(null),M=o.useRef(null),y=o.useRef(0),C=o.useRef(""),j=o.useRef(!1),w=o.useRef(null),b=o.useRef(!1),E=o.useRef(null),A=o.useRef(!1),[I,P]=o.useState(new Set),O=o.useRef(!1),V=o.useRef(!1),L=o.useRef(x),R=()=>{const U=g.current;return U?U.scrollHeight-U.scrollTop-U.clientHeight<200:!0},G=o.useCallback((U="auto")=>{const Q=g.current;Q&&Q.scrollTo({top:Q.scrollHeight,behavior:U})},[]),B=o.useCallback(()=>{var le;const U=g.current,Q=(le=window.getSelection)==null?void 0:le.call(window);if(!U||!Q||Q.rangeCount===0||Q.isCollapsed){A.current=!1;return}const de=Q.anchorNode,re=Q.focusNode;A.current=!!(de&&re&&U.contains(de)&&U.contains(re))},[]),$=Fd(s),H=o.useCallback(()=>{const U=g.current;!U||!l||un.set(l,{top:U.scrollTop,fromBottom:Math.max(0,U.scrollHeight-U.scrollTop-U.clientHeight),messageFingerprint:$})},[l,$]),J=o.useCallback((U="auto")=>{w.current!=null&&cancelAnimationFrame(w.current),w.current=requestAnimationFrame(()=>{w.current=null,G(U)})},[G]),xe=o.useCallback(()=>{O.current=!1,b.current=!0,V.current=!0,E.current!=null&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>{b.current=!1,E.current=null},180)},[]);o.useEffect(()=>{const U=!j.current,Q=C.current!==l;if(C.current=l,U||Q){if(j.current=!0,O.current=!1,b.current=!0,!A.current){const re=l?un.get(l):null;re&&io(re,$)?requestAnimationFrame(()=>{const le=g.current;le&&(co(le,re),V.current=!0)}):J("auto")}y.current=s.length;return}s.length>y.current?!O.current&&!A.current&&J("auto"):R()&&!O.current&&!A.current&&J("auto"),y.current=s.length},[$,l,c,s.length,J]),o.useEffect(()=>{p&&(xe(),A.current||J("auto"))},[xe,J,p]),o.useEffect(()=>{const U=L.current;L.current=x,Ud(U,x)&&(xe(),A.current||J("auto"))},[x,xe,J]),o.useEffect(()=>()=>{H(),w.current!=null&&cancelAnimationFrame(w.current),E.current!=null&&window.clearTimeout(E.current)},[H]),o.useEffect(()=>{const U=N.current;if(!U)return;const Q=()=>{E.current!=null&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>{b.current=!1,E.current=null},180)},de=new ResizeObserver(()=>{b.current&&(A.current||(J("auto"),Q()))});return de.observe(U),()=>{de.disconnect(),E.current!=null&&(window.clearTimeout(E.current),E.current=null)}},[J,l]),o.useImperativeHandle(v,()=>({scrollToBottom:(U="smooth")=>{G(U)}}),[G]),o.useEffect(()=>{const U=g.current;if(!U)return;let Q;const de=()=>{clearTimeout(Q),Q=setTimeout(()=>{O.current=!R(),H()},50)};return U.addEventListener("scroll",de,{passive:!0}),()=>{U.removeEventListener("scroll",de),clearTimeout(Q)}},[H]),o.useEffect(()=>(document.addEventListener("selectionchange",B),()=>document.removeEventListener("selectionchange",B)),[B]);const me=o.useRef(0),ce=o.useRef(!1);o.useEffect(()=>{const U=g.current;if(!U||!ce.current||me.current===0)return;const Q=U.scrollHeight-me.current;Q>0&&(U.scrollTop=Q),H(),me.current=0,ce.current=!1},[s.length,H]),o.useEffect(()=>{if(V.current||!l)return;const U=un.get(l),Q=g.current;if(!(!U||!Q)){if(!io(U,$)){G("auto"),V.current=!0;return}co(Q,U),V.current=!0}},[l,$,s.length,G]);const ge=()=>{const U=g.current;U&&(me.current=U.scrollHeight),ce.current=!0,d==null||d()},be=o.useMemo(()=>{const U=s.map((le,te)=>({type:"message",data:le,index:te,ts:zd(le,te,u)}));if(!r||r.length===0)return U;const Q=[...r].sort((le,te)=>le.timestamp-te.timestamp).map((le,te)=>({type:"action",data:le,index:te,ts:le.timestamp})),de=[];let re=0;for(const le of U){for(;re<Q.length&&le.ts>0&&Q[re].ts<le.ts;)de.push(Q[re++]);de.push(le)}for(;re<Q.length;)de.push(Q[re++]);return de},[s,r,u]),we=k>0||!!m,z=k>0?`↑ Show ${Math.min(k,80)} earlier messages${k>80?` (${k} hidden)`:""}`:S?`↻ ${S}`:"↑ Load older messages";return t.jsx("div",{ref:g,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:N,className:"chat-container-content",children:[h&&t.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),we&&!h&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:ge,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${S&&k===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:z})}),be.length===0&&!we&&(f||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),be.map(U=>{if(U.type==="action"){const ne=U.data;return t.jsx(Gd,{log:ne},`action-${U.index}`)}const Q=U.data,de=U.index,re=Kr(Q,de),le=Q.receivedAt||u[re],te=`${l}-${re}`,fe=I.has(te);return t.jsx(qd,{message:Q,receivedAt:le,agentName:n,userName:a,isCliMode:i,isTextExpanded:fe,onToggleTextExpanded:()=>P(ne=>{const ie=new Set(ne);return fe?ie.delete(te):ie.add(te),ie})},`msg-${re}`)}),c&&t.jsx("div",{className:"self-start chat-typing-wrapper",children:t.jsxs("div",{className:"typing-indicator",children:[t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),t.jsx("div",{className:"min-h-10",ref:M})]})})}),Xd=o.memo(Yd,(e,s)=>e.messages===s.messages&&e.actionLogs===s.actionLogs&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isWorking===s.isWorking&&e.contextKey===s.contextKey&&e.receivedAtMap===s.receivedAtMap&&e.emptyState===s.emptyState&&e.onLoadMore===s.onLoadMore&&e.isLoadingMore===s.isLoadingMore&&e.hasMoreHistory===s.hasMoreHistory&&e.hiddenLiveCount===s.hiddenLiveCount&&e.loadError===s.loadError&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isVisible===s.isVisible),Jd="modulepreload",Qd=function(e){return"/"+e},uo={},Zd=function(s,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=Promise.allSettled(r.map(u=>{if(u=Qd(u),u in uo)return;uo[u]=!0;const f=u.endsWith(".css"),d=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const h=document.createElement("link");if(h.rel=f?"stylesheet":Jd,f||(h.as="script"),h.crossOrigin="",h.href=u,l&&h.setAttribute("nonce",l),document.head.appendChild(h),f)return new Promise((m,k)=>{h.addEventListener("load",m),h.addEventListener("error",()=>k(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return s().catch(i)})};let mo=!1;const Ti=o.forwardRef(({onInput:e,onViewportMetrics:s,fontSize:r=13,readOnly:n=!1,sizingMode:a="measured"},i)=>{const c=o.useRef(null),[l,u]=o.useState(null),f=o.useRef([]),d=o.useRef(!1),h=o.useRef(!1),m=o.useRef(!1),k=()=>{const S=c.current;if(S){d.current&&(S.clear(),d.current=!1);for(const p of f.current)S.write(p);f.current=[],h.current&&(S.fit(),h.current=!1),m.current&&(S.bumpResize(),m.current=!1)}};return o.useImperativeHandle(i,()=>({write:S=>{c.current?c.current.write(S):f.current.push(S)},clear:()=>{c.current?c.current.clear():(f.current=[],d.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(f.current=[],d.current=!0)},resize:(S,p)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(S,p)},fit:()=>{c.current?c.current.fit():h.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():m.current=!0}}),[]),o.useEffect(()=>{l&&k()},[l]),o.useEffect(()=>{let S=!1;return Zd(()=>import("./terminal-Bv6gUGuY.js"),__vite__mapDeps([0,1,2])).then(p=>{mo||(mo=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),S||u(()=>p.GhosttyTerminalView)}).catch(p=>{console.error("[CliTerminal] failed to load terminal renderer",p)}),()=>{S=!0}},[]),l?t.jsx(l,{ref:c,onInput:e,onViewportMetrics:s,fontSize:r,readOnly:n,sizingMode:a,className:"w-full h-full rounded-lg overflow-hidden"}):t.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Ti.displayName="CliTerminal";function mr({label:e,value:s,sub:r,icon:n}){return t.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[t.jsx("span",{className:"text-base flex items-center",children:n}),t.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),t.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:s}),r&&t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function fo({value:e,max:s,label:r,color:n="#8b5cf6",detail:a,compact:i=!1}){const c=s>0?Math.min(Math.round(e/s*100),100):0,l=c>85?"#ef4444":c>60?"var(--status-warning)":n;return i?t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-0.5",children:[t.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),t.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[c,"%"]})]}),t.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${c}%`,background:l}})})]}):t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-1.5",children:[t.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),t.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[c,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${c}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),a&&t.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function eu({cursorPos:e,viewportRef:s,imgRef:r}){var g;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(g=s.current)==null?void 0:g.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,u=c/l,f=a.width/a.height;let d,h,m,k;u>f?(d=a.width,h=a.width/u,m=0,k=(a.height-h)/2):(h=a.height,d=a.height*u,m=(a.width-d)/2,k=0);const S=a.left-i.left+m+d*e.nx,p=a.top-i.top+k+h*e.ny,x=Math.max(8,Math.min(i.width-8,S)),v=Math.max(8,Math.min(i.height-8,p));return t.jsxs("div",{style:{position:"absolute",left:x-8,top:v-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[t.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),t.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),t.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 tu({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:f,zoom:d,isMobile:h,mobileFillZoom:m,onZoomOut:k,onZoomReset:S,onZoomIn:p,transportType:x,screenshotUsage:v,lastActionStatus:g}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:N=>N.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[t.jsxs("div",{onClick:s,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:[t.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),t.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),t.jsxs("div",{className:"relative",children:[t.jsx("div",{onClick:()=>{n(N=>!N),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&t.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:t.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:N=>N.stopPropagation(),onChange:N=>l(N.target.value),onKeyDown:N=>{u(N)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),t.jsx("div",{className:"relative",children:t.jsx("div",{onClick:()=>{i(N=>!N),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⚙️"})})}),t.jsx("div",{className:"w-px h-[18px] bg-white/10"}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:f?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[t.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:f?"#22c55e":"#eab308",boxShadow:f?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:f?"#22c55e":"#eab308"},children:f?"Connected":"WS"})]}),d>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),x==="direct"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),x==="relay"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),v&&v.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:v.budgetExhausted?"#ef4444":"#c4b5fd",background:v.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:v.budgetExhausted?"TURN blocked":`TURN ${v.dailyUsedMinutes}/${v.dailyBudgetMinutes}m`}),g&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:g})]})]}),a&&t.jsxs("div",{onTouchStart:N=>N.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[t.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",d<=(h?m:1)+.01?h?"FILL":"FIT":`${Math.round(d*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:N=>{N.stopPropagation(),k()},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:"−"}),t.jsx("button",{onClick:N=>{N.stopPropagation(),S()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:h?"FILL":"FIT"}),t.jsx("button",{onClick:N=>{N.stopPropagation(),p()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function su({waitingLabel:e,waitingHint:s,transportType:r}){return t.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[t.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:t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),t.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),t.jsx("div",{className:"text-[11px] text-white/40",children:s}),r==="relay"&&t.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function ru(){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 po(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 tr(e,s){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!ru())return;n.current+=1;const a=r.current;if(!a){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(s).map(([c,l])=>[c,po(l)]))}),r.current=s;return}const i=Object.keys({...a,...s}).filter(c=>!Object.is(a[c],s[c]));i.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(c=>[c,po(s[c])]))}),r.current=s})}function nu({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:f,setPanY:d,setZoom:h,lastWheelTimeRef:m,onAction:k,setLastActionStatus:S,spawnRippleFromNormalized:p,clampPan:x,isMobile:v,mobileFillZoom:g}){const[N,M]=o.useState(null),y=o.useRef(null),C=o.useRef(null),j=o.useRef(null),w=o.useRef(!1),b=o.useRef(null),E=o.useRef(0),A=o.useRef(null),I=o.useRef(1),P=o.useRef({x:0,y:0}),O=o.useRef(!1),V=o.useRef(n),L=o.useRef(k),R=30,G=550,B=18,$=60,H=400,J=12,xe=()=>{if(y.current)return;const ge={nx:.5,ny:.5};y.current=ge,M(ge)};return o.useEffect(()=>{V.current=n,n==="mouse"&&xe()},[n]),o.useEffect(()=>{L.current=k},[k]),o.useEffect(()=>{const ge=e.current;if(!ge)return;const be=re=>{if(!r.current)return null;const le=r.current.getBoundingClientRect();return!le.width||!le.height?null:{nx:Math.max(0,Math.min(1,(re.clientX-le.left)/le.width)),ny:Math.max(0,Math.min(1,(re.clientY-le.top)/le.height))}},we=(re,le)=>{if(!r.current)return{dnx:0,dny:0};const te=r.current,fe=te.getBoundingClientRect(),ne=te.naturalWidth||fe.width,ie=te.naturalHeight||fe.height,ae=ne/ie,ye=fe.width/fe.height;let he,Se;return ae>ye?(he=fe.width,Se=fe.width/ae):(Se=fe.height,he=fe.height*ae),{dnx:re/he,dny:le/Se}},z=(re,le,te)=>{if(te<=1.05)return;const fe=-(re-.5)*100,ne=-(le-.5)*100,ie=x(fe,ne,te);(Math.abs(ie.x-l.current)>.1||Math.abs(ie.y-u.current)>.1)&&(f(ie.x),d(ie.y),l.current=ie.x,u.current=ie.y)},U=re=>{const le=s.current;if(le&&re.target instanceof Node&&le.contains(re.target))re.preventDefault();else return;if(re.touches.length===1){const te=re.touches[0];C.current={x:te.clientX,y:te.clientY,time:Date.now()},j.current={x:te.clientX,y:te.clientY},O.current||(w.current=!1),b.current=setTimeout(()=>{if(!w.current&&!O.current)if(w.current=!0,V.current==="mouse"){const fe=y.current||{nx:.5,ny:.5};S("Right Click"),p(fe.nx,fe.ny,"right"),L.current("input_click",{...fe,button:"right"}).catch(()=>{})}else{const fe=be(te);fe&&(S("Right Click"),p(fe.nx,fe.ny,"right"),L.current("input_click",{...fe,button:"right"}).catch(()=>{}))}},500);return}if(re.touches.length===2){b.current&&clearTimeout(b.current),w.current=!0,O.current=!0;const te=re.touches[1].clientX-re.touches[0].clientX,fe=re.touches[1].clientY-re.touches[0].clientY;A.current=Math.sqrt(te*te+fe*fe),I.current=c.current,P.current={x:(re.touches[0].clientX+re.touches[1].clientX)/2,y:(re.touches[0].clientY+re.touches[1].clientY)/2}}},Q=re=>{const le=s.current;if(le&&re.target instanceof Node&&le.contains(re.target)&&re.preventDefault(),re.touches.length===1&&j.current){const te=re.touches[0],fe=te.clientX-j.current.x,ne=te.clientY-j.current.y;if(!w.current&&C.current){const ie=te.clientX-C.current.x,ae=te.clientY-C.current.y;Math.sqrt(ie*ie+ae*ae)>8&&(w.current=!0,b.current&&clearTimeout(b.current))}if(w.current)if(V.current==="mouse"){const ie=we(fe,ne),ae=y.current||{nx:.5,ny:.5},ye=Math.max(0,Math.min(1,ae.nx+ie.dnx)),he=Math.max(0,Math.min(1,ae.ny+ie.dny));y.current={nx:ye,ny:he},M({nx:ye,ny:he}),S(`Cursor: ${Math.round(ye*100)}%, ${Math.round(he*100)}%`),z(ye,he,c.current);const Se=Date.now();Se-m.current>=30&&(m.current=Se,L.current("input_mouseMoved",{nx:ye,ny:he}).catch(()=>{}))}else if(c.current>1){const ie=s.current;if(ie){const ae=ie.clientWidth,ye=ie.clientHeight,he=l.current+fe/ae*100,Se=u.current+ne/ye*100,T=x(he,Se,c.current);f(T.x),d(T.y),l.current=T.x,u.current=T.y}}else{const ie=be(te);if(ie){const ae=Date.now();ae-m.current>=40&&(m.current=ae,S("Scroll"),L.current("input_wheel",{nx:ie.nx,ny:ie.ny,deltaX:Math.round(-fe*2.5),deltaY:Math.round(-ne*2.5)}).catch(()=>{}))}}j.current={x:te.clientX,y:te.clientY};return}if(re.touches.length===2&&A.current!==null){const te=re.touches[1].clientX-re.touches[0].clientX,fe=re.touches[1].clientY-re.touches[0].clientY,ie=Math.sqrt(te*te+fe*fe)/A.current,ae=(re.touches[0].clientX+re.touches[1].clientX)/2,ye=(re.touches[0].clientY+re.touches[1].clientY)/2,he=ae-P.current.x,Se=ye-P.current.y,T=Math.abs(ie-1)>.03;if(V.current==="mouse"){if(T){const D=Math.max(i,Math.min(5,I.current*ie));h(D),c.current=D}else if(Math.abs(he)>2||Math.abs(Se)>2){const D=y.current||{nx:.5,ny:.5},Y=Date.now();Y-m.current>=30&&(m.current=Y,S("Scroll"),L.current("input_wheel",{nx:D.nx,ny:D.ny,deltaX:Math.round(-he*3),deltaY:Math.round(-Se*3)}).catch(()=>{}))}}else{const D=Math.max(i,Math.min(5,I.current*ie));h(D),c.current=D;const Y=s.current;if(Y&&D>1){const X=Y.clientWidth,pe=Y.clientHeight,Ie=l.current+he/X*100,Ne=u.current+Se/pe*100,Be=x(Ie,Ne,D);f(Be.x),d(Be.y),l.current=Be.x,u.current=Be.y}}P.current={x:ae,y:ye}}},de=re=>{var le;if(b.current&&clearTimeout(b.current),A.current=null,re.touches.length===1&&O.current){const te=re.touches[0];C.current={x:te.clientX,y:te.clientY,time:Date.now()},j.current={x:te.clientX,y:te.clientY},w.current=!0;return}if(re.touches.length===0){if(O.current){O.current=!1,w.current=!1;return}if(re.changedTouches.length===1){const te=re.changedTouches[0],fe=Date.now(),ne=fe-(((le=C.current)==null?void 0:le.time)||0),ie=C.current?te.clientX-C.current.x:0,ae=C.current?te.clientY-C.current.y:0,ye=Math.sqrt(ie*ie+ae*ae);if(V.current==="mouse"){if(ne<R||ne>G||ye>B){w.current=!1;return}const he=y.current||be(te);he&&(S(`Click: ${Math.round(he.nx*100)}%, ${Math.round(he.ny*100)}%`),p(he.nx,he.ny,"left"),L.current("input_click",{...he}).catch(()=>{}))}else{if(w.current){w.current=!1;return}if(ne<$||ne>H||ye>J){w.current=!1;return}const he=be(te);if(!he)return;fe-E.current<300?(S("Double tap"),p(he.nx,he.ny,"double"),L.current("input_click",{...he,clickCount:2}).catch(()=>{}),E.current=0):(S(`Tap: ${Math.round(he.nx*100)}%, ${Math.round(he.ny*100)}%`),p(he.nx,he.ny,"left"),L.current("input_click",{...he}).catch(()=>{}),E.current=fe)}}w.current=!1}};return ge.addEventListener("touchstart",U,{passive:!1}),ge.addEventListener("touchmove",Q,{passive:!1}),ge.addEventListener("touchend",de,{passive:!1}),()=>{ge.removeEventListener("touchstart",U),ge.removeEventListener("touchmove",Q),ge.removeEventListener("touchend",de),b.current&&clearTimeout(b.current)}},[e,s,r,i,c,l,u,f,d,h,m,S,p,x]),{cursorPos:N,cursorPosRef:y,handleToggleInputMode:()=>{a(ge=>{const be=ge==="touch"?"mouse":"touch";return be==="mouse"&&xe(),be})},handleZoomReset:()=>{const ge=v?g:1;h(ge),c.current=ge,f(0),d(0),l.current=0,u.current=0}}}function Li({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),u=o.useRef(null),[f,d]=o.useState(null),[h,m]=o.useState(""),[,k]=o.useState(!1),[S,p]=o.useState([]),x=o.useRef(0),[v,g]=o.useState(!1),[N,M]=o.useState(!1),y=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[C,j]=o.useState(y?"mouse":"touch"),[w,b]=o.useState(1),E=o.useRef(!1),[A,I]=o.useState(1),[P,O]=o.useState(0),[V,L]=o.useState(0);tr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:C,zoom:A,panX:P,panY:V,isMenuOpen:v,isImeOpen:N});const R=o.useRef(0),G=o.useRef(A),B=o.useRef(P),$=o.useRef(V);o.useEffect(()=>{G.current=A},[A]),o.useEffect(()=>{B.current=P},[P]),o.useEffect(()=>{$.current=V},[V]),o.useEffect(()=>{var ne;(ne=c.current)==null||ne.focus()},[]);const H=r==="connected",J=n,xe=H?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",me=H?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!y||E.current||!J)return;const ne=u.current,ie=l.current;if(!ne||!ie)return;const ae=()=>{const ye=ie.clientWidth,he=ie.clientHeight,Se=ne.naturalWidth,T=ne.naturalHeight;if(!Se||!T||!ye||!he)return;const D=Math.min(ye/Se,he/T),X=Math.max(ye/Se,he/T)/D;X>1.01&&(b(X),I(X),G.current=X),E.current=!0};ne.complete&&ne.naturalWidth?ae():ne.addEventListener("load",ae,{once:!0})},[J,y]);const ce=.5;o.useEffect(()=>{A<=ce&&(O(0),L(0))},[A,ce]);const ge=(ne,ie,ae)=>{if(ae<=ce)return{x:0,y:0};const ye=(ae-1)/(2*ae)*100,he=(ae-1)/(2*ae)*100;return{x:Math.max(-ye,Math.min(ye,ne)),y:Math.max(-he,Math.min(he,ie))}},be=(ne,ie)=>{if(!u.current)return null;const ae=u.current.getBoundingClientRect();return!ae.width||!ae.height?null:{nx:Math.max(0,Math.min(1,(ne-ae.left)/ae.width)),ny:Math.max(0,Math.min(1,(ie-ae.top)/ae.height))}},we=(ne,ie,ae)=>{const ye=l.current;if(!ye)return;const he=ye.getBoundingClientRect(),Se=++x.current;p(T=>[...T,{id:Se,x:ne-he.left,y:ie-he.top,type:ae}]),setTimeout(()=>p(T=>T.filter(D=>D.id!==Se)),600)},z=(ne,ie,ae)=>{const ye=u.current,he=l.current;if(!ye||!he)return;const Se=ye.getBoundingClientRect(),T=he.getBoundingClientRect(),D=ye.naturalWidth||Se.width,Y=ye.naturalHeight||Se.height,X=D/Y,pe=Se.width/Se.height;let Ie,Ne,Be,He;X>pe?(Ie=Se.width,Ne=Se.width/X,Be=0,He=(Se.height-Ne)/2):(Ne=Se.height,Ie=Se.height*X,Be=(Se.width-Ie)/2,He=0);const Ue=Se.left-T.left+Be+Ie*ne,Qe=Se.top-T.top+He+Ne*ie,tt=++x.current;p(ct=>[...ct,{id:tt,x:Ue,y:Qe,type:ae}]),setTimeout(()=>p(ct=>ct.filter(ut=>ut.id!==tt)),600)},U=async ne=>{var ae;const ie=be(ne.clientX,ne.clientY);if(ie){d(`Click: ${Math.round(ie.nx*100)}%, ${Math.round(ie.ny*100)}%`),we(ne.clientX,ne.clientY,"left"),(ae=c.current)==null||ae.focus();try{const ye=await e("input_click",{nx:ie.nx,ny:ie.ny});ye!=null&&ye.success||s(`❌ Click failed: ${ye==null?void 0:ye.error}`)}catch(ye){s(`❌ Click error: ${ye.message||ye}`)}}},Q=async(ne,ie,ae,ye=0)=>{try{await e("input_key",{type:ae?"char":"keyDown",key:ne,code:ie,text:ae?ne:void 0,unmodifiedText:ae?ne:void 0,modifiers:ye})}catch(he){s(`❌ Key error: ${he.message||he}`)}},de=async ne=>{if(ne.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ne.key)&&ne.preventDefault();let ae=0;ne.altKey&&(ae|=1),ne.ctrlKey&&(ae|=2),ne.metaKey&&(ae|=4),ne.shiftKey&&(ae|=8),d(`Key: ${ne.key}`),await Q(ne.key,ne.code,ne.key.length===1,ae)},re=async ne=>{if(ne.key==="Enter"){if(ne.nativeEvent.isComposing)return;if(h){const ie=h;m(""),d(`IME Sent: ${ie}`);try{const ae=await e("input_type",{text:ie});ae!=null&&ae.success||s(`❌ IME error: ${ae==null?void 0:ae.error}`)}catch(ae){s(`❌ IME error: ${ae.message}`)}}else d("Key: Enter"),await Q("Enter","Enter",!1)}};o.useEffect(()=>{const ne=c.current;if(!ne)return;const ie=ae=>{var ye;if((ye=u.current)!=null&&ye.contains(ae.target)){ae.preventDefault();const he=Date.now();if(he-R.current<40)return;R.current=he;const Se=be(ae.clientX,ae.clientY);if(!Se)return;d(`Scroll: ${Math.round(ae.deltaY)}`),e("input_wheel",{nx:Se.nx,ny:Se.ny,deltaX:Math.round(ae.deltaX),deltaY:Math.round(ae.deltaY)}).catch(()=>{})}};return ne.addEventListener("wheel",ie,{passive:!1}),()=>ne.removeEventListener("wheel",ie)},[e]);const{cursorPos:le,handleToggleInputMode:te,handleZoomReset:fe}=nu({containerRef:c,viewportRef:l,imgRef:u,inputMode:C,setInputMode:j,minZoom:ce,zoomRef:G,panXRef:B,panYRef:$,setPanX:O,setPanY:L,setZoom:I,lastWheelTimeRef:R,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:z,clampPan:ge,isMobile:y,mobileFillZoom:w});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:de,onContextMenu:ne=>ne.preventDefault(),onFocus:()=>k(!0),onBlur:()=>k(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[J?t.jsx("img",{ref:u,src:J,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${A}) translate(${P}%, ${V}%)`,transformOrigin:"center center",cursor:C==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:U,onContextMenu:ne=>ne.preventDefault(),onDragStart:ne=>ne.preventDefault()}):t.jsx(su,{waitingLabel:xe,waitingHint:me,transportType:i}),C==="mouse"&&J&&t.jsx(eu,{cursorPos:le,viewportRef:l,imgRef:u}),S.map(ne=>{const ae={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ne.type];return t.jsxs("div",{style:{position:"absolute",left:ne.x,top:ne.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ae}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),t.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${ae}, 0.9)`,boxShadow:`0 0 12px rgba(${ae}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ne.id)})]}),t.jsx(tu,{inputMode:C,onToggleInputMode:te,isImeOpen:N,setIsImeOpen:M,isMenuOpen:v,setIsMenuOpen:g,imeText:h,setImeText:m,handleImeSubmit:re,isConnActive:H,zoom:A,isMobile:y,mobileFillZoom:w,onZoomOut:()=>I(ne=>Math.max(.5,ne-.25)),onZoomReset:fe,onZoomIn:()=>I(ne=>Math.min(5,ne+.25)),transportType:i,screenshotUsage:a,lastActionStatus:f}),t.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 Jr(e,s={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=s,i=Date.now()-e,c=Math.floor(i/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const u=Math.floor(l/60);if(u<24)return`${u}h${r}`;const f=Math.floor(u/24);return f<7?`${f}d${r}`:new Date(e).toLocaleDateString()}const Ri=e=>Jr(e);function au(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function As(e){const s=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:a}}function ou(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...au(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 s}function Or(e,s){if(e.sessionId){const r=s.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 Qr(e,s,r){const n=Or(e,s),a=As(e),i=a.isReconnecting,c=a.isConnecting,l=a.isGenerating,u=a.isWaiting,f=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||u,d=n.inboxBucket==="working"||l,m=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:m,requiresAction:f,isWorking:d,isReconnecting:i,isConnecting:c,isGenerating:l,isWaiting:u,inboxBucket:f?"needs_attention":d?"working":m?"task_complete":"idle"}}function iu(e,s,r){return Qr(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Pi({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!As(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),s(l))},c=l=>l.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return t.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&&t.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)}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[t.jsx(qs,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,u)=>{const f=c(l).toLowerCase(),d=/^(run|approve|accept|yes|allow|always)/.test(f),h=/^(reject|deny|delete|remove|abort)/.test(f),m=r===l,k=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:k,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${d?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${k&&!m?"opacity-40":"opacity-100"} ${k?"cursor-not-allowed":"cursor-pointer"}`,style:d?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:h?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:m?"⏳ ...":c(l)},u)})})]})]})}const ya="adhdev_controls_bar_visible",Yn="adhdev:controlsbarvisibilitychange";function fn(e){if(!e)return!1;try{return e.getItem(ya)==="1"}catch{return!1}}function ho(e,s){if(s)try{s.setItem(ya,e?"1":"0")}catch{}}function xo(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Yn,{detail:{visible:e}}))}function _i(){const[e,s]=o.useState(()=>typeof window>"u"?!1:fn(window.localStorage));o.useEffect(()=>{const a=c=>{const l=c.detail;if(typeof(l==null?void 0:l.visible)=="boolean"){s(l.visible);return}s(fn(window.localStorage))},i=c=>{c.key===ya&&s(fn(window.localStorage))};return window.addEventListener(Yn,a),window.addEventListener("storage",i),()=>{window.removeEventListener(Yn,a),window.removeEventListener("storage",i)}},[]);const r=o.useCallback(a=>{s(a),typeof window<"u"&&ho(a,window.localStorage),xo(a)},[]),n=o.useCallback(()=>{s(a=>{const i=!a;return typeof window<"u"&&ho(i,window.localStorage),xo(i),i})},[]);return{isVisible:e,setVisibility:r,toggleVisibility:n}}var cu=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function lu(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function bt(e,s){if(lu(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":cu.has(r)?"generating":r==="error"?"error":r==="stopped"?"stopped":r==="starting"?"starting":r==="panel_hidden"?"panel_hidden":r==="not_monitored"?"not_monitored":r==="disconnected"?"disconnected":"idle"}function Di(e){return bt(e)==="generating"}function et(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function du(e){if(e<60)return`${Math.round(e)}s`;const s=Math.floor(e/60);if(s<60)return`${s}m`;const r=Math.floor(s/60),n=s%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 pn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Zr(e,s){const r=typeof s=="string"?s.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 uu(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const s=e.split("_"),r=s[s.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function mu(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function fu(e){return uu(e.trim().replace(/\.local$/i,""))}function pu(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function Ei(e,s={}){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&&!mu(c));if(r&&r!=="Unknown")return fu(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function At(e,s={}){return pu(e)||Ei(e,s)}function $i(e){return!e||!Array.isArray(e.items)?[]:e.items.map(s=>String((s==null?void 0:s.value)||(s==null?void 0:s.shortValue)||"").trim()).filter(Boolean)}function Bi(e,s,r={}){const n=String(s).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 ds(e,s){return $i(e).join(" · ")}function Xs(e){return e.transport==="pty"}function ys(e){return e.transport==="acp"}function hu(e,s){var r,n;return(r=s==null?void 0:s.providerLabels)!=null&&r[e]?s.providerLabels[e]:(n=s==null?void 0:s.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?s.providerLabels[e.toLowerCase()]:s!=null&&s.agentName&&s.agentName!==e?s.agentName:et(e)}function bo(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=et(r||"").trim().toLowerCase();return n===a||n===i||n===c}function xu(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function bu(e){if(!Array.isArray(e)||e.length<=1)return e;const s=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=s.get(a),c=bt(n.status);if(!i){s.set(a,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),u=r.indexOf(c||"idle");u>=0&&(l<0||u<l)&&s.set(a,{...n,status:c})}return Array.from(s.values())}function gu(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function yu(e){var r,n;const s=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return s&&gu(s.receivedAt)||0}function vu(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Xn(e){return Math.max(vu(e),yu(e.activeChat))}function wu(e,s,r,n,a,i){const c=s-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(i)}function va(e,s){return wu(Xn(e),Xn(s),At(e,{fallbackId:e.id}),At(s,{fallbackId:s.id}),e.id,s.id)}const Ki="adhdev_notification_prefs",go={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function ju(){try{const e=localStorage.getItem(Ki);if(e){const s=JSON.parse(e);return{...go,...s}}}catch{}return{...go}}function ku(e){try{localStorage.setItem(Ki,JSON.stringify(e))}catch{}}let Wt=ju(),Ar=[];function Su(){Ar.forEach(e=>e())}function Nu(e){Wt={...Wt,...e},ku(Wt),Su()}function Cu(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Ar.push(r),()=>{Ar=Ar.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{Nu(r)},[]);return[{...Wt},s]}function Os(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 Iu={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Oi(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Wi(){return"Notification"in window&&Notification.permission==="granted"}let Xt=null;async function Mu(){if(Xt!==null)return Xt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Xt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Xt=!!await e.pushManager.getSubscription(),Xt):(Xt=!1,!1)}catch{return Xt=!1,!1}}function Jn(e,s,r){if(Wi())try{const n=new Notification(e,{body:s,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function Au(e,s={}){const r={...Iu,...s},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{Mu().then(l=>{i.current=l})},[]);const c=o.useCallback((l,u,f)=>{const d=Date.now();d-a.current<r.throttleMs||(a.current=d,Jn(l,u,f))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!Wi())&&Os("browser")&&i.current!==!0){if(document.hasFocus()){for(const u of e)n.current.set(u.id,bt(u.status,{activeModal:u.activeModal}));return}for(const u of e){const f=n.current.get(u.id),d=bt(u.status,{activeModal:u.activeModal}),h=u.name||u.id;if(r.onApproval&&Os("approval")&&d==="waiting_approval"&&f!=="waiting_approval"){const m=((l=u.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,m.slice(0,120),`approval-${u.id}`)}r.onComplete&&Os("completion")&&Di(f)&&d==="idle"&&c(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${u.id}`),r.onError&&d==="error"&&f!=="error"&&c(`⚠️ ${h} — Error`,"Agent encountered an error",`error-${u.id}`),n.current.set(u.id,d)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const Tu=/^(run|approve|accept|yes|allow|always)/,Lu=/^(run|approve|accept|yes|allow|always|proceed|save)/,Ru=/^(reject|deny|delete|remove|abort|cancel|no)/;function wa(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Pu(e){const s=wa(e).toLowerCase();return Tu.test(s)?"primary":Ru.test(s)?"danger":"default"}function _u(e){return Lu.test(wa(e).toLowerCase())?"approve":"reject"}function Du(e){return e.map((s,r)=>({label:wa(s),variant:Pu(s),action:_u(s),button:s,buttonIndex:r}))}function Eu(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function $u(e,s,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,s,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,s,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class Bu{constructor(){Ge(this,"dedupMap",new Map);Ge(this,"DEDUP_WINDOW_MS",5e3);Ge(this,"DEDUP_MAX_SIZE",50);Ge(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ge(this,"toastCallbacks",[]);Ge(this,"resolveActionFn",null);Ge(this,"viewRequestRespondFn",null);Ge(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:s,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(s){const r=Date.now(),n=this.dedupMap.get(s)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(s,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(s){if(s.daemonId){const a=this.ides.find(i=>i.id===s.daemonId&&i.type==="adhdev-daemon");if(a)return a}const r=s.targetSessionId&&this.findOwningSession(s.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(s){for(const r of this.ides)if(r.id===s||r.sessionId===s||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===s))return r;return null}resolveActionRouteTarget(s){if(s.targetSessionId){const r=this.findOwningSession(s.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return s.daemonId||null}resolveConversationKey(s){return s.targetSessionId?s.targetSessionId:s.daemonId?s.daemonId:null}handleRawEvent(s,r){var S;const n=this.resolveConversationKey(s),a=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now(),i=n||s.daemonId||"",c=s.requestId||s.targetName||s.requesterName||s.modalMessage||String(a),l=`${i}:${s.event}:${c}`;if(this.isDuplicate(l))return;const u=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,f=(u==null?void 0:u.type)||"";let d=et(f);const h=this.resolveOwningDaemon(s);if(h){const p=At(h,{fallbackId:h.id});p&&(d=!f||f==="adhdev-daemon"?p:`${p}/${d}`)}let m="",k="info";if(s.event==="agent:generating_completed"){const p=s.duration?` (${s.duration}s)`:"";m=`✅ ${d} agent task completed${p}`,k="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(s.event!=="agent:generating_started")if(s.event==="agent:waiting_approval"){if(m=`⚡ ${d} approval needed`,k="warning",(S=s.modalButtons)!=null&&S.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(s);if(!p)return;const x=this.resolveActionFn,v=Du(s.modalButtons).map(M=>({label:M.label,variant:M.variant,onClick:()=>{x(p,"resolve_action",{action:M.action,button:M.button,buttonIndex:M.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),g=Eu(d,s.modalMessage,m),N=Date.now();this.emitToast({id:N,message:g,type:k,timestamp:N,targetKey:n||p,actions:v,duration:15e3}),m=""}}else if(s.event==="monitor:long_generating"){const p=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";m=`⚠️ ${d} agent is taking a long time${p}`,k="warning",Os("browser")&&!document.hasFocus()&&Jn(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const p=s.requesterName||"A team member",x=s.requestId,v=s.orgId;if(m=`👁️ ${p} wants to view your session`,k="warning",x&&v&&this.viewRequestRespondFn){const g=Date.now(),N=$u(v,x,this.viewRequestRespondFn,(M,y)=>console.error(`[EventManager] ${M} view request failed:`,y));this.emitToast({id:g,message:m,type:k,timestamp:g,actions:N,duration:3e4}),m=""}Os("browser")&&!document.hasFocus()&&Jn("👁️ View Request",`${p} wants to view your session`,`view-request-${x}`)}else s.event==="team:view_request_approved"?(m="✅ View request approved",k="success"):s.event==="team:view_request_rejected"&&(m=`❌ ${s.targetName||"Team member"} declined your view request`,k="warning");if(m){const p=Date.now();this.emitToast({id:p,message:m,type:k,timestamp:p,targetKey:n||s.daemonId,duration:5e3})}}}const dt=new Bu,yo=new Map;function Wr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function vs(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function en(e){return Wr(e)?Wr(e.result)?e.result:e:null}function Ku(e){const s=en(e);return!s||!Wr(s.controlResult)||!Array.isArray(s.controlResult.options)?null:s.controlResult}function fr(e){const s=en(e);return!s||!Wr(s.controlResult)||typeof s.controlResult.ok!="boolean"?null:s.controlResult}function Ls(e){const s=en(e);if(!(!s||typeof s.error!="string"||!s.error.trim()))return s.error}function pr(e){const s=en(e);return!!s&&s.success===!1}function Ou(e){var s,r;for(const n of e||[]){if(n.type==="toast"&&((s=n.toast)!=null&&s.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";dt.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";dt.showToast(n.notification.body,a)}}}function Wu(e,s){return e&&vs(e.currentValue)?e.currentValue:s}function Hu(e,s){return vs(s)?vs(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Fu(e,s){var i,c;if((s.now??Date.now())<s.localOverrideUntil){const l=s.localValues[e];if(vs(l))return l}const n=(i=s.controlValues)==null?void 0:i[e];if(vs(n))return n;const a=(c=s.defaultValues)==null?void 0:c[e];return vs(a)?a:void 0}function Tr(e,s){return e.options||s[e.id]||[]}const Uu={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 zu(e,s,r){var n;return((n=Uu[s])==null?void 0:n.has(r.id))===!0}function ja(e,s){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!zu(s.hostIdeType,s.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function hn(e,s){return{value:s}}function Vu(e,s,r){var a;return r?((a=Tr(e,s).find(i=>i.value===r))==null?void 0:a.label)||r:""}const Gu={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function qu({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=jt(),u=`${e}:${s||n}`,f=Gu[n]||"#94a3b8",[d,h]=o.useState({}),m=o.useRef({}),k=o.useRef(c);m.current=d,k.current=c;const S=o.useRef(0),p={};for(const R of i||[])R.defaultValue!==void 0&&(p[R.id]=R.defaultValue);const x={...p,...c||{},...Date.now()<S.current?d:{}};o.useEffect(()=>{c&&Date.now()>S.current&&h({})},[c]);const[v,g]=o.useState(yo.get(u)||{}),[N,M]=o.useState(null),[y,C]=o.useState(null),j=o.useCallback(async(R,G={})=>{const B={...G,...s&&{targetSessionId:s}};return await l(e,R,B)},[e,s,l]),w=o.useCallback(async(R,G={})=>{const B=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await j("invoke_provider_script",{...B,scriptName:R,...G})},[j,n,r,s]),b=o.useCallback((R,G,B)=>{const $=Wu(B,G);h(H=>({...H,[R.id]:$})),Ou(B==null?void 0:B.effects)},[]),E=o.useCallback((R,G)=>{h(B=>{const $={...B};return G===void 0?delete $[R.id]:$[R.id]=G,$}),S.current=0},[]);if(!i||i.length===0)return null;const A=ja(i,{hostIdeType:r,providerType:n});if(A.length===0)return null;const I=async R=>{if(N===R.id){M(null);return}if(Tr(R,v).length>0){M(R.id);return}if(R.dynamic&&R.listScript){C(R.id);try{const B=await w(R.listScript,{}),$=Ku(B);if(!$){const xe=Ls(B);xe&&dt.showToast(xe,"warning");return}const H=$.options;g(xe=>{const me={...xe,[R.id]:H};return yo.set(u,me),me});const J=Fu(R.id,{localOverrideUntil:S.current,localValues:m.current,controlValues:k.current,defaultValues:p});if(Hu(J,$.currentValue)){const xe=$.currentValue;h(me=>({...me,[R.id]:xe}))}M(R.id)}catch(B){const $=B instanceof Error?B.message:`Could not load ${R.label}`;dt.showToast($,"warning")}finally{C(null)}}},P=async(R,G)=>{M(null);const B=(c==null?void 0:c[R.id])??p[R.id];h($=>({...$,[R.id]:G})),S.current=Date.now()+5e3;try{if(!R.setScript)return;const $=await w(R.setScript,hn(R,G)),H=fr($);if(H&&!H.ok||pr($))throw new Error((H==null?void 0:H.error)||Ls($)||`Could not update ${R.label}`);b(R,G,H)}catch($){E(R,B);const H=$ instanceof Error?$.message:`Could not update ${R.label}`;dt.showToast(H,"warning")}},O=async R=>{const G=Tr(R,v).map(me=>me.value);if(G.length===0)return;const B=String(x[R.id]||""),H=(G.indexOf(B)+1)%G.length,J=G[H];if(typeof J!="string")return;const xe=(c==null?void 0:c[R.id])??p[R.id];h(me=>({...me,[R.id]:J})),S.current=Date.now()+5e3;try{if(!R.setScript)return;const me=await w(R.setScript,hn(R,J)),ce=fr(me);if(ce&&!ce.ok||pr(me))throw new Error((ce==null?void 0:ce.error)||Ls(me)||`Could not update ${R.label}`);b(R,J,ce)}catch(me){E(R,xe);const ce=me instanceof Error?me.message:`Could not update ${R.label}`;dt.showToast(ce,"warning")}},V=async R=>{const B=!x[R.id],$=(c==null?void 0:c[R.id])??p[R.id];h(H=>({...H,[R.id]:B})),S.current=Date.now()+5e3;try{if(!R.setScript)return;const H=await w(R.setScript,hn(R,B)),J=fr(H);if(J&&!J.ok||pr(H))throw new Error((J==null?void 0:J.error)||Ls(H)||`Could not update ${R.label}`);b(R,B,J)}catch(H){E(R,$);const J=H instanceof Error?H.message:`Could not update ${R.label}`;dt.showToast(J,"warning")}},L=async R=>{if(!R.invokeScript)return;if(R.confirmMessage){const B=[R.confirmTitle,R.confirmMessage,R.confirmLabel].filter(H=>typeof H=="string"&&H.trim().length>0);if(!window.confirm(B.join(`
|
|
28
|
+
|
|
29
|
+
`)))return}const G=(c==null?void 0:c[R.id])??p[R.id];try{const B=await w(R.invokeScript),$=fr(B);if($&&!$.ok||pr(B))throw new Error(($==null?void 0:$.error)||Ls(B)||`Could not run ${R.label}`);$&&b(R,G??!0,$)}catch(B){E(R,G);const $=B instanceof Error?B.message:`Could not run ${R.label}`;dt.showToast($,"warning")}};return t.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${f}33`,background:`${f}12`,color:f},children:a}),A.map(R=>{const G=String(x[R.id]||""),B=Vu(R,v,G),$=N===R.id,H=y===R.id,J=Tr(R,v),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(R.type){case"select":return t.jsxs("div",{className:"relative max-w-full",children:[t.jsxs("button",{type:"button",className:`${xe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:$?`${f}55`:"var(--border-default)",background:$?`${f}10`:"var(--surface-tertiary)",color:G?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void I(R),title:R.label,children:[R.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:H?"Loading…":B||R.label}),t.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),$&&J.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>M(null)}),t.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:[t.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:R.label}),J.map(me=>t.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:me.value===G?`${f}14`:"transparent",color:me.value===G?"var(--text-primary)":"var(--text-secondary)",borderLeft:me.value===G?`2px solid ${f}`:"2px solid transparent"},title:me.description||me.label,onMouseEnter:ce=>{ce.currentTarget.style.background=`${f}10`},onMouseLeave:ce=>{ce.currentTarget.style.background=me.value===G?`${f}14`:"transparent"},onClick:()=>void P(R,me.value),children:[t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:me.label}),me.value===G&&t.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:f},children:"✓"})]},me.value))]})]})]},R.id);case"cycle":return t.jsxs("button",{type:"button",className:`${xe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:G?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void O(R),title:`Click to cycle: ${J.map(me=>me.label).join(" → ")}`,children:[R.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:B||R.label}),t.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},R.id);case"toggle":return t.jsxs("button",{type:"button",className:`${xe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:G?`${f}44`:"var(--border-default)",background:G?`${f}14`:"var(--surface-tertiary)",color:G?f:"var(--text-muted)"},onClick:()=>void V(R),"aria-pressed":!!G,children:[R.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),R.label]},R.id);case"action":return t.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 L(R),children:[R.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:R.resultDisplay==="inline"&&G?`${R.label}: ${G}`:R.label})]},R.id);case"display":return t.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:G?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:G?`${R.label}: ${G}`:R.label})]},R.id);default:return null}})]})})}function Yu({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:f}=_i(),d=ja(l,{hostIdeType:a,providerType:i});return!e||s||d.length===0||!f?null:t.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:t.jsx(qu,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:d,controlValues:u})})}function Xu({hasDraft:e,isBusy:s=!1}){return!e||s}const Hi=o.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1,animateVisibility:f=!0}){const d=o.useRef(null),[h,m]=o.useState(""),{isVisible:k,toggleVisibility:S}=_i();o.useEffect(()=>{m("")},[s]),o.useEffect(()=>{var x;l&&((x=d.current)==null||x.focus({preventScroll:!0}))},[s,l]);const p=async()=>{const x=h.trim();if(!x||a)return;await c(x)!==!1&&m("")};return t.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",f?"transition-all duration-200 ease-out":""].filter(Boolean).join(" "),style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[t.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[u&&t.jsx("button",{type:"button",onClick:S,"aria-label":k?"Hide controls":"Show controls","aria-pressed":k,title:k?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:t.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[t.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:d,type:"text",placeholder:i||`Send message to ${r}...`,value:h,onChange:x=>m(x.target.value),onPaste:x=>{const v=x.clipboardData.getData("text");v&&m(g=>g+v),x.preventDefault()},onKeyDown:x=>{if(x.key==="Enter"){if(x.nativeEvent.isComposing){x.preventDefault();return}x.preventDefault(),p()}},onBlur:x=>{if(window.innerWidth<768){const v=x.relatedTarget;if((v==null?void 0:v.tagName)==="BUTTON")return;setTimeout(()=>{document.documentElement.scrollTop=0},300)}},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))"}})}),t.jsx("button",{onClick:()=>{p()},disabled:Xu({hasDraft:!!h.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${h.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:h.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:h.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),Je=e=>e.transport==="pty",Ts=(e,s)=>Je(e)?e.mode||"terminal":"chat",Fi=(e,s)=>Je(e)&&Ts(e)==="terminal",qe=e=>e.transport==="acp";function Vt(e){return e.streamSource!=="agent-stream"}function fs(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function Ui(e){return e.machineName||""}function sr(e){return fs(e)}function Kt(e){return e.agentType||""}function Hr(e){return e.hostIdeType||""}function ka(e){return e.displayPrimary||e.agentName||"Agent"}function zi(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Ju(e){return e.lastMessagePreview||e.displaySecondary||""}function Vi(e){return[e.displaySecondary,Ui(e)].filter(Boolean)}function Ns(e){return e.agentName||et(Kt(e))}function Qu(e){var s,r;if(!Vt(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return et(Hr(e)||Kt(e))}function Gi(e){return Vt(e)?e.sessionId:e.nativeSessionId}function vo(e){return Vt(e)?"native":e.tabKey}function Zu(e){return e.sessionId}function em(e,s){if(s)return Vt(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function tm(e,s){const r=Kt(e),n=Vt(e),a=Je(e)||qe(e),i=n?a?Ns(e)||(s==null?void 0:s.cliName)||et(Hr(e)||r):s!=null&&s.type?et(s.type):et(Hr(e)||r):Ns(e);return{isNativeConversation:n,isCli:Je(e),isAcp:qe(e),isCliTerminal:Fi(e),providerType:r,displayLabel:i,targetEntry:em(e,s)}}function gt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ht(e,s){const r=gt(s);return r?`${e}:${r}`:void 0}function zt(e,s,r){const n=Ht(s,r),a=gt(r);n&&e.push(n),a&&e.push(a)}function gs(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function qi(e){return gt(e.providerSessionId)||gt(e.sessionId)||gt(e.tabKey)||gt(e.routeId)}function Sa(e){return gs([gt(e.providerSessionId),gt(e.sessionId)])}function ws(e){const s=[];return zt(s,"provider",e.providerSessionId),zt(s,"session",e.sessionId),zt(s,"tab",e.tabKey),zt(s,"route",e.routeId),gs(s)}function sm(e){const s=[];return gt(e.providerSessionId)?(zt(s,"provider",e.providerSessionId),gs(s)):gt(e.sessionId)?(zt(s,"session",e.sessionId),gs(s)):gt(e.tabKey)?(zt(s,"tab",e.tabKey),gs(s)):gt(e.routeId)?(zt(s,"route",e.routeId),gs(s)):[]}function Na(e){return Ht("provider",e.providerSessionId)||Ht("session",e.sessionId)||Ht("tab",e.tabKey)||Ht("route",e.routeId)||"unknown:"}function rr(e){return Sa(e)[0]}function rm(e){const s=gt(e.providerSessionId),r=gt(e.sessionId),n=gt(e.tabKey),a=gt(e.routeId),i=[Ht("provider",s),Ht("session",r),Ht("tab",n),Ht("route",a)].filter(u=>typeof u=="string"),c=ws({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),l=Na({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:qi({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:rr({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function Qn(e,s){const r=rm(e);return sm(s).some(n=>r.lookupKeys.includes(n))}function wo(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function es(e){const s=[...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=wo(s==null?void 0:s.receivedAt)||wo(s==null?void 0:s.timestamp)||0;return Math.max(r,n)}function Zn(e,s=0){return es(e)||e.lastUpdated||s||0}function Yi(e){return es(e)||e.lastUpdated||0}function Xi(e,s,r=Yi){const n=r(s)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(s.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(s.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(s.displaySecondary);return c!==0?c:e.tabKey.localeCompare(s.tabKey)}function ea(e){var r;const s=bt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function nm(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!ea(e)&&!e.title.trim()}function am(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(ea(r))-Number(ea(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:Xi(s,r)})[0]||null}function _t(e,s){const r=e.filter(c=>c.routeId===s);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,a=r.filter(c=>c.streamSource==="agent-stream"),i=am(a);return n?i&&nm(n)?i:n:i||r[0]||null}function Gt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ca(e){return rr(e)||e.tabKey||e.routeId||null}function Ji(e){const s=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(s)return s;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=_t(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?Ca(a):null}function Qi({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Ms(),c=fs(e),l=Ui(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",f=e.streamSource==="agent-stream"&&!!e.agentName,d=!f&&(e.transport==="pty"||e.transport==="acp"),h=Ns(e),m=Qu(e),k=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),S=o.useCallback(()=>{if(r){r();return}const p=Ca(e);p&&i(Gt(p))},[e,i,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[u&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:m,children:[t.jsx(Ct,{size:12}),t.jsx("span",{children:m})]}):t.jsxs("span",{className:"conversation-meta-chip",title:m,children:[t.jsx(Ct,{size:12}),t.jsx("span",{children:m})]})),f&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[t.jsx(Ys,{size:12}),t.jsx("span",{children:h})]}),d&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[t.jsx(Ys,{size:12}),t.jsx("span",{children:h})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:k,title:l,children:[t.jsx(ls,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(ls,{size:12}),t.jsx("span",{children:l})]}))]})}function xn(e,s){return`${e}:${s}`}function om(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function hr(e,s){om()&&console.debug(`[subscription-manager] ${e}`,s)}class im{constructor(){Ge(this,"active",new Map)}subscribe(s,r,n,a){var f;const i=xn(n.topic,n.key),c=this.active.get(i);let l=!0;if(c)c.handlers.add(a),c.lastUpdate&&a(c.lastUpdate);else{const d={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,d),hr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((f=s.sendData)==null?void 0:f.call(s,r,n))??!1}const u=()=>{var m;const d=this.active.get(i);if(!d||(d.handlers.delete(a),d.handlers.size>0))return;this.active.delete(i);const h={type:"unsubscribe",topic:n.topic,key:n.key};hr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(m=s.sendData)==null||m.call(s,r,h)};return u.initialSendAccepted=l,u}publish(s){const r=xn(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,ks.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.publish",topic:s.topic,payload:{key:s.key}}),n.handlers.forEach(a=>{a(s),ks.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}updateParams(s,r,n){const a=xn(s,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;hr("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=s.sendData)==null||r.call(s,n.daemonId,n.request)}resubscribeForDaemon(s,r){var a;const n=Array.from(this.active.values()).filter(i=>i.daemonId===s);hr("resubscribe_daemon",{daemonId:s,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)}}const qt=new im;function cm(e,s){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===s&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker});for(const i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function lm(e){const s=[],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 s.push(n);return{topLevel:s,childrenByParent:r}}function Fr(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:f,childrenByParent:d}=lm(u),h=cm(i,n),m=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,k=f.filter(x=>x.kind==="workspace"&&x.transport==="cdp-page"),S=f.filter(x=>x.kind==="agent"&&x.transport==="pty"),p=f.filter(x=>x.kind==="agent"&&x.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...m&&{machine:m,platform:m.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},cdpConnected:k.some(x=>!!x.cdpConnected)});for(const x of k){const v=h.get(x.id),g=Bs(x,v),N=(d.get(x.id)||[]).map(M=>Bs(M,h.get(M.id)));r.push({id:`${n}:ide:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:g.parentId,sessionKind:g.kind,transport:g.transport,sessionCapabilities:g.capabilities,type:g.providerType,status:g.cdpConnected?"online":"detected",daemonId:n,instanceId:x.id,workspace:g.workspace,terminals:0,childSessions:N,agents:N.map(M=>({id:M.id,name:M.providerName||M.providerType,type:M.providerType,status:M.status})),activeChat:g.activeChat,chats:[],cdpConnected:g.cdpConnected,...g.lastMessagePreview!==void 0&&{lastMessagePreview:g.lastMessagePreview},...g.lastMessageRole!==void 0&&{lastMessageRole:g.lastMessageRole},...g.lastMessageAt!==void 0&&{lastMessageAt:g.lastMessageAt},...g.lastMessageHash!==void 0&&{lastMessageHash:g.lastMessageHash},lastUpdated:g.lastUpdated,unread:g.unread,lastSeenAt:g.lastSeenAt,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,seenCompletionMarker:g.seenCompletionMarker,surfaceHidden:g.surfaceHidden,...g.controlValues!==void 0&&{controlValues:g.controlValues},...g.providerControls!==void 0&&{providerControls:g.providerControls},...g.summaryMetadata!==void 0&&{summaryMetadata:g.summaryMetadata},timestamp:l})}for(const x of S){const v=h.get(x.id),g=Bs(x,v);r.push({id:`${n}:cli:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:g.parentId,sessionKind:g.kind,transport:g.transport,sessionCapabilities:g.capabilities,type:g.providerType,agentType:g.providerType,status:g.status||"running",daemonId:n,instanceId:x.id,cliName:g.providerName||g.providerType,mode:g.mode||(v==null?void 0:v.mode)||"terminal",workspace:g.workspace||"",activeChat:g.activeChat,...g.resume!==void 0&&{resume:g.resume},...g.runtimeKey!==void 0&&{runtimeKey:g.runtimeKey},...g.runtimeDisplayName!==void 0&&{runtimeDisplayName:g.runtimeDisplayName},...g.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:g.runtimeWorkspaceLabel},...g.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:g.runtimeWriteOwner},...g.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:g.runtimeAttachedClients},...g.lastMessagePreview!==void 0&&{lastMessagePreview:g.lastMessagePreview},...g.lastMessageRole!==void 0&&{lastMessageRole:g.lastMessageRole},...g.lastMessageAt!==void 0&&{lastMessageAt:g.lastMessageAt},...g.lastMessageHash!==void 0&&{lastMessageHash:g.lastMessageHash},lastUpdated:g.lastUpdated,unread:g.unread,lastSeenAt:g.lastSeenAt,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,seenCompletionMarker:g.seenCompletionMarker,surfaceHidden:g.surfaceHidden,...g.controlValues!==void 0&&{controlValues:g.controlValues},...g.providerControls!==void 0&&{providerControls:g.providerControls},...g.summaryMetadata!==void 0&&{summaryMetadata:g.summaryMetadata},timestamp:l,_isCli:!0})}for(const x of p){const v=h.get(x.id),g=Bs(x,v);r.push({id:`${n}:acp:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:g.parentId,sessionKind:g.kind,transport:g.transport,sessionCapabilities:g.capabilities,type:g.providerType,agentType:g.providerType,status:g.status||"running",daemonId:n,instanceId:x.id,cliName:g.providerName||g.providerType,mode:"chat",workspace:g.workspace||"",activeChat:g.activeChat,...g.runtimeKey!==void 0&&{runtimeKey:g.runtimeKey},...g.runtimeDisplayName!==void 0&&{runtimeDisplayName:g.runtimeDisplayName},...g.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:g.runtimeWorkspaceLabel},...g.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:g.runtimeWriteOwner},...g.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:g.runtimeAttachedClients},...g.lastMessagePreview!==void 0&&{lastMessagePreview:g.lastMessagePreview},...g.lastMessageRole!==void 0&&{lastMessageRole:g.lastMessageRole},...g.lastMessageAt!==void 0&&{lastMessageAt:g.lastMessageAt},...g.lastMessageHash!==void 0&&{lastMessageHash:g.lastMessageHash},lastUpdated:g.lastUpdated,unread:g.unread,lastSeenAt:g.lastSeenAt,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,seenCompletionMarker:g.seenCompletionMarker,surfaceHidden:g.surfaceHidden,...g.controlValues!==void 0&&{controlValues:g.controlValues},...g.providerControls!==void 0&&{providerControls:g.providerControls},...g.summaryMetadata!==void 0&&{summaryMetadata:g.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const dm=15e3,um=15e3,mm=6e4,fm=1200,jo=12,pm=8e3,hm=4e3,bn=new Map,gn=new Map,xr=new Set,Ws=new Map;function xm(e){if(!e||typeof e!="object")return null;const s=e,r=s.status;if(r&&typeof r=="object")return r;const n=s.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return s}function ko(e,s){const r=Ws.get(e);!r||r.size===0||(Ws.delete(e),r.forEach(n=>n(s)))}function bm(e,s){return new Promise(r=>{const n=Ws.get(e)||new Set;Ws.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&Ws.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function nr(){const{sendCommand:e,sendData:s}=jt(),{injectEntries:r,getIdes:n}=Gs();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??mm,l=gn.get(a)||0;if(!(i!=null&&i.force)&&xr.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=bn.get(a);if(u)return u;const f=(async()=>{if(s&&!xr.has(a)){const p=qt.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},x=>{const v=n(),g=v.find(M=>M.id===a),N=Fr(x.status,{daemonId:a,existingDaemon:g,existingEntries:v,timestamp:x.timestamp});N.length>0&&r(N),gn.set(a,Date.now()),ko(a,!0)});if(p.initialSendAccepted?xr.add(a):xr.delete(a),!(i!=null&&i.force)&&p.initialSendAccepted&&await bm(a,fm))return}const d=await e(a,"get_status_metadata"),h=xm(d);if(!h)return;const m=n(),k=m.find(p=>p.id===a),S=Fr(h,{daemonId:a,existingDaemon:k,existingEntries:m,timestamp:h.timestamp||Date.now()});S.length>0&&r(S,{authoritativeDaemonIds:[a]}),gn.set(a,Date.now()),ko(a,!0)})().finally(()=>{bn.delete(a)});return bn.set(a,f),f},[n,r,e,s])}function gm(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function js(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:Je(e)||qe(e)?{agentType:Kt(e)}:e.streamSource==="agent-stream"?{agentType:Kt(e)}:s}function Js(e){return e?sr(e):""}function Rs(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Ia(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function ym(e){const s=e instanceof Error?e.message:String(e||""),r=s.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.":s||"Unable to send message right now."}const vm=60,wm=1e3;function Zi(e={}){return e.isCliLike?wm:vm}function jm(e={}){return Zi(e)}const ar=60,km=1e3,Ma=12e4,Sm=new Set(["generating","waiting_approval","starting","streaming","working"]),So=new Map;function ec(e,s){return`${e}::${s}`}function ta(e=ar){return{liveMessages:[],cursor:tc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function sa(e){return yi(e)}function tc(e,s=ar){return{knownMessageCount:e.length,lastMessageSignature:sa(e[e.length-1]),tailLimit:s}}function br(e,s){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function Nm(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return[...e,...r];case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return[...e.slice(0,n),...r]}case"full":return r;default:return r}}class Cm{constructor(s){Ge(this,"manager");Ge(this,"sendData");Ge(this,"daemonId");Ge(this,"sessionId");Ge(this,"historySessionId");Ge(this,"subscriptionKey");Ge(this,"snapshot");Ge(this,"transportSubscription",null);Ge(this,"listeners",new Set);Ge(this,"retainCount",0);Ge(this,"loadHistoryPromise",null);Ge(this,"pendingDisconnectTimer",null);Ge(this,"pendingSubscribeRetryTimer",null);this.manager=s.manager||qt,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=ta(Math.max(0,s.tailLimit??ar))}updateOptions(s){if(s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId),s.tailLimit!==void 0){const r=Math.max(0,s.tailLimit);if(r!==this.snapshot.cursor.tailLimit){const n=Math.min(this.snapshot.cursor.knownMessageCount,this.snapshot.liveMessages.length);this.snapshot={...this.snapshot,cursor:{...this.snapshot.cursor,knownMessageCount:n,tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect())}}}getSnapshot(){return this.snapshot}hydrateLiveMessages(s){const r=Array.isArray(s)?s:[];if(r.length===0)return;const n=r,a=tc(n,this.snapshot.cursor.tailLimit);br(this.snapshot.liveMessages)===br(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a},this.emit())}subscribe(s){return this.listeners.add(s),s(this.snapshot),()=>{this.listeners.delete(s)}}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(s){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await s(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},knownMessageCount:this.snapshot.cursor.knownMessageCount,lastMessageSignature:this.snapshot.cursor.lastMessageSignature,...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}clearPendingSubscribeRetry(){this.pendingSubscribeRetryTimer&&(clearTimeout(this.pendingSubscribeRetryTimer),this.pendingSubscribeRetryTimer=null)}scheduleSubscribeRetry(){this.pendingSubscribeRetryTimer||!this.sendData||!this.daemonId||!this.sessionId||this.retainCount===0||(this.pendingSubscribeRetryTimer=setTimeout(()=>{if(this.pendingSubscribeRetryTimer=null,!this.sendData||!this.daemonId||!this.sessionId||this.retainCount===0)return;this.sendData(this.daemonId,this.buildSubscribeRequest())||this.scheduleSubscribeRetry()},km))}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),s=>{this.handleUpdate(s)}),this.transportSubscription.initialSendAccepted||this.scheduleSubscribeRetry())}disconnect(){var s;this.clearPendingSubscribeRetry(),(s=this.transportSubscription)==null||s.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(s=>s(this.snapshot))}handleUpdate(s){this.clearPendingSubscribeRetry();const r=typeof s.lastMessageSignature=="string"?s.lastMessageSignature:"",n=sa(this.snapshot.liveMessages[this.snapshot.liveMessages.length-1]);if(s.syncMode!=="full"&&r&&n===r){const u={knownMessageCount:Math.max(this.snapshot.cursor.knownMessageCount,Number(s.totalMessages||0)),lastMessageSignature:r,tailLimit:this.snapshot.cursor.tailLimit};this.snapshot.cursor.knownMessageCount===u.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===u.lastMessageSignature||(this.snapshot={...this.snapshot,cursor:u},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:u.knownMessageCount,lastMessageSignature:u.lastMessageSignature}));return}const a=Nm(this.snapshot.liveMessages,s),i={knownMessageCount:a.length,lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:sa(a[a.length-1]),tailLimit:this.snapshot.cursor.tailLimit};br(this.snapshot.liveMessages)===br(a)&&this.snapshot.cursor.knownMessageCount===i.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===i.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:a,cursor:i},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:i.knownMessageCount,lastMessageSignature:i.lastMessageSignature}),this.emit())}}function sc(e){const s=ec(e.daemonId,e.sessionId),r=So.get(s);if(r)return r.updateOptions(e),r;const n=new Cm(e);return So.set(s,n),n}function Im(e,s){return{...e,loadHistoryPage:s}}function Mm(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function Am(e,s={}){const r=String(e.status||"").trim().toLowerCase();if(Sm.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=s.now??Date.now(),a=Math.max(0,Number(s.recentActivityMs??Ma)),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 Tm(e=Ma){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Lm(e,s={}){const r=new Set,n=[];for(const a of e){if(!Am(a,s))continue;const i=sr(a),c=a.sessionId||"";if(!i||!c)continue;const l=ec(i,c);if(r.has(l))continue;r.add(l);const u=rr(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Mm),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Rm(e,s){const{sendData:r,sendCommand:n}=jt(),a=(s==null?void 0:s.enabled)!==!1,i=sr(e),c=e.sessionId||"",l=rr(e)||c,u=`daemon:${i}:session:${c}`,f=Math.max(0,(s==null?void 0:s.tailLimit)??ar),d=o.useMemo(()=>!a||!i||!c?null:sc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:f}),[i,a,l,r,c,u,f]),[h,m]=o.useState(()=>(d==null?void 0:d.getSnapshot())||ta(f));o.useEffect(()=>{if(!d){m(ta(f));return}d.retain(),m(d.getSnapshot());const S=d.subscribe(p=>{m(p)});return()=>{S(),d.release()}},[d,f]),o.useEffect(()=>{d&&(d.hydrateLiveMessages(e.messages),m(d.getSnapshot()))},[e.messages,d]);const k=o.useCallback(async()=>{!d||!i||!c||await d.loadHistoryPage(async()=>{const S=e.agentType,p=await n(i,"chat_history",{agentType:S,offset:d.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),x=p&&typeof p=="object"&&"result"in p?p.result||{}:p||{};return{messages:Array.isArray(x.messages)?x.messages:[],hasMore:x.hasMore===!0}})},[e.agentType,d,i,l,n,c]);return o.useMemo(()=>Im(h,k),[k,h])}function Pm(e,s){const{sendData:r}=jt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,(s==null?void 0:s.tailLimit)??ar),i=Math.max(0,Number((s==null?void 0:s.recentActivityMs)??Ma)),c=Tm(i),[l,u]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const d=setInterval(()=>{u(h=>h+1)},c);return()=>{clearInterval(d)}},[e.length,n,c]);const f=o.useMemo(()=>Lm(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||f.descriptors.length===0)return;const d=f.descriptors.map(h=>sc({...h,sendData:r,tailLimit:a}));return d.forEach(h=>h.retain()),()=>{d.forEach(h=>h.release())}},[f.signature,n,r,a])}function _m(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function Dm(e){return _m(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Em=60;function ra({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:f=!1,scrollToBottomRequestNonce:d,isInputActive:h=!0,isVisible:m=!0}){var ge,be,we,z,U;const k=o.useRef(new Map),S=nr();tr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const p=St.useMemo(()=>As(e),[e.status,e.connectionState]),x=o.useMemo(()=>tm(e,s),[e,s]),v=o.useMemo(()=>{var Q;return ja((Q=x.targetEntry)==null?void 0:Q.providerControls,{hostIdeType:e.hostIdeType,providerType:x.providerType})},[e.hostIdeType,x.providerType,(ge=x.targetEntry)==null?void 0:ge.providerControls]),g=Zi({isCliLike:x.isCli||x.isAcp}),N=jm({isCliLike:x.isCli||x.isAcp}),M=Rm(e,{enabled:m&&!!e.sessionId,tailLimit:N}),[y,C]=o.useState(g),j=e.tabKey,w=M.historyMessages,b=M.hasMoreHistory,E=M.historyError,A=M.liveMessages.length>0?M.liveMessages:e.messages;o.useEffect(()=>{C(g)},[g,j]);const I=Math.max(0,A.length-y),P=ka(e),O=sr(e),V=Dm(e),L=Ia(e),R=a||L,G=!!L,[B,$]=o.useState(!1);o.useEffect(()=>{const Q=x.targetEntry;O&&(!Q||Q.providerControls===void 0||Q.controlValues===void 0)&&S(O,{minFreshMs:3e4}).catch(()=>{})},[O,x.isAcp,(be=x.targetEntry)==null?void 0:be.providerControls,(we=x.targetEntry)==null?void 0:we.controlValues,S]);const H=o.useCallback(async()=>{if(!B){if(A.length>y){C(Q=>Math.min(A.length,Q+Em));return}$(!0);try{await M.loadHistoryPage()}finally{$(!1)}}},[M,B,A.length,y]),{allMessages:J,receivedAtMap:xe}=o.useMemo(()=>{const Q=I>0?A.slice(-y):A,de=w.length===0?Q:[...w,...Q],re={};return de.forEach((le,te)=>{const fe=`${e.tabKey}:${Kr(le,te)}`;let ne=gm(le)||k.current.get(fe)||0;ne||(ne=Date.now(),k.current.set(fe,ne)),re[Kr(le,te)]=ne}),{allMessages:de,receivedAtMap:re}},[e.tabKey,I,w,A,y]),me=o.useMemo(()=>l.filter(Q=>Q.routeId===e.tabKey).sort((Q,de)=>Q.timestamp-de.timestamp),[l,e.tabKey]),ce=o.useMemo(()=>{if(A.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[t.jsx("div",{className:"connecting-logo-float",children:t.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:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),t.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[t.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",t.jsx("span",{className:"connecting-dots"})]}),t.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((p.isGenerating||e.status==="streaming")&&$(!1),e.status==="not_monitored"&&V)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(Ys,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ss,{size:14})," Open ",P," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&V)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(Si,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ss,{size:14})," Open ",P," Panel"]})}),t.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"&&!B)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),t.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,V,i,c,B,A.length,P,p.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[f&&t.jsx(Qi,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(Xd,{messages:J,actionLogs:me,agentName:Ns(e)||P||"Agent",userName:u,isCliMode:x.isCli||x.isAcp,isWorking:p.isGenerating,contextKey:e.tabKey,receivedAtMap:xe,onLoadMore:H,isLoadingMore:B,hasMoreHistory:b,hiddenLiveCount:I,loadError:E??void 0,emptyState:ce,scrollToBottomRequestNonce:d,isVisible:m}),t.jsx(Yu,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:x.providerType,displayLabel:x.displayLabel,controls:(z=x.targetEntry)==null?void 0:z.providerControls,controlValues:(U=x.targetEntry)==null?void 0:U.controlValues,isActive:h,isCliTerminal:x.isCliTerminal}),!x.isCliTerminal&&t.jsx(Hi,{contextKey:e.tabKey,panelLabel:P,isSending:n,isBusy:G,statusMessage:R,onSend:r,isActive:h,showControlsToggle:v.length>0})]})}let rc=cs;function nc(){return rc()}class $m{constructor(){Ge(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(a=>a(...r))}}let ac=new $m;class Bm{sendPtyInput(s,r,n){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,r){return!1}get(s){}onScreenshot(s,r){return()=>{}}onRuntimeEvent(s,r){return()=>{}}requestRuntimeSnapshot(s,r){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let it=new Bm;function Km(e){e.dashboardWS&&(ac=e.dashboardWS),e.connectionManager&&(it=e.connectionManager),e.useDaemonsHook&&(rc=e.useDaemonsHook)}const Om=.5,Wm=1.25;function No(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function Hm(e){return[...e].reverse().find(s=>!(s!=null&&s._localId))||e[e.length-1]}function Fm(e){return No(e==null?void 0:e.receivedAt)||No(e==null?void 0:e.timestamp)||0}function rt(e){return ka(e)}function us(e){return Vi(e).join(" · ")}function oc(e){const s=Hm(e.messages),r=Vs(s==null?void 0:s.content),n=Fm(s),a=Vs(e.lastMessagePreview),i=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0;return a&&(!r||i>0&&i>=n)?a:r||a||(e.title?e.title:us(e)||"No messages yet")}function ic(e,s){const{isReconnecting:r,isConnecting:n}=As(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Um(e,s){const r=["Chat",...Vi(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function ts(e){return ic(e)||us(e)}function zm(e){return`${rt(e)} · ${oc(e)}`}function Vm(e){const s=Hr(e),r=s?et(s):Ns(e);return`${rt(e)} — ${r||"Agent"}`}function Gm(e){return Ns(e)||"CLI"}function cc(e){return zi(e)}function lc(e){return e?`Remote · ${rt(e)||e.workspaceName||"Session"}`:"Remote"}function qm({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var T;cs();const{sendPtyInput:u}=jt(),[f,d]=o.useState(!1),[h,m]=o.useState("Runtime terminal unavailable"),[k,S]=o.useState(1),[p,x]=o.useState({width:0,height:0}),[v,g]=o.useState({width:0,height:0}),N=o.useRef(null),M=o.useRef(null),y=o.useRef(!1),C=o.useRef(!1),j=o.useRef(0),w=o.useRef(!1),b=o.useRef(""),E=o.useRef(null),A=o.useRef(!1),I=o.useRef(null),P=32*1024,O=()=>{var D,Y,X,pe;return((Y=(D=N.current)==null?void 0:D.ownerDocument)==null?void 0:Y.defaultView)||((pe=(X=M.current)==null?void 0:X.ownerDocument)==null?void 0:pe.defaultView)||window},V=D=>{const Y=O();return{ownerWindow:Y,frameId:Y.requestAnimationFrame(D)}},L=()=>{const D=I.current;if(D){try{D.ownerWindow.cancelAnimationFrame(D.frameId)}catch{}I.current=null}},R=()=>{c&&I.current===null&&(I.current=V(()=>{ae()}))},G=e.tabKey,B=e.sessionId||"",$=e.daemonId||((T=e.routeId)==null?void 0:T.split(":")[0])||e.routeId||"",H=Ia(e),J=f?i||H:h,xe=Om,me=Wm,ce=.05,ge=Number.isFinite(k)&&k>0?k:1,be=Number((13*k).toFixed(2)),we=()=>{const D=v.width>0?Math.max(p.width,Math.round(v.width)):p.width,Y=v.height>0?Math.max(p.height,Math.round(v.height)):p.height;if(!Number.isFinite(p.width)||p.width<=0||!Number.isFinite(p.height)||p.height<=0||!Number.isFinite(D)||D<=0||!Number.isFinite(Y)||Y<=0)return 1;const X=D/ge,pe=Y/ge;if(!Number.isFinite(X)||X<=0||!Number.isFinite(pe)||pe<=0)return 1;const Ie=p.width/X,Ne=p.height/pe;return Number(Math.min(me,Math.max(xe,Math.min(Ie,Ne))).toFixed(2))},z=we(),U=y.current&&k>z,Q=v.width>p.width+1||v.height>p.height+1,de=v.width>0?Math.max(p.width,Math.round(v.width)):p.width,re=v.height>0?Math.max(p.height,Math.round(v.height)):p.height,le=v.width>0?Math.round(v.width):de,te=v.height>0?Math.round(v.height):re,fe=()=>{V(()=>{const D=M.current;D&&(D.scrollLeft=0,D.scrollTop=D.scrollHeight-D.clientHeight)})},ne=()=>{var D,Y;j.current=0,w.current=!1,b.current="",E.current=null,A.current=!1,y.current||(C.current=!1,S(1)),I.current!==null&&L(),d(!1),m("Runtime terminal unavailable"),(Y=(D=r.current)==null?void 0:D.reset)==null||Y.call(D)},ie=()=>{var D,Y;j.current=0,w.current=!1,b.current="",E.current=null,A.current=!1,I.current!==null&&L(),d(!0),m(""),(Y=(D=r.current)==null?void 0:D.reset)==null||Y.call(D)},ae=()=>{var X;if(I.current=null,!c)return;const D=b.current;if(!D)return;const Y=D.slice(0,P);b.current=D.slice(Y.length),(X=r.current)==null||X.write(Y),b.current.length>0&&R()},ye=D=>{D&&(b.current+=D,R())},he=(D,Y=0,X,pe)=>{var Ie,Ne,Be,He;Y>0&&j.current>=Y||Y===0&&w.current||(j.current=Y,d(!0),m(""),typeof X=="number"&&typeof pe=="number"&&X>0&&pe>0&&((Ne=(Ie=r.current)==null?void 0:Ie.resize)==null||Ne.call(Ie,X,pe)),b.current="",(He=(Be=r.current)==null?void 0:Be.reset)==null||He.call(Be),D&&ye(D))};o.useEffect(()=>{ne()},[B]),o.useEffect(()=>{var Y;if(!B)return;const D=((Y=it.onRuntimeEvent)==null?void 0:Y.call(it,B,X=>{if(!(!X||X.sessionId!==B)){if(X.type==="runtime_snapshot"){if(!c){E.current={text:X.text||"",seq:X.seq||0,cols:X.cols,rows:X.rows};return}he(X.text||"",X.seq||0,X.cols,X.rows);return}if(X.type==="session_output"){w.current=!0,typeof X.seq=="number"&&(j.current=Math.max(j.current,X.seq)),f||d(!0),f||m(""),typeof X.data=="string"&&ye(X.data);return}if(X.type==="session_cleared"){if(!c){A.current=!0,b.current="",E.current=null;return}ie();return}if(X.type==="session_io_error"){const pe=typeof X.error=="string"&&X.error?X.error:typeof X.reason=="string"&&X.reason?X.reason:"unknown error";d(!1),m(`Runtime input failed: ${pe}`);return}}}))||(()=>{});return()=>{D()}},[$,B,r,c,f]);const Se=async()=>{var D;if(!(!$||!B)){m("Loading runtime terminal...");try{const Y=await((D=it.requestRuntimeSnapshot)==null?void 0:D.call(it,$,B));Y&&Y.success===!1&&(d(!1),m(`Runtime terminal unavailable: ${Y.error}`))}catch(Y){d(!1),m(`Runtime terminal unavailable: ${(Y==null?void 0:Y.message)||String(Y)}`)}}};return o.useEffect(()=>{var Y,X;if(!B)return;$&&((Y=it.getState)==null?void 0:Y.call(it,$))==="connected"&&Se();const D=(X=it.onStateChange)==null?void 0:X.call(it,(pe,Ie)=>{pe!==$||Ie!=="connected"||Se()});return()=>{D==null||D()}},[$,B,r]),o.useEffect(()=>{s&&ne()},[s,G,r]),o.useEffect(()=>{var pe,Ie;const D=N.current,Y=(Ie=(pe=D==null?void 0:D.ownerDocument)==null?void 0:pe.defaultView)==null?void 0:Ie.ResizeObserver;if(!D||!Y)return;const X=new Y(Ne=>{const Be=Ne[0];if(!Be)return;const{width:He,height:Ue}=Be.contentRect;x(Qe=>{const tt=Math.round(He),ct=Math.round(Ue);return Qe.width===tt&&Qe.height===ct?Qe:{width:tt,height:ct}})});return X.observe(D),()=>X.disconnect()},[]),o.useEffect(()=>{if(y.current)return;const D=we();!Number.isFinite(D)||D<=0||S(Y=>C.current?D<Y-ce?D:Y:(C.current=!0,D))},[v.height,v.width,p.height,p.width]),o.useEffect(()=>{!Q&&!U||fe()},[Q,U,re,de]),o.useEffect(()=>{var Y;if(!c)return;A.current&&(A.current=!1,ie());const D=E.current;D&&(E.current=null,he(D.text,D.seq,D.cols,D.rows)),$&&B&&((Y=it.getState)==null?void 0:Y.call(it,$))==="connected"&&Se(),b.current&&I.current===null&&R(),V(()=>{var X;(X=r.current)==null||X.bumpResize()})},[$,c,B]),o.useEffect(()=>()=>{I.current!==null&&L()},[]),o.useEffect(()=>{const D=pe=>{var Ne;const Ie=pe.detail;Ie!=null&&Ie.sessionId&&Ie.sessionId!==B||f&&((Ne=r.current)==null||Ne.bumpResize())},Y=O(),X=Y===window?[window]:[window,Y];for(const pe of X)pe.addEventListener("adhdev:fit-cli-terminal",D);return()=>{for(const pe of X)pe.removeEventListener("adhdev:fit-cli-terminal",D)}},[f,B,r]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:N,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[t.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[t.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:()=>{y.current=!0,S(D=>{const Y=Math.max(z,Number((D-.1).toFixed(2)));return Y>z&&fe(),Y})},title:"Shrink terminal viewport",children:"-"}),t.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:()=>{y.current=!0,S(D=>{const Y=Math.min(me,Number((D+.1).toFixed(2)));return Y>z&&fe(),Y})},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{ref:M,className:Q?"w-full h-full overflow-x-auto overflow-y-hidden rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",style:{display:"flex",justifyContent:"flex-start",alignItems:"flex-end"},children:t.jsx("div",{style:{width:le>0?`${le}px`:de>0?`${de}px`:"100%",height:te>0?`${te}px`:re>0?`${re}px`:"100%",minWidth:le>0?`${le}px`:"100%",minHeight:te>0?`${te}px`:"100%",position:"relative"},children:t.jsx("div",{style:{width:"100%",height:"100%",position:"absolute",left:0,bottom:0},children:t.jsx(Ti,{ref:r,readOnly:!f||!c,sizingMode:"measured",fontSize:be,onViewportMetrics:g,onInput:D=>{!f||(u==null||u($,B,D))}})})})}),!f&&t.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:h})]}),t.jsx(Hi,{contextKey:e.tabKey,panelLabel:rt(e),isSending:a,isBusy:!f||!!H,statusMessage:J,onSend:async D=>!f||H?!1:n(D),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}function Ym({wsStatus:e,showReconnected:s,loginUrl:r,onReconnect:n}){const a=e==="disconnected"||e==="reconnecting"||e==="offline"||e==="auth_failed",i=e==="auth_failed"?"red":e==="offline"?"orange":"accent",c={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))"},l={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)"},u={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},f="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",d={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return t.jsxs(t.Fragment,{children:[a&&t.jsx("div",{className:f,style:d,children:t.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-4 py-3 text-[13px] font-semibold flex items-center gap-2.5 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:c[i],border:l[i],color:u[i]},children:[t.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}}),t.jsxs("span",{className:"min-w-0 text-center",children:[e==="offline"&&"Network offline — waiting for connection...",e==="disconnected"&&"Reconnecting to server...",e==="reconnecting"&&"Reconnecting to server...",e==="auth_failed"&&(r?t.jsxs(t.Fragment,{children:["Session expired."," ",t.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — please restart the server.")]}),n&&e!=="auth_failed"&&t.jsx("button",{type:"button",className:"ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:n,disabled:e==="offline",children:"Reconnect now"})]})}),s&&e==="connected"&&t.jsx("div",{className:f,style:d,children:t.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:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function Xm({terminalBackend:e,isStandalone:s=!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]),!s||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",u=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!0)};return t.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:[t.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[t.jsxs("span",{children:[l," is using `xterm` fallback."]}),t.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),t.jsx("button",{type:"button",onClick:u,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Aa({mode:e,onChange:s,compact:r=!1}){const n=r?14:15;return t.jsx("button",{type:"button",onClick:()=>s(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?t.jsx(ba,{size:n}):t.jsx(Ft,{size:n})})}const $t="New session",dc="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 Jm({wsStatus:e,isConnected:s,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..."}:s?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function Co({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Io({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=Jr(e.updatedAt),l=!e.readAt;return t.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[t.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[s?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",s]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?t.jsx("span",{className:"dashboard-header-inbox-item-meta",children:e.preview}):null]}),t.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),n()},children:"Mark read"}):t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:"Mark unread"}),t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),i()},children:"Delete"})]})]})}function Qm({activeConv:e,wsStatus:s,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:u,onHideConversation:f,hiddenConversations:d=[],onShowConversation:h,onShowAllHidden:m,onResetPanelsToMain:k,inboxOpen:S,onInboxOpenChange:p,hiddenOpen:x,onHiddenOpenChange:v,onOpenNewSession:g,actionShortcuts:N,notifications:M,notificationUnreadCount:y,onOpenNotification:C,onMarkNotificationRead:j,onMarkNotificationUnread:w,onDeleteNotification:b}){const{ides:E,p2pStates:A={}}=cs(),I=!!e&&Je(e)&&!qe(e),P=!!e&&qe(e),O=l||(e?Fi(e)?"terminal":"chat":null),[V,L]=o.useState(!1),R=o.useRef(null),G=o.useRef(null),B=E.filter(z=>z.type==="adhdev-daemon"),$=Jm({wsStatus:s,isConnected:r,daemonCount:B.length,p2pStates:A}),H=$.subtitle,J=$.tone==="connected"?"#22c55e":$.tone==="limited"?"#eab308":"#ef4444",xe=$.tone==="connected"?"0 0 4px #22c55e80":$.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",me=o.useMemo(()=>M.filter(z=>!z.readAt),[M]),ce=o.useMemo(()=>M.filter(z=>!!z.readAt),[M]),ge=o.useMemo(()=>me.slice(0,9),[me]),be=y;o.useEffect(()=>{if(!S)return;const z=U=>{var Q;(Q=R.current)!=null&&Q.contains(U.target)||p(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[S,p]),o.useEffect(()=>{if(!x)return;const z=U=>{var Q;(Q=G.current)!=null&&Q.contains(U.target)||v(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[x,v]),o.useEffect(()=>{if(!x&&!S)return;const z=U=>{if(!U.altKey)return;const Q=U.code.match(/^Digit([1-9])$/);if(!Q)return;const de=Number(Q[1])-1,re=x?d[de]:void 0,le=S?ge[de]:void 0;if(!(!re&&!le)){if(U.preventDefault(),U.stopPropagation(),re){h==null||h(re),v(!1);return}le&&(C(le),p(!1))}};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[d,x,S,ge,v,p,C,h]);const we=z=>{if(!z)return;const U=n.find(Q=>Q.tabKey===z);U&&(f==null||f(U))};return t.jsxs("div",{className:"dashboard-header",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsx("div",{className:"header-title-block",children:t.jsxs("div",{className:"header-title-row",children:[t.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[t.jsx(Ft,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?rt(e):"Dashboard"}),t.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:t.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:J,boxShadow:xe}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[t.jsx("span",{title:$.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:J,boxShadow:xe}}),H&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",H]}),g&&t.jsx("button",{type:"button",onClick:g,className:"btn btn-secondary btn-sm ml-2",title:$t,"aria-label":$t,children:t.jsx(Ii,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(I||P||!qe(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:us(e)||rt(e),children:rt(e)}),(I||P)&&c&&t.jsxs(t.Fragment,{children:[I&&u&&O&&t.jsx(Aa,{mode:O,onChange:u,compact:!0}),t.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:P?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(wt,{size:14})})]}),!qe(e)&&t.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(xa,{size:14})}),!I&&!qe(e)&&t.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Ct,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:R,children:[t.jsxs("div",{className:`dashboard-header-hidden${V?" is-drop-target":""}`,ref:G,onDragEnter:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),L(!0))},onDragOver:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),z.dataTransfer.dropEffect="move",L(!0))},onDragLeave:z=>{z.currentTarget.contains(z.relatedTarget)||L(!1)},onDrop:z=>{const U=z.dataTransfer.getData("text/tab-key");z.preventDefault(),L(!1),we(U)},children:[t.jsxs("button",{type:"button",onClick:()=>v(!x),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${N!=null&&N.toggleHiddenTabs?` (${N.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(Ni,{size:16}),d.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),x&&t.jsxs("div",{className:"dashboard-header-hidden-popover",children:[t.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),t.jsx(Co,{value:N==null?void 0:N.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[k&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:k,children:"Reset panels"}),d.length>0&&m&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{m(),v(!1)},children:"Restore all"})]})]}),e&&f&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>f(e),children:[t.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[t.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),t.jsx(Co,{value:N==null?void 0:N.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:rt(e)})]}),d.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(z=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(z),v(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:rt(z)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(z)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(z)+1]}):null,us(z)]})]},z.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>p(!S),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(Xr,{size:16}),be>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:be})]}),S&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[me.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),me.map(z=>t.jsx(Io,{notification:z,shortcutIndex:ge.indexOf(z)>=0?ge.indexOf(z)+1:void 0,onOpen:()=>C(z),onMarkRead:()=>j(z.id),onMarkUnread:()=>w(z.id),onDelete:()=>b(z.id)},z.id))]}),ce.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),ce.map(z=>t.jsx(Io,{notification:z,onOpen:()=>C(z),onMarkRead:()=>j(z.id),onMarkUnread:()=>w(z.id),onDelete:()=>b(z.id)},z.id))]}),M.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function ht(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Zm(e,s){return String(e||"")!==String(s||"")}function ef(e,s={}){const r=String(s.textQuery||"").trim().toLowerCase(),n=String(s.workspaceQuery||"").trim().toLowerCase(),a=String(s.modelQuery||"").trim().toLowerCase(),i=!!s.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(u=>String(u||"").toLowerCase()).join(`
|
|
30
|
+
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!$i(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
|
|
31
|
+
`).includes(a)))}function tf(e,s="recent"){const r=e.slice();return r.sort((n,a)=>{if(s==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(s==="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 uc(e,s={}){return tf(ef(e,s),s.sortMode||"recent")}function Ur(e){return e?"Resume saved history":"Start fresh"}function Ta(e){return e?"Resuming saved history…":"Starting fresh…"}function sf(){return"Start fresh"}function mc(e,s=!1){return e==="cli"?Ur(s):e==="ide"?"Start IDE":"Start ACP session"}function fc(e,s=!1){return e==="cli"?Ta(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function rf(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function nf(){return"Open saved history"}function af(){return"Saved History"}function La(){return"Use saved history when you want continuity in the same provider conversation."}function of(){return"No saved history found yet."}function cf(){return"Refresh saved history"}function lf(){return"Refreshing saved history…"}function ss(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function rs(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Cs(e){return e==="start-fresh"?"Start fresh":"Restart"}function Is(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Ra(e){return`Resume saved history with ${e}?`}function Pa(){return"Review or change the target workspace before resuming saved history."}function df(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 _a({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:f,onNewChat:d,onSwitchSession:h,onRefreshHistory:m,onResumeSavedSession:k}){var w;const S=s.find(b=>b.id===e.routeId),p=(S==null?void 0:S.chats)||[],x=(w=S==null?void 0:S.activeChat)==null?void 0:w.id,v=Je(e)&&!qe(e),[g,N]=o.useState(()=>ht()),M=l||g,y=b=>{if(u){u(b);return}N(b)},C=o.useMemo(()=>uc(a,{textQuery:M.textQuery,workspaceQuery:M.workspaceQuery,modelQuery:M.modelQuery,resumableOnly:M.resumableOnly,sortMode:M.sortMode}),[M.modelQuery,M.resumableOnly,M.sortMode,M.textQuery,M.workspaceQuery,a]),j=t.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:[t.jsx("div",{onClick:f,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.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:[t.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:[t.jsxs("div",{children:[t.jsx("h3",{className:"m-0 text-lg font-extrabold",children:v?af():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Vm(e)}),v&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:La()})]}),t.jsx("button",{onClick:f,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:t.jsx(wt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!v&&t.jsx("button",{onClick:d,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),v?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[t.jsx("input",{type:"text",value:M.textQuery,onChange:b=>y({...M,textQuery:b.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:M.workspaceQuery,onChange:b=>y({...M,workspaceQuery:b.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:M.modelQuery,onChange:b=>y({...M,modelQuery:b.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsxs("select",{value:M.sortMode,onChange:b=>y({...M,sortMode:b.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:M.resumableOnly,onChange:b=>y({...M,resumableOnly:b.target.checked})}),"Resume-ready only"]})]}),C.map(b=>{const E=e.providerSessionId===b.providerSessionId,A=E||!b.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{A||!k||k(b)},disabled:A,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${E?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${A?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:`font-bold text-sm mb-1 truncate ${E?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:b.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:b.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:df(b.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:b.preview||"No saved preview yet"}),t.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[t.jsxs("div",{className:"truncate",children:[b.workspace||"Workspace unknown",ds(b.summaryMetadata)?` · ${ds(b.summaryMetadata)}`:"",b.messageCount>0?` · ${b.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:E?"ACTIVE":b.canResume?c===b.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},b.id)})]}):p.map(b=>t.jsxs("div",{onClick:()=>{h(e.routeId,b.id),f()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===b.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[t.jsx("div",{className:`font-bold text-sm mb-1 ${x===b.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:b.title||"Untitled Session"}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[b.id.substring(0,12),"..."]}),x===b.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},b.id)),(v&&!i&&C.length===0||!v&&p.length===0)&&t.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[t.jsx("div",{className:"text-3xl mb-3 opacity-60",children:t.jsx(Td,{size:32})}),t.jsx("div",{className:"text-[13px]",children:v?a.length>0?"No saved history matches these filters.":of():"No recent chat sessions found."})]}),v&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:lf()})})]}),t.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:t.jsx("button",{onClick:m,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(er,{size:13})," ",v?cf():"Refresh History"]})})})]})]});return typeof document>"u"?j:zs.createPortal(j,document.body)}const Mo={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 pc({toasts:e,onDismiss:s,onClickToast:r}){return t.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=Mo[n.type]||Mo.info;return t.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:[t.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))`}}),t.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(),s(n.id)},"aria-label":"Dismiss",children:t.jsx(wt,{size:14})}),t.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[t.jsx("div",{className:"flex items-center gap-2 pr-8",children:t.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})}),t.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&t.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>t.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(),s(n.id)},children:i.label},c))})]})]},n.id)})})}const uf=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function mf(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function ff(e){return e.sessionId||e.instanceId||e.agentType}function yn(e,s){return e||s}function hc(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=At(r,{fallbackId:r.id}));return s}function xc(e,s={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=s.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function Da(e,s={}){return pf(e,xc(e,s))}function pf(e,s={}){var d,h,m,k,S,p;const r=[],n=s.machineName,a=s.connectionState,i=mf(e),c=hu(e.type,{agentName:e.cliName}),l=Je(e)||qe(e)?c:et(e.type),u=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var v,g;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||et(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((v=x.activeChat)==null?void 0:v.messages)||[],activeModal:((g=x.activeChat)==null?void 0:g.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,surfaceHidden:x.surfaceHidden}}):[],f=uf(e);if(f){const x=e.sessionId||e.instanceId,v=c,g=(d=e.activeChat)==null?void 0:d.activeModal,N=g&&Array.isArray(g.buttons)&&g.buttons.length>0,M=bt((h=e.activeChat)==null?void 0:h.status,{activeModal:(m=e.activeChat)==null?void 0:m.activeModal})||bt((S=(k=e.agents)==null?void 0:k[0])==null?void 0:S.status)||"idle",y=e.activeChat||{title:"",messages:[]};let C=y.title&&String(y.title).trim()?String(y.title).trim():"";const j=(p=e.activeChat)==null?void 0:p.id,w=e.chats;if(j&&Array.isArray(w)&&w.length>0){const I=w.find(P=>P.id===j||P.id&&String(P.id)===String(j));I!=null&&I.title&&String(I.title).trim()&&(C=String(I.title).trim())}const b=(Je(e)||qe(e),e.type),E=(Je(e)||qe(e))&&bo(C,v,b)?"":C,A=y.messages||[];r.push({routeId:e.id,sessionId:x,providerSessionId:e.providerSessionId,nativeSessionId:x,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:Je(e)?e.mode||"terminal":"chat",agentName:v,agentType:b,status:M,title:E,messages:A,resume:e.resume,hostIdeType:!Je(e)&&!qe(e)?e.type:void 0,workspaceName:i,displayPrimary:E||i||(Je(e)?e.mode==="chat"?v:"Terminal":v),displaySecondary:l,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:N?g.buttons:void 0,modalMessage:N?g.message:void 0,streamSource:"native",tabKey:yn(x,e.id),machineName:n,connectionState:a})}if(f&&(Je(e)||qe(e)))return r;for(const x of u){const v=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,g=xu(x),N=ff(x),M=`${e.id}:${N}`,y=x.title&&String(x.title).trim()||"",C=bo(y,x.agentName,x.agentType)?"":y,j=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||j.length>0||v||C||!["idle","panel_hidden","disconnected","not_monitored"].includes(g))&&r.push({routeId:e.id,sessionId:x.sessionId||x.instanceId,providerSessionId:x.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:x.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:x.sessionCapabilities,mode:"chat",agentName:x.agentName,agentType:x.agentType,status:g,title:C,messages:j,hostIdeType:e.type,workspaceName:i,displayPrimary:C||i||x.agentName||l,displaySecondary:`${l} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,modalButtons:v?x.activeModal.buttons:void 0,modalMessage:v?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:yn(x.sessionId||x.instanceId,M),machineName:n,connectionState:a})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:i,displayPrimary:i||l,displaySecondary:l,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:yn(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function hf(e){const s=e.split(":");return s.length>=3&&(s[1]==="ide"||s[1]==="cli"||s[1]==="acp")?{daemonId:s[0],targetSessionId:s.slice(2).join(":")||void 0}:{daemonId:e}}function bc(e,s){const r=hf(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.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:"🏄"}],yc=[{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:"🧩"}],vc=[{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:"🟠"}],xf=gc,bf=yc,gf=vc;function ms(...e){return Ul(zl(e))}function yf({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:ms("dashboard-header",i),children:[t.jsxs("div",{children:[t.jsxs("h1",{className:"header-title flex items-center gap-2",children:[t.jsx("span",{className:"flex items-center text-lg",children:e})," ",s,n&&t.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&&t.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&t.jsx("div",{className:"flex gap-2",children:a})]})}function wc({icon:e,title:s,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx(yf,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:ms("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const na="adhdev:themechange";function vf(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function xs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function bs(e){return e==="system"?vf():e}function jc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Lr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(na,{detail:{preference:e,theme:s}}))}function wf(){const e=xs(),s=bs(e);jc(s),Lr(e,s)}function Ea(){const[e,s]=o.useState(xs),[r,n]=o.useState(()=>bs(xs()));o.useEffect(()=>{jc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const f=u.matches?"light":"dark";n(f),Lr("system",f)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const f=u.detail||{},d=f.preference,h=f.theme;s(d==="dark"||d==="light"||d==="system"?d:xs()),n(h==="dark"||h==="light"?h:bs(xs()))},l=u=>{if(u.key!=="theme")return;const f=xs(),d=bs(f);s(f),n(d)};return window.addEventListener(na,c),window.addEventListener("storage",l),()=>{window.removeEventListener(na,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=bs(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Lr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=bs(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Lr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const Ao={dark:"Dark",light:"Light",system:"System"};function jf({collapsed:e}){const{preference:s,cycleTheme:r}=Ea(),n=s==="dark"?t.jsx(Rd,{size:16}):s==="light"?t.jsx(Ld,{size:16}):t.jsx(Pd,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Ao[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:Ao[s]})]})}function vn(e,s){return e?typeof e=="function"?e(s):e:null}function kf({children:e,brand:s,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:u="sidebar-collapsed"}){const[f,d]=o.useState(!1),[h,m]=o.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),k=()=>d(!0),S=()=>d(!1),p=()=>{m(N=>{const M=!N;try{localStorage.setItem(u,M?"1":"0")}catch{}return M})},x=o.useMemo(()=>({collapsed:h,mobileMenuOpen:f,openMobileMenu:k,closeMobileMenu:S,toggleCollapsed:p}),[h,f]),v=N=>`nav-item${N.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${N.className?` ${N.className}`:""}`,g=N=>t.jsxs("div",{className:v(N),id:`nav-${N.id}`,onClick:()=>{N.onSelect(),S()},title:h?N.title??(typeof N.label=="string"?N.label:void 0):N.title,children:[t.jsx("span",{className:"nav-icon",children:N.icon}),!h&&N.label]},N.id);return t.jsxs("div",{className:`app-layout${f?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:k,children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),f&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:S,onKeyDown:N=>N.key==="Escape"&&S()}),t.jsxs("aside",{className:`sidebar ${f?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:vn(s,x)}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:S,children:t.jsx(wt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:r.map(g)}),n.map(N=>t.jsxs("div",{className:N.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&N.title?t.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:N.title}):null,N.items.map(g)]},N.key)),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(g),vn(i,x),t.jsx(jf,{collapsed:h}),vn(c,x)]})]}),t.jsx("main",{className:"main-content relative",children:t.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function Nt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:ms("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&t.jsxs("div",{className:"mb-4",children:[e&&t.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&t.jsx("span",{className:"mr-1.5",children:s}),e]}),r&&t.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function kc({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:ms("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[t.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),t.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),t.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Sf={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"},Nf={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function gr({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:ms("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Sf[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:Nf[e]}),t.jsx("span",{children:s})]}),r&&t.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const Cf={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"},If={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Mf({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:ms("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Cf[e],r),children:[t.jsx("span",{className:ms("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",If[e])}),n]})}function Qt({label:e,description:s,checked:r,disabled:n,onChange:a,extra:i}){return t.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[t.jsxs("div",{className:"pr-4",children:[t.jsx("div",{className:"font-medium text-sm",children:e}),t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,t.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:[t.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))"}}),t.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 Af({onPrefChange:e}){const[s,r]=Cu(),[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 t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Xr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:c=>i("globalEnabled",c)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ct,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:c=>i("browserNotifications",c)}),s.globalEnabled&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.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"&&t.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[t.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),t.jsx("button",{onClick:()=>{Oi().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"&&t.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"&&t.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."})]}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(_d,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:c=>i("completionAlert",c)}),t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Dd,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:c=>i("approvalAlert",c)}),t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ys,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function zr(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Tf(e,s){const r=zr(e),n=zr(s);if(!r||!n)return e.localeCompare(s);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 Sc(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function Hs(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Tf(r,s)>=0)return!1;const n=zr(r),a=zr(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Lf(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function wn(e,s){return e instanceof Error?e.message:s}function Rf({ides:e,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?t.jsx(kc,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:s||"Install ADHDev on a machine and sign in to connect it here."}):t.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>t.jsx(_f,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function To({title:e,message:s,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 zs.createPortal(t.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:t.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:[t.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),t.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.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"}),t.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 Pf(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...xf,...bf,...gf].find(a=>a.id===s||s.includes(a.id)||a.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function _f({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var O,V;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[f,d]=o.useState(null),[h,m]=o.useState("idle"),[k,S]=o.useState(""),p=e.version||null,x=((O=e.machine)==null?void 0:O.platform)||((V=e.system)==null?void 0:V.platform)||"",v=At(e,{fallbackId:e.id}),g=x==="win32"?"🪟":x==="darwin"?"🍎":"🐧",N=s.filter(L=>L.daemonId===e.id&&L.transport==="cdp-page"),M=s.filter(L=>L.daemonId===e.id&&L.transport==="pty"),y=s.filter(L=>L.daemonId===e.id&&L.transport==="acp"),C=e.p2p,j=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const L=Lf(await r(e.id,"daemon_upgrade",{}));L.alreadyLatest?(c("done"),u(`Already on v${L.version||"latest"}.`)):L.upgraded||L.success?(c("done"),u(`Upgrade to v${L.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(L.error||"Upgrade failed"))}catch(L){c("error"),u(wn(L,"Connection lost during upgrade"))}}},w=async()=>{if(d(null),!!n){m("loading");try{await n(e.id),m("done"),S("Machine disconnected.")}catch(L){m("error"),S(wn(L,"Failed to disconnect"))}}},b=async()=>{if(d(null),!!a){m("loading");try{await a(e.id),m("done"),S("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(L){m("error"),S(wn(L,"Failed to revoke token"))}}},E="0.9.13",A=Sc(e,E),I=Hs(e,E),P=N.length+M.length+y.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"text-xl",children:g}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:v}),t.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[t.jsxs("span",{children:[e.id.substring(0,12),"…"]}),p&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${A?"":"bg-bg-secondary"}`,style:A?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!A&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&A&&t.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${E}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${I?"↑ Update now":`↑ Update${` to v${E}`}`}`}),n&&t.jsx("button",{onClick:()=>d("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&t.jsx("button",{onClick:()=>d("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(Mf,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[C&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${C.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${C.state==="connecting"||C.state==="new"?"animate-pulse":""}`,style:C.state==="connecting"||C.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",C.state==="connected"?"connected":C.state==="connecting"||C.state==="new"?"connecting...":C.state||"off"]}),C.peers!==void 0&&C.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",C.peers," peer",C.peers!==1?"s":"",")"]})]}),C&&P>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),P>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(L=>{const R=Pf(L.type),G=L.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:R.icon}),t.jsx("span",{children:R.name}),G!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${G?"bg-green-400":"animate-pulse"}`,style:G?void 0:{background:"var(--status-warning)"},title:G?"CDP connected":"CDP connecting..."})]},L.id)}),M.map(L=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:L.cliName||"CLI"})]},L.id)),y.map(L=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:L.cliName||"ACP"})]},L.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||k)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-red-400":i==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:k||l})]}),f==="disconnect"&&t.jsx(To,{title:"🔌 Disconnect Machine",message:`Disconnect "${v}" from ADHDev?
|
|
32
|
+
|
|
33
|
+
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
34
|
+
|
|
35
|
+
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:w,onCancel:()=>d(null)}),f==="revoke"&&t.jsx(To,{title:"⚠️ Remove Machine",message:`Remove "${v}" from your dashboard?
|
|
36
|
+
|
|
37
|
+
This will:
|
|
38
|
+
• Immediately disconnect the machine
|
|
39
|
+
• Delete the machine registration
|
|
40
|
+
• Require restarting ADHDev on that machine
|
|
41
|
+
|
|
42
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:b,onCancel:()=>d(null)})]})}const Df=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Ef(){const{preference:e,setPreference:s}=Ea();return t.jsx("div",{className:"flex gap-2",children:Df.map(r=>t.jsxs("button",{onClick:()=>s(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:[t.jsx("span",{children:r.icon}),r.label]},r.id))})}function $f(e){const s=e.trim();return/^#[0-9a-fA-F]{6}$/.test(s)?s:/^#[0-9a-fA-F]{3}$/.test(s)?`#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`:null}function Bf(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function jn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function Lo(e){const{r:s,g:r,b:n}=Bf(e);return .2126*jn(s)+.7152*jn(r)+.0722*jn(n)}function Ro(e,s){const r=Lo(e),n=Lo(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Nc(e){const s=$f(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return Ro(s,r)>=Ro(s,n)?r:n}const aa={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},oa={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},Kf=[{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"}}}],Cc="adhdev-chat-theme",Ic="adhdev-chat-theme-custom";function Rr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Cc)||"ember"}catch{return"ember"}}function Pt(e){try{const s=localStorage.getItem(Ic);if(s){const r=JSON.parse(s);return{...e==="dark"?aa:oa,...r[e]}}}catch{}return e==="dark"?aa:oa}function yr(e,s){try{localStorage.setItem(Ic,JSON.stringify({dark:e,light:s}))}catch{}}function It(e,s){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}, ${s})`}function Vr(e,s){const r=Math.min(255,parseInt(e.slice(1,3),16)+s),n=Math.min(255,parseInt(e.slice(3,5),16)+s),a=Math.min(255,parseInt(e.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const Of={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Fs(e,s){var a;const r=(a=Of[e])==null?void 0:a[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Vr(r,24)),n.style.setProperty("--accent-on-primary",Nc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Vr(r,18)})`),n.style.setProperty("--border-accent",It(r,.35)),n.style.setProperty("--nav-active-bg",It(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${It(r,.06)}`)}function ns(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",It(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",It(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",It(e.borderSubtle,.25)),s.style.setProperty("--text-primary",e.textPrimary),s.style.setProperty("--text-secondary",e.textSecondary),s.style.setProperty("--text-muted",e.textMuted),s.style.setProperty("--border-subtle",It(e.borderSubtle,.5)),s.style.setProperty("--border-default",It(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",Vr(e.accentColor,30)),s.style.setProperty("--accent-on-primary",Nc(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Vr(e.accentColor,40)})`),s.style.setProperty("--border-accent",It(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",It(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${It(e.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",e.userBubble),s.style.setProperty("--chat-user-color",e.userText),s.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",e.assistantBubble),s.style.setProperty("--chat-assistant-color",e.assistantText),s.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${It(e.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",e.containerBg),s.style.setProperty("--dashboard-pane-bg",e.containerBg),s.style.setProperty("--chat-thought-accent",e.accentColor),s.style.setProperty("--chat-tool-accent",e.accentColor),s.style.setProperty("--chat-action-color",e.accentColor),s.style.setProperty("--chat-send-bg",e.sendButton),s.style.setProperty("--chat-input-border",e.inputBorder)}function $a(){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 Wf(e){try{localStorage.setItem(Cc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=as()?"dark":"light";ns(Pt(s))}else $a(),Fs(e,as()?"dark":"light")}function Hf(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Rr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=as()?"dark":"light";ns(Pt(s))}else $a(),Fs(e,as()?"dark":"light")}function as(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function xt({label:e,value:s,onChange:r}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),t.jsx("input",{type:"text",value:s,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 Ps({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.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}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function Ff({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Pt(r));o.useEffect(()=>{a(Pt(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const f={...u,[c]:l},h=Pt(r==="dark"?"light":"dark");return r==="dark"?yr(f,h):yr(h,f),ns(f),s(f),f})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.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",t.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"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(Ps,{title:"App Background",children:[t.jsx(xt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(xt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(xt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(Ps,{title:"App Text",children:[t.jsx(xt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(xt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(xt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(Ps,{title:"Borders & Accent",children:[t.jsx(xt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(xt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(xt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(Ps,{title:"Chat Bubbles",children:[t.jsx(xt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(xt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(xt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(xt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(Ps,{title:"Chat Layout",children:[t.jsx(xt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(xt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(xt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[t.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)"}}),t.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),t.jsx("button",{onClick:()=>{const c=e?aa:oa,u=Pt(e?"light":"dark");e?yr(c,u):yr(u,c),a(c),ns(c),s(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 Uf(){const[e,s]=o.useState(Rr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Pt("dark"));o.useEffect(()=>{n(as());const u=new MutationObserver(()=>{const h=as();n(h);const m=Rr();m==="custom"?ns(Pt(h?"dark":"light")):Fs(m,h?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const h=as();n(h);const m=Rr();m==="custom"?ns(Pt(h?"dark":"light")):Fs(m,h?"dark":"light")};return f.addEventListener("change",d),()=>{u.disconnect(),f.removeEventListener("change",d)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ns(Pt(r?"dark":"light")):($a(),Fs(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Pt(r?"dark":"light"))},[r]);const c=u=>{s(u),Wf(u)},l=[...Kf,{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 t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const f=e===u.id,d=r?u.preview.dark:u.preview.light,h=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:d.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.userBubble,color:h},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[f&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&t.jsx(Ff,{dark:r,onColorsChange:u=>i(u)})]})}const Ba="adhdev_mobileDashboardMode_v1",ia="adhdev:mobile-dashboard-mode-change";function Ka(){try{return localStorage.getItem(Ba)==="workspace"?"workspace":"chat"}catch{return"chat"}}function zf(e){if(typeof window>"u")return()=>{};const s=a=>{e(a??Ka())},r=a=>{const i=a.detail;s(i)},n=a=>{a.key&&a.key!==Ba||s()};return window.addEventListener(ia,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ia,r),window.removeEventListener("storage",n)}}function Vf(e){try{localStorage.setItem(Ba,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ia,{detail:e}))}function Gf(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(Ka()==="chat")},[]),t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ft,{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=>{s(r),Vf(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const kn=new Map,Po=new Map;function qf(e){if(!e||typeof e!="object")return null;const s=e,r=s.result&&typeof s.result=="object"?s.result:s,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function Yf(e,s,r,n){return{...e||{},id:s,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 Mc(){const{sendCommand:e}=jt(),{injectEntries:s,getIdes:r}=Gs();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??um,c=Po.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=kn.get(n);if(l)return l;const u=(async()=>{const f=await e(n,"get_machine_runtime_stats"),d=qf(f);if(!d)return;const h=r().find(k=>k.id===n),m=Yf(h,n,d.machine,d.timestamp||Date.now());s([m]),Po.set(n,Date.now())})().finally(()=>{kn.delete(n)});return kn.set(n,u),u},[r,s,e])}function Xf(e,s,r){return{...e||{},id:s,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 Jf(e,s){const{sendData:r}=jt(),{injectEntries:n,getIdes:a}=Gs(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>qt.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},d=>{const h=a().find(k=>k.id===u),m=Xf(h,u,d);n([m])}));return()=>{l.forEach(u=>u())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}function Qf(e,s){const{sendData:r}=jt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const u=qt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},f=>{l&&(clearTimeout(l),l=null),a(f.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},hm):c(!1),()=>{l&&clearTimeout(l),u()}},[e,s==null?void 0:s.enabled,s==null?void 0:s.includeSessions,s==null?void 0:s.intervalMs,s==null?void 0:s.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:a}}function Zf(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Ac(e){const{sendData:s}=jt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=Zf(e);if(!a||!e.sessionId||!s){n({});return}const i=qt.subscribe({sendData:s},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}),ks.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,s]),r}const Tc="adhdev_hiddenTabs";function ep(){try{const e=localStorage.getItem(Tc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ps(e){try{localStorage.setItem(Tc,JSON.stringify([...e]))}catch{}}function Sn(e){return Na(e)}function Oa(e,s){return ws(s).some(r=>e.has(r))}function tp(){const[e,s]=o.useState(ep),r=o.useCallback(f=>{const d=Sn(f);s(h=>{const m=new Set(h);return m.has(d)?m.delete(d):m.add(d),ps(m),m})},[]),n=o.useCallback(f=>{const d=Sn(f);s(h=>{if(h.has(d))return h;const m=new Set(h);return m.add(d),ps(m),m})},[]),a=o.useCallback(f=>{const d=Sn(f);s(h=>{if(!h.has(d))return h;const m=new Set(h);return m.delete(d),ps(m),m})},[]),i=o.useCallback(()=>{s(f=>{if(f.size===0)return f;const d=new Set;return ps(d),d})},[]),c=o.useCallback((f,d)=>{s(h=>{const m=new Set(h);for(const k of d)m.add(k);return ps(m),m})},[]),l=o.useCallback((f,d)=>{s(h=>{const m=new Set(h);for(const k of d)m.delete(k);return ps(m),m})},[]),u=o.useCallback(f=>Oa(e,f),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Lc(e){return e instanceof Error?e.message:String(e||"")}function Rc(e){const s=Lc(e);return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("P2P channel not open")||s.includes("P2P not available")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function Pc(e){const s=Lc(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}async function _c({conversation:e,mode:s,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Je(e)||qe(e))return;const i=Ts(e);if(i===s)return;const c=e.sessionId;c&&a(l=>({...l,[c]:s}));try{await n(fs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Kt(e),mode:s})}catch(l){const u=Pc(l);c&&!u&&a(f=>{const d={...f};return i===Dc(r,c)?delete d[c]:d[c]=i,d}),Rc(l)?console.warn(u?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function _o(e,s){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=s[r];return!n||e.mode===n?e:{...e,mode:n}}function sp(e,s){if(!Array.isArray(e)||e.length===0||!s||Object.keys(s).length===0)return e;let r=!1;const n=e.map(a=>{const i=_o(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>_o(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Dc(e,s){if(!s)return null;for(const r of e){if(r.sessionId===s&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===s&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function rp(e,s){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))Dc(s,a)===i&&(delete n[a],r=!0);return r?n:e}function np({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Oi()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:cc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Au(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),f={};for(const[d,h]of Object.entries(l))u-h<5e3&&(f[d]=h);return Object.keys(f).length===Object.keys(l).length?l:f})},5500);return()=>clearTimeout(c)},[s,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(f=>f.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function ap(e){const s=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of s){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 Nn(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function op(e){let s=2166136261;for(let r=0;r<e.length;r+=1)s^=e.charCodeAt(r),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}function Do(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?op(Vs(r.content)):"";return[e.id||"",e.title||"",e.status||"",s.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 ip(e){const s=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||""),Do(e.activeChat),...s.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||""),Do(r.activeChat)].join(":"))].join("|")}function cp(e,s){const r=Date.now();return e.map(n=>{const a=s[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function lp(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of ws({routeId:n.routeId}))r.set(i,a);for(const i of ws({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of ws({tabKey:n.tabKey}))r.set(i,n)}return r}function dp(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function up(e){const s=dp(e);if(!s)return`empty:${e.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=Vs(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function mp({ides:e,connectionStates:s,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>ap(e),[e]),i=o.useMemo(()=>hc(e),[e]),c=o.useRef([]),l=o.useRef([]),u=o.useRef([]),f=o.useRef(new Map),d=o.useRef(new Map),h=o.useMemo(()=>{const M=new Map,y=[];for(const b of a){const{connectionState:E="new",machineName:A}=xc(b,{machineNames:i,connectionStates:s,defaultConnectionState:"new"}),I=ip(b),P=f.current.get(b.id);if(P&&P.ide===b&&P.sourceSignature===I&&P.connectionState===E&&P.machineName===A){M.set(b.id,P),y.push(...P.conversations);continue}const O=Da(b,{machineNames:i,connectionStates:s,defaultConnectionState:"new"}),V={ide:b,sourceSignature:I,connectionState:E,machineName:A,conversations:O};M.set(b.id,V),y.push(...O)}f.current=M;const C=new Map,j=b=>{const E=up(b),A=d.current.get(b.tabKey);if(A&&A.signature===E)return C.set(b.tabKey,A),A.timestamp;const I={signature:E,timestamp:Yi(b)||(A==null?void 0:A.timestamp)||0};return C.set(b.tabKey,I),I.timestamp},w=[...y].sort((b,E)=>Xi(b,E,j));return d.current=C,w},[a,s,i]),m=o.useMemo(()=>{const M=cp(h,r);return Nn(c.current,M)?c.current:(c.current=M,M)},[h,r]),k=o.useMemo(()=>{const M=new Map,y=Array.from(new Set(m.map(C=>C.routeId)));for(const C of y){const j=_t(m,C);j&&M.set(C,j)}return M},[m]),S=o.useMemo(()=>{const M=new Map;for(const y of m){const C=k.get(y.routeId),j=y.streamSource==="native"&&C?C:y;for(const w of ws({providerSessionId:y.providerSessionId,sessionId:y.sessionId}))M.set(w,j)}return M},[m,k]),p=o.useMemo(()=>lp(m,k),[m,k]),x=o.useCallback(M=>{if(M)return S.get(M)},[S]),v=o.useCallback(M=>{if(M)return p.get(M)},[p]),g=o.useMemo(()=>{const M=m.filter(y=>!Oa(n,y));return Nn(l.current,M)?l.current:(l.current=M,M)},[m,n]),N=o.useMemo(()=>{const M=g.map(y=>y.tabKey);return Nn(u.current,M)?u.current:(u.current=M,M)},[g]);return{chatIdes:a,conversations:m,visibleConversations:g,visibleTabKeys:N,resolveConversationBySessionId:x,resolveConversationByTarget:v}}function fp({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),i=o.useMemo(()=>{var l;return!e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),c=o.useCallback(()=>{s&&n(l=>{const u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,s]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function pp({ides:e,sendDaemonCommand:s,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{dt.setIdes(e)},[e]),o.useEffect(()=>{dt.setResolveAction((a,i,c)=>{s(a,i,c).catch(()=>{})})},[s]),o.useEffect(()=>{const a=dt.onToast(i=>{r(l=>l.some(f=>f.message===i.message&&i.timestamp-f.timestamp<3e3)?l:[...l.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions}]);const c=i.duration||5e3;setTimeout(()=>r(l=>l.filter(u=>u.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=ac.on("status_event",i=>{dt.handleRawEvent(i,"ws")});return()=>{a()}},[]),o.useEffect(()=>{var i;const a=c=>{var p;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const u=l.targetSessionId||l.targetKey||l.daemonId,f=n(u),d=(f==null?void 0:f.routeId)||l.daemonId;if(!d)return;const h=Number(l.buttonIndex),m=l.button||((p=f==null?void 0:f.modalButtons)==null?void 0:p[h])||"Approve",k=String(m).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(k);s(d,"resolve_action",{action:S?"approve":"reject",button:m,...Number.isFinite(h)&&{buttonIndex:h},...(f==null?void 0:f.sessionId)&&{targetSessionId:f.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};return(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,s])}const hp="adhdev_dashboardLayout_v1",xp="adhdev_dashboardDockview_v1",bp="adhdev_dashboardDockviewHiddenRestore_v1",_s={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Wa(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function gp(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Ec(e){return`${hp}:${e}`}function yp(e){const s=Ec(e);return Wa(s,null)}function vp(e,s){try{const r=s.groupAssignments.length===0&&s.focusedGroup===0&&Object.keys(s.groupActiveTabIds).length===0&&Object.keys(s.groupTabOrders).length===0&&s.groupSizes.length===0,n=Ec(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function $c(e){return`${xp}:${e}`}function wp(e){const s=$c(e);return Wa(s,null)}function jp(e,s){try{const r=$c(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Bc(e){return`${bp}:${e}`}function kp(e){const s=Bc(e);return Wa(s,{})}function Sp(e,s){try{const r=Bc(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Np(){return{groupAssignments:[..._s.groupAssignments],focusedGroup:_s.focusedGroup,groupActiveTabIds:{..._s.groupActiveTabIds},groupTabOrders:{..._s.groupTabOrders},groupSizes:[..._s.groupSizes]}}function Cp(e,s){return e?e.length===s.length&&e.every((r,n)=>r===s[n]):s.length===0}function Ip(){const[e]=o.useState(()=>gp(typeof window<"u"?window.innerWidth:1280)),[s,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[f,d]=o.useState([]),[h,m]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[k,S]=o.useState(!1),p=o.useCallback(()=>{if(k)return;const b=yp(e)??Np();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),u(b.groupTabOrders),d(b.groupSizes),S(!0)},[k,e]);o.useEffect(()=>{k&&vp(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:f})},[k,e,s,n,i,l,f]),o.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),E=A=>m(A.matches);return b.addEventListener("change",E),()=>b.removeEventListener("change",E)},[]);const x=o.useCallback(b=>{r(b)},[]),v=o.useCallback(b=>{a(b)},[]),g=o.useCallback(b=>{c(b)},[]),N=o.useCallback(b=>{u(b)},[]),M=o.useCallback(b=>{d(b)},[]),y=o.useCallback(b=>{v(b)},[v]),C=o.useCallback((b,E)=>{c(A=>(A[b]??null)===(E??null)?A:{...A,[b]:E})},[]),j=o.useCallback((b,E)=>{u(A=>{const I=A[b];return Cp(I,E)?A:{...A,[b]:E}})},[]),w=o.useCallback((b,E)=>{const A=E.get(b)??0;return C(A,b),y(A),A},[y,C]);return{layoutProfile:e,groupAssignments:s,updateGroupAssignments:x,focusedGroup:n,updateFocusedGroup:v,focusGroup:y,groupActiveTabIds:i,updateGroupActiveTabIds:g,setGroupActiveTab:C,groupTabOrders:l,updateGroupTabOrders:N,setGroupTabOrder:j,groupSizes:f,updateGroupSizes:M,isMobile:h,hasHydratedStoredLayout:k,hydrateStoredLayout:p,focusConversationTab:w}}function Mp(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=Sa(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Ap({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:u,activeConv:f,isRefreshingHistory:d,ides:h,handleRefreshHistory:m}){const k=o.useRef(!1),S=o.useRef(!1),p=o.useRef(null),x=o.useRef(!1);o.useEffect(()=>{if(!e||k.current||s.length===0)return;if(!a){i();return}const v=r(e);v&&(c(v.tabKey,n),k.current=!0,S.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(g=>{const N=new URLSearchParams(g);return N.delete("activeTab"),N},{replace:!0}))},[e,s,r,n,a,i,c,l]),o.useEffect(()=>{if(!(S.current||a)&&s.length!==0){if(!e){i(),S.current=!0;return}if(k.current){S.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(S.current||a)&&(i(),S.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!u){x.current=!1;return}if(!f||x.current||d)return;const v=h.find(g=>g.id===f.routeId);v&&(!v.chats||v.chats.length===0||Mp(v.chats,f))&&(x.current=!0,m())},[u,f,d,h,m]),o.useEffect(()=>{if(!f)return;let v=null,g=0,N=-1,M=0;const y=()=>{v=null;const C=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(w=>w.offsetParent!==null);if(C.length===0){g<18&&(g+=1,v=requestAnimationFrame(y));return}let j=0;for(const w of C)w.scrollTop=w.scrollHeight,j+=w.scrollHeight;j===N?M+=1:(M=0,N=j),g+=1,!(M>=2||g>=18)&&(v=requestAnimationFrame(y))};return v=requestAnimationFrame(y),()=>{v!=null&&cancelAnimationFrame(v)}},[f==null?void 0:f.tabKey])}function Cn(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=Sa(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Kc({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[u,f]=o.useState(!1),d=o.useCallback(async S=>{try{await e("standalone","launch_ide",{ideType:S,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=o.useCallback(async(S,p)=>{try{const x=S||(s==null?void 0:s.daemonId)||"",v=await e(x,"switch_chat",{id:p,sessionId:p,...js(s)}),g=v==null?void 0:v.result;if((v==null?void 0:v.success)===!0||g==="switched"||g==="switched-by-title")return;g===!1||g==="not_found"?Rs(a,"⚠️ Session tab not found — try refreshing history"):typeof g=="string"&&g.startsWith("error:")?Rs(a,`⚠️ Switch error: ${g}`):Rs(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Rs(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[s,e,a]),m=o.useCallback(async()=>{if(!(!s||c)){l(!0);try{const S=Js(s);await e(S,"new_chat",{...js(s)}),i(p=>({...p,[s.tabKey]:Date.now()}))}catch(S){console.error("New chat failed",S)}finally{l(!1)}}},[s,c,e,i]),k=o.useCallback(async()=>{var S,p;if(!(!s||u)){f(!0);try{const x=Js(s),v=async()=>e(x,"list_chats",{forceExpand:!0,...js(s)});let g=await v(),N=(g==null?void 0:g.chats)||((S=g==null?void 0:g.result)==null?void 0:S.chats);Cn(N,s)&&(await new Promise(M=>setTimeout(M,450)),g=await v(),N=(g==null?void 0:g.chats)||((p=g==null?void 0:g.result)==null?void 0:p.chats)),g!=null&&g.success&&Array.isArray(N)&&(n(s.routeId,N),Cn(N,s)&&!Cn(r,s)&&Rs(a,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{f(!1)}}},[s,r,u,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:h,handleNewChat:m,handleRefreshHistory:k}}function Tp(e,s){if(e.size!==s.size)return!1;for(const[r,n]of e)if(s.get(r)!==n)return!1;return!0}function Lp(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function Eo(e,s){const r=Object.keys(e),n=Object.keys(s);return r.length!==n.length?!1:r.every(a=>s[Number(a)]===e[Number(a)])}function vr(e,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const u=a[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function $o(e,s){const r={};for(const[n,a]of Object.entries(e)){const i=s[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function Rp(e,s,r){if(s.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...s].reverse().find(a=>a<e)??s[0];return r[n]??0}function Pp(e,s,r){if(s.length<=1)return[];const n=s.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===s.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 Bo(e,s){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=s?i+1:i]=a}return r}function Ko(e){return Array(e).fill(100/e)}function _p({groupAssignments:e,updateGroupAssignments:s,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:f}){const d=o.useRef(null),h=o.useMemo(()=>vr(e,f),[e,f]),m=h.assignments,k=o.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),S=k>1,p=o.useCallback((y,C)=>{s(j=>{const w=new Map(vr(j,f).assignments);return C===0?w.delete(y):w.set(y,C),w}),n(j=>({...j,[C]:y})),r(C)},[s,f,n,r]),x=o.useCallback(y=>{s(C=>{const j=vr(C,f).assignments,w=new Map;for(const[b,E]of j)E!==y&&(E>y?w.set(b,E-1):w.set(b,E));return w}),c(C=>{if(C.length<=1)return[];const j=[...C];j.splice(y,1);const w=j.reduce((b,E)=>b+E,0);return w>0?j.map(b=>b/w*100):[]}),r(0)},[s,f,c,r]),v=o.useCallback((y,C)=>{C.preventDefault();const j=d.current;if(!j)return;const w=C.clientX,b=j.offsetWidth,E=i.length===k?[...i]:Ko(k),A=P=>{const V=(P.clientX-w)/b*100,L=[...E];L[y]=Math.max(15,E[y]+V),L[y+1]=Math.max(15,E[y+1]-V),c(L)},I=()=>{document.removeEventListener("mousemove",A),document.removeEventListener("mouseup",I),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",A),document.addEventListener("mouseup",I)},[i,k,c]),g=o.useCallback((y,C,j)=>{if(k>=4)return;const w=j==="left"?C:C+1;s(b=>{const E=vr(b,f).assignments,A=new Map;for(const I of u){const P=E.get(I.tabKey)??0,O=P>=w?P+1:P;O>0&&A.set(I.tabKey,O)}return w>0&&A.set(y,w),A}),c(b=>{const E=b.length===k?[...b]:Ko(k),A=E[C]??100/k,I=Math.max(15,A/2),P=Math.max(15,A/2),O=[...E];O[C]=I,O.splice(w,0,P);const V=O.reduce((L,R)=>L+R,0);return O.map(L=>L/V*100)}),n(b=>{const E=Bo(b,w);return E[w]=y,E}),a(b=>{const E=Bo(b,w);return E[w]=[y],E}),r(w)},[k,s,f,u,c,n,a,r]);o.useEffect(()=>{Tp(e,m)||s(m)},[e,m,s]),o.useEffect(()=>{const{mapping:y,usedGroups:C}=h;n(j=>{const w=$o(j,y);return Eo(j,w)?j:w}),a(j=>{const w=$o(j,y);return Eo(j,w)?j:w}),r(j=>{const w=l?0:Rp(j,C,y);return j===w?j:w}),c(j=>{const w=l?[]:Pp(j,C,h.groupCount);return Lp(j,w)?j:w})},[h,l,n,a,r,c]);const N=o.useMemo(()=>{const y=Array.from({length:k},()=>[]);for(const C of u){const j=m.get(C.tabKey)??0,w=Math.min(j,k-1);y[w].push(C)}return y},[u,m,k]),M=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:d,normalizedGroupAssignments:m,numGroups:k,isSplitMode:S,groupedConvs:N,moveTabToGroup:p,closeGroup:x,handleResizeStart:v,splitTabRelative:g,clearAllSplits:M}}function Dp({ides:e,sendDaemonCommand:s}){const r="0.9.13",n=o.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:Sc(d,r)).sort((d,h)=>Number(Hs(h,r))-Number(Hs(d,r))),[r,e]),a=o.useMemo(()=>n.some(d=>Hs(d,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),f=o.useCallback(async d=>{var h,m;u(k=>({...k,[d]:"upgrading"}));try{const k=await s(d,"daemon_upgrade",{});(h=k==null?void 0:k.result)!=null&&h.upgraded||(m=k==null?void 0:k.result)!=null&&m.success?u(S=>({...S,[d]:"done"})):u(S=>({...S,[d]:"error"}))}catch{u(k=>({...k,[d]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}const Oc=80;function Pr(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function Ep(e){return{...e,createdAt:Pr(e.createdAt),updatedAt:Pr(e.updatedAt,e.createdAt),lastEventAt:Pr(e.lastEventAt,e.updatedAt||e.createdAt)}}function $p(e){const s=Na(e);return s==="unknown:"?e.id:s}function Bp(e){return[e.type,qi(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Kp(e,s=Oc){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=$p(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,s))}function Op(e,s){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?s.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=Qr(a,s),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const u=Pr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),f=Bp({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(Ep({id:f,dedupKey:f,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:zi(a),preview:Ju(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return Kp(n)}function Wp(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function Hp(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=Oc}=e,a=o.useMemo(()=>Op(s,r).slice(0,Math.max(0,n)),[s,r,n]),i=o.useMemo(()=>Wp(a),[a]);return{notifications:a,unreadCount:i}}function Fp({notifications:e,sendDaemonCommand:s}){const r=o.useCallback(i=>{const c=e.find(u=>u.id===i),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&s(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,s]),n=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&s(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,s]),a=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&s(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,s]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}function tn(...e){const s=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();s.has(c)||(s.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 Up(e){const s=e.trim();if(!s)return null;if(s.startsWith("~"))return s;if(/^[A-Za-z]:$/.test(s))return`${s[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(s))return`${s[0].toUpperCase()}:${s.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(s))return`${s[0].toUpperCase()}:\\${s.slice(2).replace(/[\\/]+/g,"\\")}`;const r=s.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function sn(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=Up(r);if(n)return n}return"C:\\"}for(const r of s){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function zp(e){const s=e.replace(/[\\/]+$/,"");if(!s||s==="/"||/^[A-Za-z]:$/.test(s))return null;const r=s.includes("\\")?"\\":"/",n=s.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 Vp(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function rn(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=Vp(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=(f,d)=>/^[A-Za-z]:\\?$/.test(f)?`${f.replace(/\\?$/,"\\")}${d}`:f==="/"||f==="\\"?`${c}${d}`:`${f.replace(/[\\/]+$/,"")}${c}${d}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(f=>(f==null?void 0:f.type)==="directory"&&typeof(f==null?void 0:f.name)=="string").map(f=>({name:f.name,path:typeof(f==null?void 0:f.path)=="string"&&f.path.trim()?f.path:l(i,f.name)})).sort((f,d)=>f.name.localeCompare(d.name)):[];return{path:i,directories:u}}function Gp(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Oo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function qp(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Yp({ides:e,conversations:s,onOpenSession:r}){const[n,a]=o.useState(null),i=o.useCallback(c=>{a(c)},[]);return o.useEffect(()=>{if(!n)return;const c=Oo(n.workspacePath),l=e.find(f=>{var S,p,x,v;if(!f||f.type==="adhdev-daemon"||Gp(f.daemonId||f.id)!==n.machineId||(Xs(f)?"cli":ys(f)?"acp":"ide")!==n.kind||String(f.agentType||f.type||"")!==n.providerType)return!1;if(n.resumeSessionId)return String(f.providerSessionId||"")===n.resumeSessionId;if(c){const g=Oo(f.workspace||f.runtimeWorkspaceLabel);return g?g===c:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((v=(x=(p=(S=f.activeChat)==null?void 0:S.messages)==null?void 0:p.at)==null?void 0:x.call(p,-1))==null?void 0:v.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const u=Ji({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:s});u&&(a(null),r(u))},[s,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 Xp({sendDaemonCommand:e,trackPendingLaunch:s,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=o.useCallback(async(m,k)=>rn(e,m,k),[e]),l=o.useCallback(async(m,k)=>{if(!k.trim())return{ok:!1,error:"Choose a workspace path first."};try{const S=await e(m,"workspace_add",{path:k.trim()});return S!=null&&S.success?{ok:!0}:{ok:!1,error:(S==null?void 0:S.error)||"Could not save workspace"}}catch(S){return{ok:!1,error:S instanceof Error?S.message:"Could not save workspace"}}},[e]),u=o.useCallback(async(m,k,S)=>{var p;try{const x={ideType:k,enableCdp:!0};(p=S==null?void 0:S.workspacePath)!=null&&p.trim()&&(x.workspace=S.workspacePath.trim());const v=await e(m,"launch_ide",x);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(s({machineId:m,kind:"ide",providerType:k,workspacePath:(S==null?void 0:S.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Could not launch IDE"}}},[e,s]),f=o.useCallback(async(m,k,S,p)=>{var v,g,N;const x=Date.now();try{const M={cliType:S};(v=p==null?void 0:p.workspacePath)!=null&&v.trim()?M.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(M.workspaceId=p.workspaceId),(g=p==null?void 0:p.resumeSessionId)!=null&&g.trim()&&(M.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(M.cliArgs=p.cliArgs),(N=p==null?void 0:p.initialModel)!=null&&N.trim()&&(M.initialModel=p.initialModel.trim());const y=await e(m,"launch_cli",M),C=(y==null?void 0:y.result)||y,j=(C==null?void 0:C.sessionId)||(C==null?void 0:C.id);return y!=null&&y.success&&j?(r(j),{ok:!0}):y!=null&&y.success?(s({machineId:m,kind:k,providerType:S,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:x}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(C==null?void 0:C.error)||`Could not launch ${k.toUpperCase()} session`}}catch(M){return qp(M)?(s({machineId:m,kind:k,providerType:S,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:x}),{ok:!0}):{ok:!1,error:M instanceof Error?M.message:`Could not launch ${k.toUpperCase()} session`}}},[r,e,s]),d=o.useCallback(async(m,k)=>{if(!m||!k)return[];try{const S=await e(m,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),p=(S==null?void 0:S.result)??S;return Array.isArray(p==null?void 0:p.sessions)?p.sessions:[]}catch(S){return console.error("List saved sessions failed",S),[]}},[e]),h=o.useCallback(async m=>{await _c({conversation:n,mode:m,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:i})},[n,a,e,i]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:u,handleLaunchMachineProvider:f,handleListMachineSavedSessions:d,setActiveCliViewMode:h}}function Jp(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":return!0;case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function Qp(e,s,r=Date.now()){return!e||!Jp(s)?null:{tabKey:e,nonce:r}}function Zp({isMobile:e,conversations:s,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,u]=o.useState(null),[f,d]=o.useState(null),h=o.useMemo(()=>{var x,v;if(!e){if(l){const g=s.find(N=>N.tabKey===l);if(g)return g}return r[0]}const p=n[a];if(p){const g=s.find(N=>N.tabKey===p);if(g)return g}return((x=i[a])==null?void 0:x[0])||((v=i[0])==null?void 0:v[0])},[s,l,a,n,i,e,r]),m=o.useCallback(p=>{u(p)},[]),k=o.useCallback(p=>{u(p.tabKey),c(x=>{const v=new URLSearchParams(x),g=Zu(p);return g?v.set("activeTab",g):v.delete("activeTab"),v},{replace:!0})},[c]),S=o.useCallback((p,x)=>{const v=Qp(p,x);v&&d(v)},[]);return{activeConv:h,openDesktopConversation:k,requestScrollToBottom:S,scrollToBottomRequest:f,setDesktopActiveTab:m}}function eh({activeConv:e,remoteDialogConv:s,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:u}){var L;const[f,d]=o.useState(!1),[h,m]=o.useState([]),[k,S]=o.useState(()=>ht()),[p,x]=o.useState(!1),[v,g]=o.useState(null),N=o.useRef(null),M=o.useMemo(()=>r||s||e,[e,r,s]),y=!!M&&Je(M)&&!qe(M),C=o.useMemo(()=>{if(!M||!y)return null;const R=M.daemonId||M.routeId||"",G=Kt(M);return`${R}:${G}`},[M,y]),{isCreatingChat:j,isRefreshingHistory:w,handleSwitchSession:b,handleNewChat:E,handleRefreshHistory:A}=Kc({sendDaemonCommand:a,activeConv:M,chats:(L=n.find(R=>R.id===(M==null?void 0:M.routeId)))==null?void 0:L.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),I=o.useCallback(()=>{d(!0)},[]),P=o.useCallback(()=>{d(!1)},[]),O=o.useCallback(async()=>{if(!(!M||!y||p)){x(!0);try{const R=M.daemonId||M.routeId,G=Kt(M),B=await a(R,"list_saved_sessions",{agentType:G,providerType:G,kind:"cli",limit:50}),$=(B==null?void 0:B.result)??B;m(Array.isArray($==null?void 0:$.sessions)?$.sessions:[])}catch(R){console.error("Refresh saved sessions failed",R),m([])}finally{x(!1)}}},[M,p,y,a]);o.useEffect(()=>{if(!f){N.current=null;return}if(!y){N.current=null,m([]),x(!1);return}!C||p||N.current!==C&&(N.current=C,O())},[O,f,p,y,C]);const V=o.useCallback(async R=>{if(!M||!y||!R.providerSessionId||!R.workspace)return;const G=M.daemonId||M.routeId,B=Kt(M);try{g(R.providerSessionId);const $=await a(G,"launch_cli",{cliType:B,dir:R.workspace,resumeSessionId:R.providerSessionId,initialModel:Bi(R.summaryMetadata,"model",{preferShortValue:!0})||void 0}),H=($==null?void 0:$.result)??$,J=typeof(H==null?void 0:H.sessionId)=="string"?H.sessionId:typeof(H==null?void 0:H.id)=="string"?H.id:"";J&&u(xe=>{const me=new URLSearchParams(xe);return me.set("activeTab",J),me},{replace:!0}),P()}catch($){console.error("Resume saved session failed",$)}finally{g(null)}},[P,M,y,a,u]);return{historyModalOpen:f,openHistoryModal:I,closeHistoryModal:P,historyTargetConv:M,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:j,isHistoryRefreshingHistory:w,handleHistorySwitchSession:b,handleHistoryNewChat:E,handleHistoryRefresh:A,savedHistorySessions:h,savedHistoryFilters:k,setSavedHistoryFilters:S,isSavedHistoryLoading:p,resumingSavedHistorySessionId:v,handleRefreshSavedHistory:O,handleResumeSavedHistorySession:V}}function th({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,f]=o.useState(null),[d,h]=o.useState(null),m=o.useMemo(()=>{if(e||!n)return null;const v=l(n);return v&&!Je(v)&&!qe(v)?v:null},[e,n,l]),k=o.useMemo(()=>{const v=u==null?void 0:u.routeId;if(!v)return null;const g=u!=null&&u.tabKey?i.find(N=>N.tabKey===u.tabKey):a?i.find(N=>N.tabKey===a):null;return(g==null?void 0:g.routeId)===v?g:_t(i,v)},[i,u,a]),S=o.useMemo(()=>{if(k)return c.find(v=>v.id===k.routeId)},[c,k]);o.useEffect(()=>{m&&(f({routeId:m.routeId,tabKey:vo(m)}),h(m),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,m]);const p=o.useCallback(v=>{v&&(f({routeId:v.routeId,tabKey:vo(v)}),h(v))},[]),x=o.useCallback(()=>{f(null),h(null)},[]);return{remoteDialogConv:k,remoteDialogIdeEntry:S,remoteDialogActiveConv:d,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:x}}function sh({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:u,sendDaemonCommand:f}){const{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:m,setRemoteDialogActiveConv:k,openRemoteDialog:S,closeRemoteDialog:p}=th({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[x,v]=o.useState(!1),[g,N]=o.useState(null),M=o.useCallback(async j=>{const w=j||u;!w||!Je(w)&&!qe(w)||(N(w),v(!0))},[u]),y=o.useCallback(()=>{v(!1),N(null)},[]),C=o.useCallback(async j=>{const w=g||u;if(!w||!Je(w)&&!qe(w)){y();return}v(!1);try{const b=Kt(w),E=w.routeId||w.daemonId||"";await f(E,"stop_cli",{cliType:b,targetSessionId:w.sessionId,mode:j})}catch(b){console.error("Stop CLI failed:",b)}finally{N(null)}},[u,y,g,f]);return{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:m,setRemoteDialogActiveConv:k,openRemoteDialog:S,closeRemoteDialog:p,cliStopDialogOpen:x,cliStopTargetConv:g,requestCliStop:M,cancelCliStop:y,confirmCliStop:C}}function Wc(){return"select_session"}function rh(){return"open_panel"}function nh({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function ah(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function Wo(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function Ho(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ha(e){return e instanceof Error?e.message:String(e||"")}function Fo(e){const s=Ha(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Uo(e,s){const r=Ha(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function nn({sendDaemonCommand:e,activeConv:s,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[u,f]=o.useState(null),d=o.useRef(!1),h=o.useRef(null);o.useEffect(()=>{f(null)},[s==null?void 0:s.tabKey]);const m=o.useCallback(async x=>{if(!s)return!1;const v=x.trim(),g=Ia(s);if(nh({hasMessage:!!v,blockedMessage:g,sendInFlight:d.current}))return g&&f(g),!1;const N=Date.now(),M={tabKey:s.tabKey,message:v,timestamp:N};if(ah(h.current,M))return f(null),!0;d.current=!0,l(!0),f(null),h.current=M;try{const y=Js(s);if(!y)return h.current=Wo(h.current,M),f("Unable to send message right now."),!1;const C=await e(y,"send_chat",{message:v,...js(s)}),j=Ho(C);if(j!=null&&j.deduplicated)return f(null),!0;if((j==null?void 0:j.sent)===!1)throw new Error((j==null?void 0:j.error)||"Send failed");if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Send failed");return f(null),!0}catch(y){const C=Ha(y);return C.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",C):console.warn("Send blocked/failed",y),h.current=Wo(h.current,M),f(ym(y)),!1}finally{d.current=!1,l(!1)}},[s,e]),k=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(x){console.error("Relaunch failed",x)}},[s,e]),S=o.useCallback(async x=>{if(s)try{const g=(s.modalButtons||[]).indexOf(x),N=x.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),M=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),y=Js(s);if(!y)return;const C=await e(y,"resolve_action",{button:x,action:M?"approve":"reject",...g>=0&&{buttonIndex:g},...js(s)}),j=Ho(C);j.success||r(w=>[...w,{routeId:s.tabKey,text:Uo(x,j==null?void 0:j.error),timestamp:Date.now()}])}catch(v){Fo(v)||console.error("[ModalButton] Error:",v),r(g=>[...g,{routeId:s.tabKey,text:Fo(v)?Uo(x,v):`❌ **${x}** error`,timestamp:Date.now()}])}},[s,e,r]),p=o.useCallback(async()=>{if(!(!s||a)){i(!0);try{await e(s.routeId,rh(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(x){console.error("Focus agent failed",x)}finally{i(!1)}}},[s,a,e]);return{isSendingChat:c,sendFeedbackMessage:u,isFocusingAgent:a,handleSendChat:m,handleRelaunch:k,handleModalButton:S,handleFocusAgent:p}}const Fa=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d=null,handleFocusAgent:h,isFocusingAgent:m,actionLogs:k,userName:S,scrollToBottomRequestNonce:p,isInputActive:x=!0}){const[v,g]=o.useState(n),N=o.useRef(n);o.useEffect(()=>{const w=N.current;if(N.current=n,!n){g(!1);return}if(w){g(!0);return}g(!1);let b=0,E=0;return b=window.requestAnimationFrame(()=>{E=window.requestAnimationFrame(()=>{g(!0)})}),()=>{window.cancelAnimationFrame(b),window.cancelAnimationFrame(E)}},[n]);const M=n&&v,y=!n||!v,C=Ac(s),j=C.status||C.modalMessage||C.modalButtons?{...s,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(Pi,{activeConv:j,onModalButton:c}),j.transport!=="pty"&&j.transport!=="acp"&&j.cdpConnected===!1?t.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:t.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:[t.jsx("span",{className:"text-sm",children:t.jsx(qs,{size:14})}),t.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),t.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:l,children:"Relaunch with CDP"})]})}):null,j.transport==="pty"?t.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[t.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:M?"visible":"hidden",pointerEvents:M?"auto":"none"},children:t.jsx(qm,{activeConv:j,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,isVisible:n,isInputActive:x&&n})}),t.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:t.jsx(ra,{activeConv:j,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:m,actionLogs:k,userName:S,scrollToBottomRequestNonce:p,isInputActive:x&&y,isVisible:y})})]}):t.jsx(ra,{activeConv:j,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:m,actionLogs:k,userName:S,scrollToBottomRequestNonce:p,isInputActive:x})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.sendFeedbackMessage===s.sendFeedbackMessage&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function oh({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:f,onOpenNativeConversation:d,onOpenMachine:h,onOpenHistory:m,onOpenRemote:k,onHideConversation:S,onStopCli:p,cliViewMode:x,onSetCliViewMode:v,handleSendChat:g,handleFocusAgent:N,handleModalButton:M,handleRelaunch:y}){const C=o.useRef(null),j=Je(e)&&!s,w=j&&x==="terminal",b=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${b} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.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:t.jsx(ha,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:rt(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(Qi,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>h(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&x&&t.jsx(Aa,{mode:x,onChange:v,compact:!0}),j&&p&&t.jsx("button",{onClick:()=>{p(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(wt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(e),type:"button",children:t.jsx(xa,{size:14})}),!s&&!j&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",children:t.jsx(Ct,{size:14})}),S&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Close chat",children:t.jsx(wt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(Fa,{activeConv:e,clearToken:0,isCliTerminal:w,ideEntry:n,terminalRef:C,handleModalButton:M,handleRelaunch:y,handleSendChat:g,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:N,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const In={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 ih(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Hc(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(ih())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(In[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return t.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:[t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.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:()=>s("unix"),children:"🍎🐧 macOS / Linux"}),t.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:()=>s("windows"),children:"🪟 Windows"})]}),e==="windows"&&t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.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"}),t.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"})]}),t.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[t.jsx("span",{className:"text-text-muted select-none",children:In[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:In[c].cmd}),t.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),t.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",t.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Fc({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Ct},{key:"chats",label:"Chats",icon:Ft}];return t.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:t.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 t.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:()=>s(n),type:"button","aria-pressed":c,children:[t.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:t.jsx(i,{size:15})}),t.jsx("span",{children:a})]},n)})})})}function wr({title:e,className:s=""}){return t.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:t.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function hs({children:e,className:s=""}){return t.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)] ${s}`,children:e})}function Ds({icon:e,title:s,subtitle:r,children:n}){return t.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:[t.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}),t.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function jr({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const a=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",l=s==="task_complete",{isReconnecting:u,isConnecting:f}=As(e.conversation),d=rt(e.conversation),h=us(e.conversation),m=ic(e.conversation,{requiresAction:s==="needs_attention"}),k=a?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",S=a?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",p=c?"text-text-secondary":"text-text-primary",x=c?"text-text-muted":"text-text-secondary",v=c?"text-text-secondary opacity-80":"text-text-muted",g=c?"text-text-muted opacity-80":"text-text-muted",N="text-[color:var(--status-warning)]";return t.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${k}`,onClick:()=>n(e.conversation),type:"button",children:[a||i?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${S}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(d)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${p}`,children:d}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${g}`,children:Ri(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${x}`,children:[h,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${N} animate-pulse`,children:"Reconnecting…"})]}):f?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):m==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:N,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${v}`,children:e.preview})]}),a&&!l&&t.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&t.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),i&&t.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 zo({size:e=32,label:s}){return t.jsxs("div",{className:"flex flex-col items-center gap-2.5",children:[t.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}}),s&&t.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:s})]})}function ch({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:f,onShowAllHidden:d,onOpenNewSession:h,onOpenMachine:m,onOpenSettings:k,onSectionChange:S,wsStatus:p="connected",isStandalone:x=!1}){const v=p==="disconnected"||p==="reconnecting"||p==="offline"||p==="auth_failed",g=c.length>0,N=s.length>0||r.length>0||n.length>0||a.length>0,M=e==="machines"?"Machines":"Chats",y=x?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",C=x?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return t.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[t.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${y}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:M}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(s.length>0||r.length>0)&&t.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:[t.jsx(Xr,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:k,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:t.jsx(Yr,{size:18})})]})]})}),t.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] ${C}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:v?t.jsx(Ds,{icon:t.jsx(zo,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:p==="offline"?"Your device appears to be offline. Waiting for network…":p==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?t.jsx(Ds,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:x?"Waiting for your daemon":"Connect your machines",subtitle:x?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!x&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(Hc,{})})}):t.jsx(hs,{children:c.map((j,w)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>m(j.id),type:"button",children:[t.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(j.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:j.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:j.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[j.unread," new"]}):j.total>0?`${j.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:j.subtitle}),j.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[j.total," chat",j.total!==1?"s":"",j.unread>0?` · ${j.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},j.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(wr,{title:"Needs attention",className:"mb-0"}),t.jsx(hs,{children:s.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(jr,{item:j,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(wr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(hs,{children:r.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(jr,{item:j,type:"task_complete",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(wr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(hs,{children:n.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(jr,{item:j,type:"working",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&t.jsx(wr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(hs,{children:a.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(jr,{item:j,type:"earlier",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))}):N?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):v?t.jsx(Ds,{icon:t.jsx(zo,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):g?t.jsx(Ds,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(Ft,{size:20})}),title:"No conversations yet",subtitle:dc,children:h&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":$t,title:$t,children:[t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),t.jsx("span",{children:$t})]})}):t.jsx(Ds,{icon:t.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&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:d,children:"Restore all"})]}),t.jsx(hs,{className:"bg-bg-secondary/25",children:i.map((j,w)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] opacity-50 saturate-0 ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(j),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(rt(j))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:rt(j)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:us(j)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},j.tabKey))})]})]}),e==="chats"&&h&&N&&t.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":$t,title:$t,children:t.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),t.jsx(Fc,{section:e,onSectionChange:S})]})}function lh(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 Uc(e){const s=[e.workspace||"Workspace unknown"],r=ds(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=lh(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function an({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:f}){const[d,h]=o.useState(r);o.useEffect(()=>{h(r)},[r]);const m=zp(r),k=d.trim();return t.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:t.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:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.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:t.jsx(wt,{size:16})})]}),t.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[t.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!m||a||u(m)},disabled:!m||a,children:[t.jsx(ha,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:d,onChange:S=>h(S.target.value),onKeyDown:S=>{S.key!=="Enter"||!k||a||(S.preventDefault(),u(k))},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"}),t.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:()=>{!k||a||u(k)},disabled:!k||a,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(S=>t.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(S.path),children:[t.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:t.jsx(Ss,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:S.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:S.path})]})]},S.path))})}),t.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:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>f(k||r),disabled:!k&&!r||a,children:c})]})]})})}function Ua({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:f,argsValue:d,onArgsChange:h,showModelInput:m,modelValue:k,onModelChange:S,historyProviderNode:p,onConfirm:x,onCancel:v}){const g=n==null?void 0:n.find(N=>N.key===a);return t.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:t.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:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:v,"aria-label":"Close launch confirmation",children:t.jsx(wt,{size:16})})]}),t.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&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),t.jsx("select",{value:a||"",onChange:N=>i(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(N=>t.jsx("option",{value:N.key,children:N.label},N.key))}),(g==null?void 0:g.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:g.description})]}),p,r.map(N=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:N.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${N.value}`)),m&&S&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:k||"",onChange:N=>S(N.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),f&&h&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:d||"",onChange:N=>h(N.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),t.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:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:v,disabled:u,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:x,disabled:u,children:[t.jsx(ga,{size:14}),u?l:c]})]})]})})}function Vo(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function os(e){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of s.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===s.defaultWorkspaceId?"⭐ ":""}${Vo(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(s.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:Vo(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(f=>f.key===u))return{options:i,selectedKey:u}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function dh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function uh(e){return[dh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function mh(e){return e.lastLaunchedAt?Jr(e.lastLaunchedAt):""}function zc(e){return{metaText:uh(e),updatedLabel:mh(e)}}function Mn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function fh({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var ut,mt,Xe,at;const c=nr(),[l,u]=o.useState(!1),f=(((ut=e.detectedIdes)==null?void 0:ut.length)||0)>0,d=o.useMemo(()=>(e.workspaces||[]).map(ve=>({id:ve.id,path:ve.path,label:ve.label})),[e]),h=e.defaultWorkspaceId||null,[m,k]=o.useState(h||((mt=d[0])==null?void 0:mt.id)||""),[S,p]=o.useState(""),[x,v]=o.useState(""),[g,N]=o.useState([]),[M,y]=o.useState(!1),[C,j]=o.useState(""),[w,b]=o.useState(!1),[E,A]=o.useState(Mn(f,s.length,r.length)),I=o.useRef(null),[P,O]=o.useState(null),V=o.useRef("__home__"),[L,R]=o.useState("__home__"),[G,B]=o.useState(""),[$,H]=o.useState(""),[J,xe]=o.useState(""),[me,ce]=o.useState([]),[ge,be]=o.useState(()=>ht().textQuery),[we,z]=o.useState(()=>ht().workspaceQuery),[U,Q]=o.useState(()=>ht().modelQuery),[de,re]=o.useState(()=>ht().resumableOnly),[le,te]=o.useState(()=>ht().sortMode),[fe,ne]=o.useState(!1),[ie,ae]=o.useState(!1),ye=o.useRef(null),he=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const Se=m==="__custom__"?S.trim():((Xe=d.find(ve=>ve.id===m))==null?void 0:Xe.path)||"",T=m==="__custom__"&&!!Se&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),D=m!=="__custom__"&&((at=d.find(ve=>ve.id===m))==null?void 0:at.path)||"",Y=o.useMemo(()=>(e.recentLaunches||[]).map(ve=>ve.workspace),[e]),X=o.useCallback(async ve=>{y(!0),j("");try{const Ee=await a(ve);v(Ee.path),p(Ee.path),N(Ee.directories)}catch(Ee){j(Ee instanceof Error?Ee.message:"Could not load folder")}finally{y(!1)}},[a]),pe=o.useCallback(()=>{var Ee;k("__custom__"),b(!0);const ve=sn(e.platform,tn(S.trim(),D,Y,e.defaultWorkspacePath,(Ee=d.find(Ke=>Ke.id===h))==null?void 0:Ee.path,d.map(Ke=>Ke.path)));X(ve)},[S,h,X,Y,D,e.platform,d]),Ie=o.useCallback(ve=>{if(ve!=null&&ve.workspaceId){k(ve.workspaceId),p("");return}if(ve!=null&&ve.workspacePath){k("__custom__"),p(ve.workspacePath);return}k(""),p("")},[]),Ne=o.useCallback(ve=>{if(k(ve),ve==="__custom__"){pe();return}p("")},[pe]),Be=o.useCallback(ve=>{k("__custom__"),p(ve)},[]),He=o.useCallback((ve,Ee)=>{I.current=Ee,V.current=ve.selectedWorkspaceKey||"__home__",R(ve.selectedWorkspaceKey||"__home__"),B(ve.initialArgs||""),H(ve.initialModel||""),xe(""),ce([]);const Ke=ve.providerType?`${e.id}:${ve.providerType}`:null;if(Zm(he.current,Ke)){const ot=ht();be(ot.textQuery),z(ot.workspaceQuery),Q(ot.modelQuery),re(ot.resumableOnly),te(ot.sortMode)}he.current=Ke,O(ve),ve.providerType&&i&&(ne(!0),i(ve.providerType).then(ot=>ce(ot||[])).catch(ot=>console.warn("Failed to load saved sessions",ot)).finally(()=>ne(!1)))},[i,e.id]),Ue=o.useMemo(()=>uc(me,{textQuery:ge,workspaceQuery:we,modelQuery:U,resumableOnly:de,sortMode:le}),[U,de,me,le,ge,we]);o.useEffect(()=>{J&&(Ue.some(ve=>ve.providerSessionId===J)||xe(""))},[Ue,J]);const Qe=o.useCallback(()=>{I.current&&(ae(!0),I.current().finally(()=>{I.current=null,ae(!1),O(null)}))},[]),tt=o.useCallback(()=>{I.current=null,O(null)},[]),ct=o.useCallback(ve=>{V.current=ve,R(ve)},[]);return o.useEffect(()=>{var ve;ye.current!==e.id&&(ye.current=e.id,k(h||((ve=d[0])==null?void 0:ve.id)||"__custom__"),p(""),v(""),N([]),j(""),b(!1),be(ht().textQuery),z(ht().workspaceQuery),Q(ht().modelQuery),re(ht().resumableOnly),te(ht().sortMode),he.current=null,A(Mn(f,s.length,r.length)))},[r.length,s.length,h,f,e.id,d]),o.useEffect(()=>{var ve;m!=="__custom__"&&(m&&d.some(Ee=>Ee.id===m)||k(h||((ve=d[0])==null?void 0:ve.id)||"__custom__"))},[h,m,d]),o.useEffect(()=>{E==="ide"&&f||E==="cli"&&s.length>0||E==="acp"&&r.length>0||A(Mn(f,s.length,r.length))},[E,r.length,s.length,f]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:f,workspaceRows:d,defaultWorkspaceId:h,workspaceChoice:m,customWorkspacePath:S,browseCurrentPath:x,browseDirectories:g,browseBusy:M,browseError:C,browseDialogOpen:w,activeLauncherKind:E,launchConfirm:P,launchConfirmWorkspaceKeyRef:V,launchConfirmWorkspaceKey:L,launchConfirmArgs:G,launchConfirmModel:$,launchConfirmResumeId:J,launchConfirmSavedSessions:me,launchConfirmTextFilter:ge,launchConfirmWorkspaceFilter:we,launchConfirmModelFilter:U,launchConfirmResumableOnly:de,launchConfirmSortMode:le,filteredLaunchConfirmSavedSessions:Ue,launchConfirmSessionsLoading:fe,launchConfirmBusy:ie,resolvedWorkspacePath:Se,canCreateMissingWorkspace:T,openBrowseDialog:pe,loadBrowsePath:X,handleWorkspaceChoiceChange:Ne,chooseCustomWorkspacePath:Be,setCustomWorkspacePath:p,setBrowseDialogOpen:b,setActiveLauncherKind:A,openLaunchConfirm:He,handleConfirmLaunch:Qe,closeLaunchConfirm:tt,setWorkspaceSelectionFromOption:Ie,setLaunchConfirmWorkspaceKeyAndSync:ct,setLaunchConfirmArgs:B,setLaunchConfirmModel:H,setLaunchConfirmResumeId:xe,setLaunchConfirmTextFilter:be,setLaunchConfirmWorkspaceFilter:z,setLaunchConfirmModelFilter:Q,setLaunchConfirmResumableOnly:re,setLaunchConfirmSortMode:te}}function ph({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:f,showBottomNav:d,onBack:h,onSectionChange:m,onOpenConversation:k,onOpenRecent:S,onOpenMachineDetails:p,onMachineUpgrade:x,onLaunchDetectedIde:v,onAddWorkspace:g,onBrowseDirectory:N,onLaunchWorkspaceProvider:M,onListSavedSessions:y}){const C=L=>L==="ide"?"IDE":L==="cli"?"CLI":"ACP",j=r.slice(0,4),w=s.slice(0,3),b=fh({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:y}),E=o.useMemo(()=>j.map(L=>{const{metaText:R,updatedLabel:G}=zc(L);return{key:`recent-launch:${L.id}`,primary:L.label,secondary:R,updatedLabel:G,onClick:()=>{const{options:B,selectedKey:$}=os({machine:{workspaces:b.workspaceRows,defaultWorkspaceId:b.defaultWorkspaceId},currentWorkspacePath:L.workspace});b.openLaunchConfirm({title:L.kind==="ide"?ss("restart-ide",L.label):L.providerSessionId?Ra(L.label):ss("start-fresh",L.label),description:L.kind==="ide"?rs("restart-ide"):L.providerSessionId?Pa():rs("start-fresh"),confirmLabel:L.kind==="ide"?Cs("restart-ide"):L.providerSessionId?Ur(!0):Cs("start-fresh"),busyLabel:L.kind==="ide"?Is("restart-ide"):L.providerSessionId?Ta(!0):Is("start-fresh"),workspaceOptions:B,selectedWorkspaceKey:$,details:[{label:"Mode",value:C(L.kind)},...L.providerType?[{label:"Provider",value:L.providerType}]:[]]},async()=>{const H=B.find(J=>J.key===b.launchConfirmWorkspaceKeyRef.current);b.setWorkspaceSelectionFromOption(H),await S({...L,workspace:(H==null?void 0:H.workspacePath)??null})})}}}),[b,S,j]),A=o.useMemo(()=>w.map(L=>({key:`recent-chat:${L.conversation.tabKey}`,primary:rt(L.conversation),secondary:Um(L.conversation,{timestampLabel:L.timestamp?Ri(L.timestamp):null}),unread:L.unread,onClick:()=>k(L.conversation)})),[k,w]),I=b.showAllRecent?E:E.slice(0,4),P=E.length>0,O=A.length>0,V=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${V} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:t.jsx(ha,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:At(e,{fallbackId:e.id})}),t.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}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[O&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:A.map(L=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${L.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:L.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:L.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))})]}),P&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:I.map(L=>t.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:L.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:L.primary}),L.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:L.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))}),E.length>4&&t.jsx("div",{className:"flex justify-center px-4 pt-2",children:t.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>b.setShowAllRecent(L=>!L),children:b.showAllRecent?"Show fewer":`Show ${E.length-4} more`})})]}),(b.hasIdeOptions||n.length>0||a.length>0)&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:t.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:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),t.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),t.jsx("select",{value:b.workspaceChoice,onChange:L=>b.handleWorkspaceChoiceChange(L.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:b.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[b.workspaceRows.map(L=>t.jsxs("option",{value:L.id,children:[L.id===b.defaultWorkspaceId?"⭐ ":"",Zr(L.path,L.label)||L.path]},L.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),b.workspaceChoice==="__custom__"&&t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start gap-3",children:[t.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:t.jsx(Ss,{size:17})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),t.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:b.resolvedWorkspacePath||b.browseCurrentPath||"No folder selected yet."})]})]})}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:b.openBrowseDialog,children:"Select workspace…"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{b.resolvedWorkspacePath&&g(b.resolvedWorkspacePath)},disabled:!b.resolvedWorkspacePath||b.browseBusy,children:"Save as workspace"})]})]}),b.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:b.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[b.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${b.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>b.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${b.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>b.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${b.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>b.setActiveLauncherKind("acp"),children:"ACP"})]}),b.activeLauncherKind&&t.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[t.jsx("div",{className:"text-xs font-bold text-text-secondary",children:b.activeLauncherKind==="ide"?"Choose an IDE":b.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:b.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(L=>t.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:R,selectedKey:G}=os({machine:{workspaces:b.workspaceRows,defaultWorkspaceId:b.defaultWorkspaceId},currentWorkspaceId:b.workspaceChoice!=="__custom__"?b.workspaceChoice:null,currentWorkspacePath:b.resolvedWorkspacePath});b.openLaunchConfirm({title:`Launch ${L.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:R,selectedWorkspaceKey:G,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:L.name}]},async()=>{const B=R.find($=>$.key===b.launchConfirmWorkspaceKeyRef.current);b.setWorkspaceSelectionFromOption(B),v(L.type,{workspacePath:(B==null?void 0:B.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:L.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:b.resolvedWorkspacePath||"Use selected workspace"})]},L.type)):(b.activeLauncherKind==="cli"?n:a).map(L=>t.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 R=b.activeLauncherKind==="cli"?"cli":"acp",{options:G,selectedKey:B}=os({machine:{workspaces:b.workspaceRows,defaultWorkspaceId:b.defaultWorkspaceId},currentWorkspaceId:b.workspaceChoice!=="__custom__"?b.workspaceChoice:null,currentWorkspacePath:b.resolvedWorkspacePath});b.openLaunchConfirm({title:`Launch ${L.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${R.toUpperCase()}`,workspaceOptions:G,selectedWorkspaceKey:B,details:[{label:"Mode",value:R.toUpperCase()},{label:"Provider",value:L.displayName}],showArgsInput:!0,showModelInput:R==="acp",initialArgs:"",initialModel:"",providerType:L.type},async()=>{const $=G.find(H=>H.key===b.launchConfirmWorkspaceKeyRef.current);b.setWorkspaceSelectionFromOption($),M(R,L.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.workspacePath)??null,args:b.launchConfirmArgs,model:b.launchConfirmModel,resumeSessionId:b.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[L.icon?`${L.icon} `:"",L.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:b.resolvedWorkspacePath||"Use selected workspace"})]},L.type))})]}),l.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,b.canCreateMissingWorkspace&&t.jsx("div",{className:"mt-2",children:t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>g(b.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:x,children:[t.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:p,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),b.browseDialogOpen&&t.jsx(an,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:b.browseCurrentPath,directories:b.browseDirectories,busy:b.browseBusy,error:b.browseError,confirmLabel:"Use this folder",onClose:()=>b.setBrowseDialogOpen(!1),onNavigate:L=>{b.loadBrowsePath(L)},onConfirm:L=>{b.chooseCustomWorkspacePath(L),b.setBrowseDialogOpen(!1)}}),b.launchConfirm&&t.jsx(Ua,{title:b.launchConfirm.title,description:b.launchConfirm.description,details:b.launchConfirm.details,workspaceOptions:b.launchConfirm.workspaceOptions,selectedWorkspaceKey:b.launchConfirmWorkspaceKey,onWorkspaceChange:b.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:b.launchConfirm.providerType?Ur(!!b.launchConfirmResumeId):b.launchConfirm.confirmLabel,busyLabel:b.launchConfirm.providerType?void 0:b.launchConfirm.busyLabel,busy:b.launchConfirmBusy,showArgsInput:b.launchConfirm.showArgsInput,argsValue:b.launchConfirmArgs,onArgsChange:b.setLaunchConfirmArgs,showModelInput:b.launchConfirm.showModelInput,modelValue:b.launchConfirmModel,onModelChange:b.setLaunchConfirmModel,historyProviderNode:b.launchConfirm.providerType&&(b.launchConfirmSessionsLoading||b.launchConfirmSavedSessions.length>0)&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),b.launchConfirmSessionsLoading&&t.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:La()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:b.launchConfirmTextFilter,onChange:L=>b.setLaunchConfirmTextFilter(L.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:b.launchConfirmWorkspaceFilter,onChange:L=>b.setLaunchConfirmWorkspaceFilter(L.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:b.launchConfirmModelFilter,onChange:L=>b.setLaunchConfirmModelFilter(L.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),t.jsxs("select",{value:b.launchConfirmSortMode,onChange:L=>b.setLaunchConfirmSortMode(L.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:b.launchConfirmResumableOnly,onChange:L=>b.setLaunchConfirmResumableOnly(L.target.checked),disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:b.launchConfirmResumeId,onChange:L=>b.setLaunchConfirmResumeId(L.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:sf()}),b.filteredLaunchConfirmSavedSessions.map(L=>t.jsxs("option",{value:L.providerSessionId,disabled:!L.canResume,children:[L.title||L.providerSessionId," ",L.canResume?"":"(workspace missing)"]},L.providerSessionId))]}),!b.launchConfirmSessionsLoading&&b.launchConfirmSavedSessions.length>0&&b.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),b.launchConfirmResumeId&&(()=>{const L=b.filteredLaunchConfirmSavedSessions.find(G=>G.providerSessionId===b.launchConfirmResumeId);if(!L)return null;const R=Uc(L);return t.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:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:R.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:R.providerSessionId}),t.jsx("div",{className:"mt-1",children:R.metaLine}),R.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:R.updatedLabel}),R.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:R.preview})]})})()]}),onConfirm:b.handleConfirmLaunch,onCancel:b.closeLaunchConfirm}),d&&t.jsx(Fc,{section:f,onSectionChange:m})]})}function hh(e){var r;const s=((r=e.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function xh(e,s){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:ds(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,f,d;const a=Xs(n)?"cli":ys(n)?"acp":"ide",i=ds(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(Xs(n)?n.cliName||n.type:ys(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:ys(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((d=(f=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:f.call(u,-1))==null?void 0:d.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function bh(e,s){const r=new Map;for(const n of s){const a=fs(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((h,m)=>m.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Xn(n),u=a.filter(h=>h.unread||h.requiresAction).length,f=hh(n),d=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:At(n,{fallbackId:n.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?zm(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 gh(e){return e==="chat"}function kr(e,s){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}`,s)}catch{}}function yh({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:k,setSelectedTabKey:S,setScreen:p,setSelectedMachineId:x,setSection:v,setMachineBackTarget:g,resetMachineAction:N}){const M=o.useRef(null),y=o.useCallback(C=>{if(!(C!=null&&C.sessionId))return;const j=Or(C,c),w=Math.max(Date.now(),es(C),j.lastUpdated||0);kr("mark_read:start",{tabKey:C.tabKey,sessionId:C.sessionId,displayPrimary:rt(C),inboxBucket:j.inboxBucket,unread:j.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:es(C),readAt:w}),l(fs(C)||C.routeId,"mark_session_seen",{sessionId:C.sessionId,seenAt:w}).then(b=>{kr("mark_read:result",{tabKey:C.tabKey,sessionId:C.sessionId,result:b})}).catch(b=>{kr("mark_read:error",{tabKey:C.tabKey,sessionId:C.sessionId,error:b instanceof Error?b.message:String(b)})})},[c,l]);return o.useEffect(()=>{var j;if(!n){gh(i)&&p("inbox"),S(((j=e[0])==null?void 0:j.tabKey)||null),M.current=null;return}if(i!=="chat"){M.current=null;return}const C=`${n.tabKey}:${n.sessionId||""}`;M.current!==C&&(M.current=C,y(n))},[e,y,i,n,p,S]),o.useEffect(()=>{if(!u)return;const C=e.find(j=>j.tabKey===u);C&&(S(C.tabKey),p("chat"),f==null||f())},[e,f,u,p,S]),o.useEffect(()=>{if(!d)return;const C=s.find(j=>j.id===d);C&&(x(C.id),N(),v("machines"),g("inbox"),p("machine"),h==null||h())},[s,h,d,N,g,p,v,x]),o.useEffect(()=>{m&&(v(m),p("inbox"),k==null||k())},[k,m,p,v]),o.useEffect(()=>{const C=r.filter(j=>j.inboxBucket==="task_complete"||j.unread);C.length!==0&&kr("inbox_state",{screen:i,selectedTabKey:a,items:C.map(j=>{const w=Or(j.conversation,c);return{liveState:w,tabKey:j.conversation.tabKey,sessionId:j.conversation.sessionId,displayPrimary:rt(j.conversation),serverBucket:w.inboxBucket,computedBucket:j.inboxBucket,serverUnread:w.unread,computedUnread:j.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:es(j.conversation)}})})},[r,c,i,a]),{markConversationRead:y}}function vh(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Go(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function wh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function jh({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,f]=o.useState(null),d=o.useCallback(()=>{i("idle"),l(""),f(null)},[]),h=o.useCallback(async(g,N,M)=>{var y;try{i("loading"),l(`Launching ${N}…`);const C={ideType:N,enableCdp:!0};(y=M==null?void 0:M.workspacePath)!=null&&y.trim()&&(C.workspace=M.workspacePath.trim()),await e(g,"launch_ide",C),i("done"),l(`${N} launch requested`)}catch(C){i("error"),l(C instanceof Error?C.message:"Launch IDE failed"),console.error("Launch IDE failed",C)}},[e]),m=o.useCallback(async(g,N,M)=>{if(N.trim())try{i("loading"),l(M!=null&&M.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(g,"workspace_add",{path:N.trim(),createIfMissing:(M==null?void 0:M.createIfMissing)===!0});if(y!=null&&y.success){i("done"),l(M!=null&&M.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((y==null?void 0:y.error)||"Could not save workspace")}catch(y){i("error"),l(y instanceof Error?y.message:"Could not save workspace")}},[e]),k=o.useCallback(async g=>{var N,M,y,C,j,w;try{i("loading"),l("Starting daemon upgrade…");const b=await e(g,"daemon_upgrade",{});if((N=b==null?void 0:b.result)!=null&&N.alreadyLatest){i("done"),l(`Already on v${((M=b==null?void 0:b.result)==null?void 0:M.version)||"latest"}.`);return}if((y=b==null?void 0:b.result)!=null&&y.upgraded||(C=b==null?void 0:b.result)!=null&&C.success){i("done"),l(`Upgrade to v${((j=b==null?void 0:b.result)==null?void 0:j.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((w=b==null?void 0:b.result)==null?void 0:w.error)||"Upgrade failed")}catch(b){i("error"),l(b instanceof Error?b.message:"Upgrade failed")}},[e]),S=o.useCallback(async(g,N,M,y)=>{var w,b,E;const C=Date.now(),j={machineId:g,kind:N,providerType:M,workspaceId:(y==null?void 0:y.workspaceId)||null,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:C};try{i("loading"),l(`Launching ${M}…`),f(j);const A={cliType:M};(w=y==null?void 0:y.workspacePath)!=null&&w.trim()?A.dir=y.workspacePath.trim():y!=null&&y.workspaceId&&(A.workspaceId=y.workspaceId),y!=null&&y.resumeSessionId&&(A.resumeSessionId=y.resumeSessionId),(b=y==null?void 0:y.args)!=null&&b.trim()&&(A.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(E=y==null?void 0:y.model)!=null&&E.trim()&&(A.initialModel=y.model.trim());const I=await e(g,"launch_cli",A),P=(I==null?void 0:I.result)||I,O=(P==null?void 0:P.sessionId)||(P==null?void 0:P.id);if(I!=null&&I.success&&O){f(null),i("done"),l(`${M} launched`),s(Gt(O));return}if(I!=null&&I.success){i("loading"),l(`${M} launch requested — waiting for session…`);return}f(null),i("error"),l((I==null?void 0:I.error)||(P==null?void 0:P.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(A){if(wh(A)){i("loading"),l(`${M} launch requested — waiting for session…`);return}f(null),i("error"),l(A instanceof Error?A.message:`Could not launch ${N.toUpperCase()} workspace`)}},[s,e]),p=o.useCallback(async(g,N)=>{try{const M=await e(g,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),y=(M==null?void 0:M.result)??M;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(M){return console.error("Failed to list saved sessions on mobile:",M),[]}},[e]),x=o.useCallback(async(g,N)=>rn(e,g,N),[e]);o.useEffect(()=>{if(!u)return;const g=Go(u.workspacePath),N=r.find(y=>{var A,I,P,O;if(!y||y.type==="adhdev-daemon"||vh(y.daemonId||y.id)!==u.machineId||(y.transport==="acp"?"acp":y.transport==="pty"?"cli":null)!==u.kind||String(y.agentType||y.type||"")!==u.providerType)return!1;const b=String(y.providerSessionId||"");if(u.resumeSessionId&&b)return b===u.resumeSessionId;if(g){const V=Go(y.workspace||y.runtimeWorkspaceLabel);return V?V===g:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((O=(P=(I=(A=y.activeChat)==null?void 0:A.messages)==null?void 0:I.at)==null?void 0:P.call(I,-1))==null?void 0:O.timestamp)||0)>=u.startedAt-5e3});if(!N)return;const M=Ji({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});M&&(f(null),i("done"),l(`${u.providerType} launched`),s(Gt(M)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const g=window.setTimeout(()=>{f(N=>!N||N.startedAt!==u.startedAt?N:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(g)},[u]);const v=o.useCallback(async(g,N)=>{if(N.kind==="ide"&&N.providerType){await h(g,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await S(g,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[h,S]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:h,handleAddWorkspace:m,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:S,handleListSavedSessions:p,handleBrowseDirectory:x,handleOpenRecent:v}}function kh({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:f}){const d=o.useCallback(v=>{i(v.tabKey),c("chat"),n(v)},[n,c,i]),h=o.useCallback(v=>{const g=e.find(N=>N.routeId===v.routeId&&N.streamSource==="native");g&&(i(g.tabKey),c("chat"),n(g))},[e,n,c,i]),m=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),k=o.useCallback((v,g="inbox")=>{l(v),a(),u("machines"),f(g),c("machine")},[a,f,c,u,l]),S=o.useCallback(v=>{const g=fs(v);g&&k(g,"chat")},[k]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),x=o.useCallback(v=>{u(v),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:h,backFromConversation:m,openMachine:k,openConversationMachine:S,backFromMachine:p,changeMachineSection:x}}function Sh(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Sr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Nh({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:k,onOpenHistory:S,onOpenRemote:p,onStopCli:x,wsStatus:v,isConnected:g,onShowHiddenConversation:N,onShowAllHiddenConversations:M,onHideConversation:y,onOpenNewSession:C,liveSessionInboxState:j,setCliViewModeOverrides:w}){const[b,E]=o.useState(()=>{var D;return((D=e[0])==null?void 0:D.tabKey)||null}),[A,I]=o.useState(()=>e[0]?"chat":"inbox"),[P,O]=o.useState("chats"),[V,L]=o.useState(null),[R,G]=o.useState("inbox"),B=Ms(),$="0.9.13",H=o.useMemo(()=>e.find(D=>D.tabKey===b)||e[0]||null,[e,b]),J=o.useMemo(()=>H?r.find(D=>D.id===H.routeId):void 0,[r,H]),xe=o.useMemo(()=>!H||qe(H)||!Je(H)?null:Ts(H),[H]),me=o.useMemo(()=>r.filter(D=>D.type==="adhdev-daemon").sort(va),[r]),ce=o.useMemo(()=>me.find(D=>D.id===V)||null,[me,V]),ge=nn({sendDaemonCommand:a,activeConv:H||void 0,setActionLogs:i,isStandalone:c}),be=jh({sendDaemonCommand:a,navigate:B,ides:r,conversations:e}),we=o.useMemo(()=>e.map(D=>{const Y=A==="chat"&&(H==null?void 0:H.tabKey)===D.tabKey,X=Qr(D,j,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Y}),pe=es(D),Ie=oc(D);return{conversation:D,timestamp:pe,preview:Ie,unread:X.unread,requiresAction:X.requiresAction,isWorking:X.isWorking,inboxBucket:X.inboxBucket}}),[e,j,A,H]),{markConversationRead:z}=yh({conversations:e,machineEntries:me,items:we,selectedConversation:H,selectedTabKey:b,screen:A,liveSessionInboxState:j,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:k,setSelectedTabKey:E,setScreen:I,setSelectedMachineId:L,setSection:O,setMachineBackTarget:G,resetMachineAction:be.resetMachineAction}),U=kh({conversations:e,selectedConversation:H,machineBackTarget:R,markConversationRead:z,resetMachineAction:be.resetMachineAction,setSelectedTabKey:E,setScreen:I,setSelectedMachineId:L,setSection:O,setMachineBackTarget:G}),Q=o.useMemo(()=>Sr(we.filter(D=>D.requiresAction)),[we]),de=o.useMemo(()=>Sr(we.filter(D=>D.unread&&!D.requiresAction)),[we]),re=o.useMemo(()=>Sr(we.filter(D=>!D.unread&&!D.requiresAction&&D.isWorking)),[we]),le=o.useMemo(()=>Sr(we.filter(D=>!D.unread&&!D.requiresAction&&!D.isWorking)),[we]),te=o.useMemo(()=>ce?we.filter(D=>fs(D.conversation)===ce.id):[],[we,ce]),fe=o.useMemo(()=>xh(ce,r),[r,ce]),ne=(ce==null?void 0:ce.version)||null,ie=!!ce&&!!ne&&!0&&ne!==$,ae=o.useMemo(()=>(ce==null?void 0:ce.availableProviders)||[],[ce]),ye=o.useMemo(()=>ae.filter(D=>D.category==="cli"&&D.installed!==!1).map(D=>({type:D.type,displayName:D.displayName||D.type,icon:D.icon})),[ae]),he=o.useMemo(()=>ae.filter(D=>D.category==="acp"&&D.installed!==!1).map(D=>({type:D.type,displayName:D.displayName||D.type,icon:D.icon})),[ae]),Se=o.useMemo(()=>bh(me,we),[we,me]),T=o.useCallback(async D=>{ce&&await be.handleOpenRecent(ce.id,D)},[be,ce]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:A==="chat"&&H?t.jsx(oh,{selectedConversation:H,isAcp:qe(H),isStandalone:c,selectedIdeEntry:J,actionLogs:n,userName:l,isSendingChat:ge.isSendingChat,sendFeedbackMessage:ge.sendFeedbackMessage,isFocusingAgent:ge.isFocusingAgent,handleModalButton:ge.handleModalButton,handleRelaunch:ge.handleRelaunch,onBack:U.backFromConversation,onOpenNativeConversation:U.openNativeConversation,onOpenMachine:U.openConversationMachine,onHideConversation:y,onOpenHistory:S,onOpenRemote:p,onStopCli:x,cliViewMode:xe,onSetCliViewMode:async D=>{await _c({conversation:H,mode:D,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:w})},handleSendChat:ge.handleSendChat,handleFocusAgent:ge.handleFocusAgent}):A==="machine"&&ce?t.jsx(ph,{selectedMachineEntry:ce,selectedMachineConversations:te,selectedMachineRecentLaunches:fe,cliProviders:ye,acpProviders:he,selectedMachineNeedsUpgrade:ie,appVersion:$,machineAction:be.machineAction,isStandalone:c,section:P,showBottomNav:R==="inbox",onBack:U.backFromMachine,onSectionChange:U.changeMachineSection,onOpenConversation:U.openConversation,onOpenRecent:T,onOpenMachineDetails:()=>B(`/machines/${ce.id}`),onMachineUpgrade:()=>be.handleMachineUpgrade(ce.id),onLaunchDetectedIde:(D,Y)=>be.handleLaunchDetectedIde(ce.id,D,Y),onAddWorkspace:(D,Y)=>be.handleAddWorkspace(ce.id,D,Y),onBrowseDirectory:D=>be.handleBrowseDirectory(ce.id,D),onLaunchWorkspaceProvider:(D,Y,X)=>be.handleLaunchWorkspaceProvider(ce.id,D,Y,X),onListSavedSessions:D=>be.handleListSavedSessions(ce.id,D)}):t.jsx(ch,{section:P,attentionItems:Q,unreadItems:de,workingItems:re,completedItems:le,hiddenConversations:s,machineCards:Se,getAvatarText:Sh,onOpenConversation:U.openConversation,onShowConversation:N,onShowAllHidden:M,onOpenNewSession:C,onOpenMachine:U.openMachine,onOpenSettings:()=>B("/settings"),onSectionChange:O,wsStatus:v,isConnected:g,isStandalone:c})})}function An(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Ch({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[f,d]=o.useState(null),h=o.useCallback(()=>{c.current=0,u(!1),d(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const m=o.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),k=o.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!An(s,r)){d("merge");return}const v=x.currentTarget.getBoundingClientRect(),g=x.clientX-v.left,N=v.width/3;g<N?d("split-left"):g>N*2?d("split-right"):d("merge")},[s,r]),S=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),d(null))},[]),p=o.useCallback(x=>{c.current=0,u(!1);const v=x.dataTransfer.getData("text/tab-key"),g=v?e.some(M=>M.tabKey===v):!1,N=f;if(d(null),i(),!!v){if(x.preventDefault(),N==="split-left"&&An(s,r)){r==null||r(v,"split-left");return}if(N==="split-right"&&An(s,r)){r==null||r(v,"split-right");return}if(g){a(v);return}n==null||n(v)}},[e,f,s,r,n,a,i]);return{dragOver:l,dropAction:f,resetDragState:h,handleDragEnter:m,handleDragOver:k,handleDragLeave:S,handleDrop:p}}function Ih(e,s){const r=new Set(s.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=s.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function Mh({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,u]=o.useState(r??[]),[f,d]=o.useState(null),h=o.useRef(null),m=o.useRef(null),k=o.useRef(n),S=o.useRef(a);o.useEffect(()=>{k.current=n},[n]),o.useEffect(()=>{S.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(j=>{const w=Ih(j,e);return w.length===j.length&&w.every((b,E)=>b===j[E])?j:w})},[e]);const p=o.useMemo(()=>{const j=f??l;if(j.length===0)return e;const w=new Map(j.map((b,E)=>[b,E]));return[...e].sort((b,E)=>{const A=w.get(b.tabKey)??999,I=w.get(E.tabKey)??999;return A-I})},[e,f,l]);o.useEffect(()=>{var w,b;if(p.length===0){i!==null&&(c(null),(w=k.current)==null||w.call(k,null));return}if(i&&p.some(E=>E.tabKey===i))return;const j=p[0].tabKey;j!==i&&(c(j),(b=k.current)==null||b.call(k,j))},[p,i]);const x=o.useMemo(()=>p.find(j=>j.tabKey===i),[p,i]),v=o.useCallback(j=>{var w;c(j),(w=k.current)==null||w.call(k,j)},[]),g=o.useCallback((j,w,b)=>{u(E=>{var O;const A=E.filter(V=>V!==j),I=A.indexOf(w);if(I<0)return E;const P=b==="left"?I:I+1;return A.splice(P,0,j),(O=S.current)==null||O.call(S,A),A}),d(null)},[]),N=o.useCallback((j,w,b)=>{const A=(l.length>0?l:e.map(O=>O.tabKey)).filter(O=>O!==j),I=A.indexOf(w);if(I<0)return;const P=b==="left"?I:I+1;A.splice(P,0,j),h.current=A,d(A)},[l,e]),M=o.useCallback(()=>{var w;const j=h.current;j&&(u(j),(w=S.current)==null||w.call(S,j))},[]),y=o.useCallback(()=>{h.current=null,d(null)},[]),C=o.useCallback(j=>{u(w=>{var E;const b=w.filter(A=>A!==j);return b.push(j),(E=S.current)==null||E.call(S,b),b})},[]);return{activeTabId:i,activeConv:x,sortedConversations:p,previewOrderRef:h,draggingTabRef:m,selectTab:v,handleTabReorder:g,updatePreviewOrder:N,commitPreviewOrder:M,clearPreviewOrder:y,moveTabToEnd:C,setDraggingTabKey:j=>{m.current=j}}}function Ah({dropAction:e,canSplit:s}){return t.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[t.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:s?1:.45},children:t.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"})}),t.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:t.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"})}),t.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:s?1:.45},children:t.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 za({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:i}){if(a)return t.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!r&&!n,l=n&&!!i,u=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",f=n?dc: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&&!s?t.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[t.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),t.jsxs("div",{className:"text-center max-w-lg",children:[t.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:u}),t.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:f}),l&&t.jsx("div",{className:"flex items-center justify-center mb-4",children:t.jsxs("button",{type:"button",onClick:i,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:$t,"aria-label":$t,children:[t.jsx(Ii,{size:14}),t.jsx("span",{children:$t})]})}),c&&t.jsx(Hc,{}),c&&t.jsx("div",{className:"mt-8",children:t.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 →"})})]})]}):t.jsx("div",{className:"text-sm text-text-muted opacity-50",children:s?"Move a tab here to view":"No active agent"})}const Vc="adhdev-tab-shortcuts";function Gc(){try{return JSON.parse(localStorage.getItem(Vc)||"{}")}catch{return{}}}function qc({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>Gc()),[l,u]=o.useState(null),f=o.useCallback(h=>{const m=[];return h.metaKey&&m.push(a?"⌘":"Meta"),h.ctrlKey&&m.push("Ctrl"),h.altKey&&m.push(a?"⌥":"Alt"),h.shiftKey&&m.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(m.push(h.key.length===1?h.key.toUpperCase():h.key),m.join("+"))},[a]),d=o.useCallback(h=>{c(h);try{localStorage.setItem(Vc,JSON.stringify(h))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const h=m=>{if(m.preventDefault(),m.stopPropagation(),m.key==="Escape"){u(null);return}const k=f(m);if(!k)return;const S={...i};for(const[p,x]of Object.entries(S))x===k&&delete S[p];S[l]=k,d(S),u(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,i,d,f]),o.useEffect(()=>{if(!e)return;const h=m=>{if(!(!m.ctrlKey&&!m.metaKey&&!m.altKey)){for(const[k,S]of Object.entries(i))if(s.includes(k)&&f(m)===S){m.preventDefault(),r(),n(k);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,i,s,r,n,f]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const Th=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:f,onConversationActivated:d,onPreviewReorder:h,onReorderTab:m,onCommitPreviewOrder:k,onClearPreviewOrder:S,onDragStateReset:p,onDragTabKeyChange:x,onReceiveTab:v,onOpenContextMenu:g,longPressTimer:N,isGroupActive:M}){const y=As(s),C=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",j=y.isReconnecting,w=o.useCallback(R=>{l.current=s.tabKey,x(s.tabKey),R.dataTransfer.setData("text/tab-key",s.tabKey),R.dataTransfer.effectAllowed="move"},[s.tabKey,l,x]),b=o.useCallback(()=>{l.current=null,x(null),k(),S(),p()},[l,x,k,S,p]),E=o.useCallback(R=>{const G=l.current;if(!(!G||G===s.tabKey)&&R.dataTransfer.types.includes("text/tab-key")){R.preventDefault(),R.stopPropagation();const B=R.currentTarget.getBoundingClientRect(),$=R.clientX<B.left+B.width/2?"left":"right";h(G,s.tabKey,$)}},[s.tabKey,l,h]),A=o.useCallback(R=>{R.preventDefault(),R.stopPropagation();const G=R.dataTransfer.getData("text/tab-key");if(G&&G!==s.tabKey){const B=R.currentTarget.getBoundingClientRect(),$=R.clientX<B.left+B.width/2?"left":"right";c.includes(G)?m(G,s.tabKey,$):v&&v(G)}S()},[s.tabKey,c,m,v,S]),I=o.useCallback(R=>{R.stopPropagation(),u(),f(s.tabKey),d(s)},[s,d,u,f]),P=o.useCallback(R=>{R.preventDefault(),g(R.clientX,R.clientY,s.tabKey)},[s.tabKey,g]),O=o.useCallback(R=>{const G=R.touches[0];N.current=setTimeout(()=>{g(G.clientX,G.clientY,s.tabKey)},600)},[s.tabKey,N,g]),V=o.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),L=["adhdev-dockview-tab",C,r&&"is-active",M&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:L,draggable:!0,onDragStart:w,onDragEnd:b,onDragOver:E,onDrop:A,onClick:I,onContextMenu:P,onTouchStart:O,onTouchEnd:V,onTouchMove:V,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?t.jsx("div",{className:"tab-spinner"}):y.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.isConnecting?t.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("span",{className:"adhdev-dockview-tab-primary",title:rt(s),children:rt(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(s)}):y.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ts(s),t.jsx("span",{className:"connecting-dots"})]}):ts(s)})]}),i&&t.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,s)=>e.conv===s.conv&&e.isActive===s.isActive&&e.isDraggedTab===s.isDraggedTab&&e.isTaskCompleteUnread===s.isTaskCompleteUnread&&e.shortcut===s.shortcut&&e.conversationKeys===s.conversationKeys&&e.isGroupActive===s.isGroupActive);function Lh({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:m,onDragTabKeyChange:k,onReceiveTab:S,onHideTab:p,isGroupActive:x,allowTabShortcuts:v=!0}){const[g,N]=o.useState(null),M=o.useRef(null),y=o.useRef(null),C=o.useMemo(()=>e.map(P=>P.tabKey),[e]);tr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(g==null?void 0:g.tabKey)||null});const{isMac:j,tabShortcuts:w,shortcutListening:b,setShortcutListening:E,saveShortcuts:A}=qc({enabled:v,sortedTabKeys:e.map(P=>P.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!g)return;const P=O=>{const V=document.querySelector("[data-pane-context-menu]");V&&V.contains(O.target)||N(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[g]),o.useEffect(()=>{const P=y.current;if(!P)return;const O=V=>{Math.abs(V.deltaY)<=Math.abs(V.deltaX)||(V.preventDefault(),P.scrollLeft+=V.deltaY)};return P.addEventListener("wheel",O,{passive:!1}),()=>P.removeEventListener("wheel",O)},[]);const I=o.useCallback((P,O,V)=>{N({x:P,y:O,tabKey:V})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:y,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(P=>t.jsx(Th,{conv:P,isActive:s===P.tabKey,isDraggedTab:a.current===P.tabKey,isTaskCompleteUnread:n.has(P.tabKey),shortcut:v?w[P.tabKey]:void 0,conversationKeys:C,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:m,onDragTabKeyChange:k,onReceiveTab:S,onOpenContextMenu:I,longPressTimer:M,isGroupActive:x},P.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),g&&t.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:g.x,top:g.y},children:[v&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:P=>{P.stopPropagation(),E(g.tabKey),N(null)},children:["⌨ ",w[g.tabKey]?`Change shortcut (${w[g.tabKey]})`:"Set shortcut"]}),w[g.tabKey]&&t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const P={...w};delete P[g.tabKey],A(P),N(null)},children:"✕ Remove shortcut"})]}),p&&t.jsxs(t.Fragment,{children:[v&&t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{p(g.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),v&&b&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>E(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:P=>P.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",j?"⌘+1":"Ctrl+1",", ",j?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Rh({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:u,groupIndex:f,onFocus:d,isSplitMode:h,numGroups:m,onMoveTab:k,onReceiveTab:S,style:p,onActiveTabChange:x,initialActiveTabId:v,initialTabOrder:g,onTabOrderChange:N,onHideTab:M,isFocused:y,allowTabShortcuts:C=!0,onOpenNewSession:j,liveSessionInboxState:w}){const{sendCommand:b}=jt(),E=o.useRef(null),{activeTabId:A,activeConv:I,sortedConversations:P,draggingTabRef:O,selectTab:V,handleTabReorder:L,updatePreviewOrder:R,commitPreviewOrder:G,clearPreviewOrder:B,moveTabToEnd:$,setDraggingTabKey:H}=Mh({conversations:e,initialActiveTabId:v,initialTabOrder:g,onActiveTabChange:x,onTabOrderChange:N}),J=nn({sendDaemonCommand:a,activeConv:I,setActionLogs:i,isStandalone:c}),{dragOver:xe,dropAction:me,resetDragState:ce,handleDragEnter:ge,handleDragOver:be,handleDragLeave:we,handleDrop:z}=Ch({conversations:e,numGroups:m,onMoveTab:k,onReceiveTab:S,onOwnTabDrop:$,onClearPreviewOrder:B}),U=I&&!qe(I)&&Ts(I)==="terminal",Q=o.useMemo(()=>I?s.find(te=>te.id===I.routeId):void 0,[s,I]),de=o.useMemo(()=>I?n.filter(te=>te.routeId===I.tabKey):[],[n,I]),re=o.useMemo(()=>new Set(P.filter(te=>iu(te,w,{isOpenConversation:te.tabKey===A})).map(te=>te.tabKey)),[A,w,P]);tr("PaneGroup",{groupIndex:f,conversationCount:e.length,activeTabId:A,dragOver:xe});const le=o.useCallback(te=>{te.streamSource==="agent-stream"&&te.agentType&&b(te.routeId,Wc(),{agentType:te.agentType,...te.sessionId&&{targetSessionId:te.sessionId}}).catch(()=>{})},[b]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...p,outline:xe?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Lh,{conversations:P,activeTabId:A,groupIndex:f,numGroups:m,unreadTabKeys:re,draggingTabRef:O,onFocus:d,onSelectTab:V,onConversationActivated:le,onPreviewReorder:R,onReorderTab:L,onCommitPreviewOrder:G,onClearPreviewOrder:B,onDragStateReset:ce,onDragTabKeyChange:H,onMoveTab:k,onReceiveTab:S,onHideTab:M,isGroupActive:y??!1,allowTabShortcuts:C}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ge,onDragOver:be,onDragLeave:we,onDrop:z,children:[xe&&t.jsx(Ah,{dropAction:me,canSplit:!!(m<4&&k)}),I?t.jsx(Fa,{activeConv:I,clearToken:r[I.tabKey]||0,isCliTerminal:!!U,ideEntry:Q,terminalRef:E,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:de,userName:u,isInputActive:!h||!!y}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(za,{conversationsCount:e.length,isSplitMode:h,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:j})})]})]})}function Ph({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:f,isStandalone:d,hasRegisteredMachines:h,userName:m,focusedGroup:k,focusGroup:S,moveTabToGroup:p,splitTabRelative:x,closeGroup:v,handleResizeStart:g,groupActiveTabIds:N,setGroupActiveTab:M,groupTabOrders:y,setGroupTabOrder:C,toggleHiddenTab:j,onOpenNewSession:w,allowTabShortcuts:b=!0,liveSessionInboxState:E}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((A,I)=>{const P=s&&n.length===r?`${n[I]}%`:void 0;return t.jsxs(St.Fragment,{children:[s&&I>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:O=>g(I-1,O),onDoubleClick:()=>v(I),title:"Drag to resize · Double-click to merge",children:t.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),t.jsx(Rh,{style:s?{flexBasis:P??`${100/r}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:A,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:f,isStandalone:d,hasRegisteredMachines:h,userName:m,groupIndex:I,isFocused:s&&k===I,onFocus:()=>S(I),isSplitMode:s,numGroups:r,onMoveTab:(O,V)=>{V==="left"&&I>0?p(O,I-1):V==="right"&&I<r-1?p(O,I+1):V==="split-left"&&r<4?x(O,I,"left"):V==="split-right"&&r<4&&x(O,I,"right")},onReceiveTab:O=>p(O,I),onActiveTabChange:O=>M(I,O),initialActiveTabId:N[I],initialTabOrder:y[I],onTabOrderChange:O=>C(I,O),onHideTab:j,onOpenNewSession:w,allowTabShortcuts:b,liveSessionInboxState:E})]},I)})})}function Yc({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?it.onScreenshot("ide-page",(d,h)=>{if(d!==e)return;const m=new FileReader;m.onload=()=>i(m.result),m.readAsDataURL(h)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var d;return e?((d=it.onStatus)==null?void 0:d.call(it,(h,m)=>{h===e&&m!=null&&m.screenshotUsage&&l(m.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const f=e?it.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&s?f.startScreenshots(s):f.stopScreenshots(s),()=>{f.stopScreenshots(s)}},[n,r,s,e]);const u=o.useCallback(async(f,d)=>{const h=e?it.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(f,d,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const Xc="adhdev-dashboard-action-shortcuts",_h=1200,Dh={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Eh(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function Ze(e,s){switch(e){case"openShortcutHelp":return"?";case"hideCurrentTab":return s?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return s?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return s?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return s?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return s?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return s?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return s?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return s?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return s?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return s?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return s?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return s?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return s?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return s?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return s?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return s?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return s?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return s?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return s?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return s?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return s?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return s?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return s?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function Jc(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:Ze("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:Ze("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:Ze("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:Ze("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:Ze("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:Ze("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:Ze("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:Ze("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:Ze("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:Ze("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:Ze("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:Ze("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:Ze("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:Ze("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:Ze("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:Ze("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:Ze("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:Ze("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:Ze("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:Ze("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:Ze("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:Ze("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:Ze("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:Ze("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:Ze("toggleCliView",e)}]}function ca(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Gr(e){const s=Object.fromEntries(Jc(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Xc)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Dh))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function Qc(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function $h({enabled:e=!0,onTrigger:s}){const r=Eh(),[n,a]=o.useState(()=>Gr(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),f=o.useRef({parts:[],timer:null}),d=o.useCallback(p=>{const x=[];return p.metaKey&&x.push(r?"⌘":"Meta"),p.ctrlKey&&x.push("Ctrl"),p.altKey&&x.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&x.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(x.push(Qc(p.key)),x.join("+"))},[r]),h=o.useCallback(p=>{a(p);try{localStorage.setItem(Xc,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=Gr(r),x=Object.entries(n),v=Object.entries(p);x.length===v.length&&x.every(([g,N])=>p[g]===N)||h(p)},[n,r,h]);const m=o.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),k=o.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},_h))},[]);o.useEffect(()=>{if(!i)return;const p=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){c(null),u([]);return}const v=d(x);if(!v)return;const N=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(v);if(l.length===0&&N){u([v]);return}const y=[...l,v].slice(0,2).join(" "),C={...n};for(const[j,w]of Object.entries(C))w===y&&delete C[j];C[i]=y,h(C),c(null),u([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,d,h,i,l]),o.useEffect(()=>{if(!e||i)return;const p=x=>{if(x.defaultPrevented)return;const v=d(x);if(!v)return;const g=x.metaKey||x.ctrlKey||x.altKey;if(ca(x.target)&&!g)return;const N=f.current.parts,M=g?[v]:[...N.slice(-1),v].slice(-2),y=M.join(" "),C=M[M.length-1],j=Object.entries(n).filter(([,I])=>!!I),w=j.find(([,I])=>I===y);if(w){x.preventDefault(),m(),s(w[0]);return}if(j.some(([,I])=>I.startsWith(`${y} `))){x.preventDefault(),f.current.parts=M,k();return}const E=j.find(([,I])=>I===C);if(E){x.preventDefault(),m(),s(E[0]);return}if(j.some(([,I])=>I.startsWith(`${C} `))){x.preventDefault(),f.current.parts=[C],k();return}m()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,k,e,d,s,m,i]),o.useEffect(()=>()=>m(),[m]);const S=o.useMemo(()=>Jc(r),[r]);return{isMac:r,actionDefinitions:S,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:h}}function Bh({isTabInPopout:e,isTabFloating:s,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(s&&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})):s?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 Zc(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function qo({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!Zc(n):!0}function Kh({previousVisibleConversationCount:e,visibleConversationCount:s,ides:r}){return s>0||e<=0?!1:Zc(r)}const el=o.createContext(null);function on(){const e=o.useContext(el);if(!e)throw new Error("DashboardDockviewContext missing");return e}function _r(e){return rt(e)||e.tabKey}function Oh(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function Yo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Tn(e){var r,n,a,i,c;const s=e==null?void 0:e.defaultView;if(s)try{s.focus(),(n=(r=e==null?void 0:e.body)==null?void 0:r.focus)==null||n.call(r),(i=(a=e==null?void 0:e.documentElement)==null?void 0:a.focus)==null||i.call(a),(c=s.requestAnimationFrame)==null||c.call(s,()=>{var l,u;try{s.focus(),(u=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||u.call(l)}catch{}})}catch{}}function Nr(e,s){e.classList.remove(Fn.className,Un.className),e.classList.add(s==="light"?Fn.className:Un.className)}function Xo(e){return e?Array.from(new Set(e.groups.map(s=>{var r,n;return(n=(r=s.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(s=>!!s&&s!==window))):[]}function Wh(e){const[,s]=o.useState(0);o.useEffect(()=>{const r=()=>s(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 Hh(e,s,r){var c;const n=[s];let a;for(const l of n){let u;for(const f of l){const d=e.addPanel({id:f.tabKey,component:"conversation",title:_r(f),params:{kind:"conversation",tabKey:f.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function Jo(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Lt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of s){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==_r(n)&&a.api.setTitle(_r(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:_r(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function Qo(e,s,r){var u,f;const n=r?Oh(r):null;for(const d of[...e.panels])Lt(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=_t(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=lc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((f=e.panels.find(d=>!Lt(d.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function Fh({params:e,api:s}){var h;const r=on(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=nn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const m=[s.onDidActiveChange(k=>i(k.isActive)),s.onDidActiveGroupChange(k=>{if(!s.isActive&&!k.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const k of m)k.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(m=>m.id===c.routeId):void 0,[r.ides,c]),f=o.useMemo(()=>c?r.actionLogs.filter(m=>m.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:t.jsx(za,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const d=!qe(c)&&Ts(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(Fa,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:d,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((h=r.scrollToBottomRequest)==null?void 0:h.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a})})}function Uh({params:e}){var u;const s=on(),r=o.useMemo(()=>_t([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>s.ides.find(f=>f.id===e.routeId),[s.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=Yc({doId:a,targetSessionId:r?Gi(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?t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:t.jsx(Li,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:l})}):t.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 zh(){const e=on();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(za,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Vh(e){var k,S;Wh(e);const s=on(),r=o.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=_t([...s.conversationsByTabKey.values()],e.params.routeId),x=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,v=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${x?" is-active":""}${v?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Live remote view"}),t.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),t.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):t.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(e.params.tabKey);if(!n)return t.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:t.jsx("div",{className:"adhdev-dockview-tab-copy",children:t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,i=e.api.isGroupActive,c=Qr(n,s.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,u=c.isConnecting,f=c.isGenerating,d=c.isWaiting,h=c.unread,m=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:rt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var x;p.preventDefault(),r(p),s.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((x=p.target)==null?void 0:x.ownerDocument)??document})},children:[h&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?t.jsx("div",{className:"tab-spinner"}):d?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):u?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:rt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ts(n)}):t.jsx("span",{children:ts(n)})})]}),m&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:m,children:m})]})}function Gh({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:u,userName:f,toggleHiddenTab:d,actionShortcuts:h,registerActionHandlers:m,onActiveTabChange:k,onOpenNewSession:S,onRequestScrollToBottom:p,requestedActiveTabKey:x,requestedRemoteIdeId:v,onRequestedActiveTabConsumed:g,scrollToBottomRequest:N,liveSessionInboxState:M,layoutProfile:y}){var ft,Fe,vt;const{theme:C}=Ea(),{sendCommand:j}=jt(),w=o.useRef(null),b=o.useRef(null),E=o.useRef(!1),A=o.useRef(!1),I=o.useRef(!1),P=o.useRef(null),O=o.useRef([]),[V,L]=o.useState(null),[R,G]=o.useState(!1),[B,$]=o.useState(!1),[H,J]=o.useState(0),xe=o.useRef(null),me=o.useRef(typeof window>"u"?{}:kp(y)),ce=o.useMemo(()=>new Map(e.map(K=>[K.tabKey,K])),[e]),ge=o.useMemo(()=>{const K=w.current;return K?K.groups.some(W=>{try{const F=W.model.location.type;return F!=="floating"&&F!=="popout"?!1:W.panels.some(q=>ce.has(q.id))}catch{return!1}}):!1},[ce,H,e]),be=o.useCallback(()=>{var K;(K=w.current)==null||K.focus()},[]),we=o.useCallback((K,W)=>{p==null||p(K,W)},[p]),z=o.useCallback(K=>{const W=document,F=K.document;for(const Me of W.querySelectorAll('link[rel="stylesheet"]')){const se=F.createElement("link");se.rel="stylesheet",se.href=Me.href,Me.crossOrigin&&(se.crossOrigin=Me.crossOrigin),F.head.appendChild(se)}for(const Me of W.querySelectorAll("style")){const se=F.createElement("style");se.textContent=Me.textContent,F.head.appendChild(se)}const q=[];for(const Me of W.styleSheets)try{for(const se of Me.cssRules)se instanceof CSSStyleRule&&(se.selectorText===":root"||se.selectorText==="html")&&q.push(se.cssText)}catch{}if(q.length>0){const Me=F.createElement("style");Me.textContent=q.join(`
|
|
43
|
+
`),F.head.appendChild(Me)}const oe=W.documentElement.getAttribute("data-theme");oe&&F.documentElement.setAttribute("data-theme",oe),F.documentElement.style.colorScheme=oe==="light"?"light":"dark",F.body.className=W.body.className;const ke=W.documentElement.getAttribute("style");ke&&F.documentElement.setAttribute("style",ke);const Ae=F.getElementById("dv-popout-window");Ae instanceof HTMLElement&&(Ae.classList.add("adhdev-dockview"),Nr(Ae,C))},[C]),U=o.useCallback(()=>{var W;const K=w.current;if(K)for(const F of K.groups)try{const q=(W=F.element)==null?void 0:W.ownerDocument;if(!q||q===document)continue;const oe=q.getElementById("dv-popout-window");oe instanceof HTMLElement&&(oe.classList.add("adhdev-dockview"),Nr(oe,C));const ke=document.documentElement.getAttribute("data-theme");ke&&q.documentElement.setAttribute("data-theme",ke),q.documentElement.style.colorScheme=ke==="light"?"light":"dark",q.body.className=document.body.className;const Ae=document.documentElement.getAttribute("style");Ae?q.documentElement.setAttribute("style",Ae):q.documentElement.removeAttribute("style")}catch{}},[C]),Q=o.useCallback(()=>{var W;const K=w.current;if(K)for(const F of K.groups)try{const q=(W=F.element)==null?void 0:W.ownerDocument;if(!q||q===document)continue;const oe=q.getElementById("dv-popout-window");if(!(oe instanceof HTMLElement))continue;oe.classList.add("adhdev-dockview"),Nr(oe,C),oe.classList.toggle("is-showing-dockview-overlay",B),oe.classList.toggle("is-dragging-dockview",R)}catch{}},[R,B,C]),de=o.useCallback(K=>{const W=w.current;if(!W)return;const F=W.getPanel(K);F&&W.addPopoutGroup(F,{popoutUrl:"/popout.html",onDidOpen:({window:q})=>{z(q),he();const oe=ce.get(K);q.document.title=oe?`${rt(oe)} — ADHDev`:"ADHDev — Popout"}})},[ce,z]),re=o.useCallback(K=>{const W=w.current,F=W==null?void 0:W.getPanel(K);if(!W||!F)return;const q=W.groups.filter(oe=>{var ke;try{return((ke=oe.element)==null?void 0:ke.ownerDocument)===document}catch{return!0}});q.length>0?F.api.moveTo({group:q[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),le=o.useCallback(K=>{var q;const W=w.current;if(!W)return!1;const F=W.getPanel(K);if(!F)return!1;try{return((q=F.group.element)==null?void 0:q.ownerDocument)!==document}catch{return!1}},[]),te=o.useCallback(K=>{le(K)&&re(K),d(K)},[le,re,d]),fe=o.useCallback(K=>{const W=w.current,F=W==null?void 0:W.getPanel(K);!W||!F||W.addFloatingGroup(F,{width:600,height:500})},[]),ne=o.useCallback(K=>{var F;const W=(F=w.current)==null?void 0:F.getPanel(K);if(!W)return!1;try{return W.group.model.location.type==="floating"}catch{return!1}},[]),ie=o.useCallback(()=>{var W,F;const K=(F=(W=w.current)==null?void 0:W.activePanel)==null?void 0:F.id;return!K||Lt(K)?null:ce.has(K)?K:null},[ce]),ae=o.useCallback(K=>{const W=w.current,F=W==null?void 0:W.getPanel(K);if(!W||!F)return;const q=W.groups.filter(oe=>{try{return oe.model.location.type==="grid"}catch{return!0}});q.length>0?F.api.moveTo({group:q[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),ye=o.useCallback(()=>{var ke;const K=w.current;if(!K)return;const F=K.groups.filter(Ae=>{var Me;try{return((Me=Ae.element)==null?void 0:Me.ownerDocument)===document&&Ae.model.location.type==="grid"}catch{return!1}})[0]||null,q=[...K.panels];for(const Ae of q){const Me=(ke=Ae.group.element)==null?void 0:ke.ownerDocument,se=Ae.group.model.location.type;Me===document&&se==="grid"||(F&&F.id!==Ae.group.id?Ae.api.moveTo({group:F,position:"center"}):Ae.api.moveTo({position:"center"}))}const oe=K.activePanel;oe&&(oe.group.model.openPanel(oe),oe.api.setActive()),Tn(document)},[]),he=o.useCallback(()=>{var W,F;const K=w.current;if(K)for(const q of K.groups){const oe=(W=q.element)==null?void 0:W.ownerDocument;if(!oe||oe===document)continue;const ke=oe.getElementById("dv-popout-window");if(!(ke instanceof HTMLElement))continue;let Ae=null,Me=oe.title||"ADHDev",se="Popout workspace";const je=q.activePanel;if(je)if(Ae=je.id,Lt(je.id)){const _e=((F=je.params)==null?void 0:F.routeId)||je.id.slice(7),_=_t([...ce.values()],_e);Me=lc(_),se=_!=null&&_.machineName?`Remote view · ${_.machineName}`:"Remote view"}else{const _e=ce.get(je.id);Me=_e?rt(_e):je.title||je.id,se=_e?ts(_e):"Dockview panel"}oe.title=`${Me} — ADHDev`;const Oe=Array.from(oe.querySelectorAll("#adhdev-popout-header"));for(const _e of Oe)_e.remove();const ze=oe.createElement("div");ze.id="adhdev-popout-header",oe.body.appendChild(ze),ze.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(";")),ze.innerHTML=`
|
|
44
|
+
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
45
|
+
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
46
|
+
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Yo(Me)}</div>
|
|
47
|
+
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Yo(se)}</div>
|
|
48
|
+
</div>
|
|
49
|
+
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
50
|
+
<button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
|
|
51
|
+
<button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
|
|
52
|
+
</div>
|
|
53
|
+
`,ke.style.top="52px",ke.style.height="calc(100% - 52px)";const Ye=ze.querySelector("[data-adhdev-popout-focus]");Ye&&(Ye.onclick=()=>{window.focus()});const Ve=ze.querySelector("[data-adhdev-popout-dock]");Ve&&(Ve.disabled=!Ae,Ve.style.opacity=Ae?"1":"0.5",Ve.style.cursor=Ae?"pointer":"default",Ve.onclick=()=>{var _e;Ae&&re(Ae),(_e=oe.defaultView)==null||_e.focus()})}},[ce,re]),Se=o.useCallback(K=>{var q;const W=w.current,F=W==null?void 0:W.getPanel(K);if(!(!W||!F)){F.group.model.openPanel(F),F.api.setActive(),we(K,"dockview-shortcut");try{const oe=F.group.model.location;oe.type==="popout"?oe.getWindow().focus():Tn((q=F.group.element)==null?void 0:q.ownerDocument)}catch{}}},[we]),T=o.useCallback(K=>{const W=w.current,F=W==null?void 0:W.activePanel,q=(W==null?void 0:W.activeGroup)||(F==null?void 0:F.group);if(!W||!F||!q)return;const oe=q.panels||[];if(oe.length<=1)return;const ke=oe.findIndex(se=>se.id===F.id);if(ke<0)return;const Ae=(ke+K+oe.length)%oe.length,Me=oe[Ae];Me&&(Me.group.model.openPanel(Me),Me.api.setActive(),Lt(Me.id)||we(Me.id,"dockview-shortcut"))},[we]),D=o.useCallback(K=>{var Ye;const W=w.current,F=(W==null?void 0:W.activeGroup)||((Ye=W==null?void 0:W.activePanel)==null?void 0:Ye.group);if(!W||!F)return;const q=W.groups||[],oe=q.find(Ve=>Ve.id===F.id);if(!oe)return;const ke=oe.element.getBoundingClientRect(),Ae=ke.left+ke.width/2,Me=ke.top+ke.height/2,se=(Ve,_e,_,ee)=>Math.max(0,Math.min(_e,ee)-Math.max(Ve,_)),je=Ve=>{const _e=Ve.element.getBoundingClientRect(),_=_e.left+_e.width/2,ee=_e.top+_e.height/2;let ue=0,Pe=0,Ce=0,Te=!1;if(K==="left"?(Te=_<Ae,ue=Math.max(0,ke.left-_e.right),Pe=Math.abs(ee-Me),Ce=se(ke.top,ke.bottom,_e.top,_e.bottom)):K==="right"?(Te=_>Ae,ue=Math.max(0,_e.left-ke.right),Pe=Math.abs(ee-Me),Ce=se(ke.top,ke.bottom,_e.top,_e.bottom)):K==="above"?(Te=ee<Me,ue=Math.max(0,ke.top-_e.bottom),Pe=Math.abs(_-Ae),Ce=se(ke.left,ke.right,_e.left,_e.right)):(Te=ee>Me,ue=Math.max(0,_e.top-ke.bottom),Pe=Math.abs(_-Ae),Ce=se(ke.left,ke.right,_e.left,_e.right)),!Te)return Number.POSITIVE_INFINITY;const Le=Ce>0?0:120;return ue*3+Pe+Le};let Oe=null,ze=Number.POSITIVE_INFINITY;for(const Ve of q){if(Ve.id===oe.id)continue;const _e=je(Ve);Number.isFinite(_e)&&(_e>=ze||(ze=_e,Oe=Ve))}return Oe||void 0},[]),Y=o.useCallback(K=>{var q;const W=D(K);if(!W)return;const F=W.activePanel||W.panels[0];F&&(W.model.openPanel(F),F.api.setActive(),Lt(F.id)||we(F.id,"dockview-focus"),Tn((q=W.element)==null?void 0:q.ownerDocument))},[D,we]),X=o.useCallback((K,W)=>{const F=w.current,q=F==null?void 0:F.activePanel,oe=(F==null?void 0:F.activeGroup)||(q==null?void 0:q.group);if(!F||!q||!oe)return;let ke=D(K);!ke&&(W!=null&&W.createGroupIfMissing)&&(ke=F.addGroup({referenceGroup:oe,direction:K})),ke&&(q.api.moveTo({group:ke,position:"center"}),q.group.model.openPanel(q),q.api.setActive(),Lt(q.id)||we(q.id,W!=null&&W.createGroupIfMissing?"dockview-split":"dockview-move"))},[D,we]),{isMac:pe,tabShortcuts:Ie,shortcutListening:Ne,setShortcutListening:Be,saveShortcuts:He}=qc({sortedTabKeys:e.map(K=>K.tabKey),onFocus:be,onSelectTab:Se}),Ue=o.useCallback(()=>{var F;const K=w.current;if(!K)return;const W=K.activePanel;if(W){if(Lt(W.id)){const q=((F=W.params)==null?void 0:F.routeId)||W.id.slice(7),oe=_t(e,q);oe!=null&&oe.tabKey&&Be(oe.tabKey);return}ce.has(W.id)&&Be(W.id)}},[ce,Se,Be,e]),Qe=o.useCallback(K=>{const W=[];return K.metaKey&&W.push(pe?"⌘":"Meta"),K.ctrlKey&&W.push("Ctrl"),K.altKey&&W.push(pe?"⌥":"Alt"),K.shiftKey&&K.key.length!==1&&W.push(pe?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(K.key)?null:(W.push(Qc(K.key)),W.join("+"))},[pe]),tt=o.useCallback(K=>{var W,F;switch(K){case"splitActiveTabRight":X("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":X("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const q=ie();q&&fe(q);return}case"popoutActiveTab":{const q=ie();q&&de(q);return}case"dockActiveTab":{const q=ie();if(!q)return;le(q)?re(q):ne(q)&&ae(q);return}case"focusLeftPane":Y("left");return;case"focusRightPane":Y("right");return;case"focusUpPane":Y("above");return;case"focusDownPane":Y("below");return;case"moveActiveTabToLeftPane":X("left");return;case"moveActiveTabToRightPane":X("right");return;case"moveActiveTabToUpPane":X("above");return;case"moveActiveTabToDownPane":X("below");return;case"selectPreviousGroupTab":T(-1);return;case"selectNextGroupTab":T(1);return;case"setActiveTabShortcut":Ue();return;case"hideCurrentTab":{const q=(F=(W=w.current)==null?void 0:W.activePanel)==null?void 0:F.id;q&&!Lt(q)&&te(q);return}default:return}},[T,ae,Y,fe,ie,te,ne,le,re,X,de,Ue]);o.useEffect(()=>{if(!V)return;const K=V.sourceDocument,W=K.defaultView??window,F=q=>{const oe=K.querySelector("[data-dockview-tab-context-menu]");oe&&oe.contains(q.target)||L(null)};return W.addEventListener("mousedown",F,!0),W!==window&&window.addEventListener("mousedown",()=>L(null),!0),()=>{W.removeEventListener("mousedown",F,!0),W!==window&&window.removeEventListener("mousedown",()=>L(null),!0)}},[V]);const ct=o.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:ce,hasDetachedConversationPanels:ge,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:S,liveSessionInboxState:M,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:te,userName:f,scrollToBottomRequest:N,tabShortcuts:Ie,openTabContextMenu:({x:K,y:W,tabKey:F,sourceDocument:q})=>L({x:K,y:W,tabKey:F,sourceDocument:q??document}),popoutTab:de,moveTabBackToMain:re,isTabInPopout:le,floatTab:fe,isTabFloating:ne}),[n,s,ce,ge,r,c,l,S,M,a,i,te,f,N,Ie,de,re,le,fe,ne]),ut=V?Bh({isTabInPopout:le(V.tabKey),isTabFloating:ne(V.tabKey),tabShortcut:Ie[V.tabKey],actionShortcuts:h}):[],mt=o.useCallback(K=>{var q;const W=w.current;if((((q=W==null?void 0:W.activePanel)==null?void 0:q.id)??null)===K.id){K.group.model.openPanel(K);return}K.group.model.openPanel(K),K.api.setActive()},[]),Xe=o.useCallback((K,W="requested-tab")=>{if(!K)return!1;const F=w.current;if(!F)return!1;const q=F.getPanel(K);return q?(mt(q),we(K,W),g==null||g(),!0):!1},[mt,g,we]),at=o.useCallback(()=>{if(I.current)return!1;const K=Xe(P.current,"stored-layout-restore");return K&&(I.current=!0),K},[Xe]),ve=o.useCallback(()=>{var W;const K=w.current;K&&jp(y,{activeTabId:((W=K.activePanel)==null?void 0:W.id)??null,layout:K.toJSON()})},[y]),Ee=o.useCallback(()=>{Sp(y,me.current)},[y]),Ke=o.useCallback(K=>{var q,oe,ke,Ae;const W=w.current;if(!W)return{kind:"grid"};const F=W.toJSON();for(const Me of F.floatingGroups||[])if((oe=(q=Me.data)==null?void 0:q.views)!=null&&oe.includes(K)&&Me.position)return{kind:"floating",position:Me.position};for(const Me of F.popoutGroups||[])if((Ae=(ke=Me.data)==null?void 0:ke.views)!=null&&Ae.includes(K))return{kind:"popout",position:Me.position,popoutUrl:Me.url};return{kind:"grid"}},[]),ot=o.useCallback(K=>{const W=w.current;if(!W)return;const F=W.getPanel(K),q=me.current[K];if(!F||!q||q.kind==="grid")return;if(F.group.model.location.type===q.kind){delete me.current[K],Ee();return}if(q.kind==="floating"){W.addFloatingGroup(F,{x:q.position.left??24,y:q.position.top??24,width:q.position.width,height:q.position.height}),delete me.current[K],Ee();return}delete me.current[K],Ee()},[Ee]);o.useEffect(()=>(m==null||m({setShortcutForActiveTab:Ue,restoreHiddenTabToSavedLocation:ot,activateConversationTab:Se,resetAllPanelsToMain:ye,activatePreviousTabInGroup:()=>T(-1),activateNextTabInGroup:()=>T(1),floatActiveTab:()=>{const K=ie();K&&fe(K)},popoutActiveTab:()=>{const K=ie();K&&de(K)},dockActiveTab:()=>{const K=ie();K&&(le(K)?re(K):ne(K)&&ae(K))},splitActiveTabRight:()=>X("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>X("below",{createGroupIfMissing:!0}),focusLeftPane:()=>Y("left"),focusRightPane:()=>Y("right"),focusUpPane:()=>Y("above"),focusDownPane:()=>Y("below"),moveActiveTabToLeftPane:()=>X("left"),moveActiveTabToRightPane:()=>X("right"),moveActiveTabToUpPane:()=>X("above"),moveActiveTabToDownPane:()=>X("below")}),()=>m==null?void 0:m(null)),[T,ae,fe,Y,ie,ne,le,X,re,de,m,ye,ot,Se,Ue]);const nt=o.useCallback(()=>{const K=b.current;if(!K)return;const W=K.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const F of W)F.setAttribute("data-adhdev-force-hidden","true")},[]),yt=o.useCallback(()=>{const K=b.current;if(!K)return;const W=K.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const F of W)F.removeAttribute("data-adhdev-force-hidden")},[]),Z=o.useCallback(()=>{const K=b.current;if(!K)return;const W=K.querySelectorAll(".dv-drop-target-container");for(const oe of W)oe.remove();const F=K.querySelectorAll(".dv-drop-target-dropzone");for(const oe of F)oe.remove();const q=K.querySelectorAll(".dv-drop-target");for(const oe of q)oe.classList.remove("dv-drop-target")},[]),Re=o.useCallback(()=>{G(!1),$(!1),yt(),nt(),Z(),!(typeof window>"u")&&(xe.current!=null&&window.clearTimeout(xe.current),window.requestAnimationFrame(()=>{nt(),Z()}),xe.current=window.setTimeout(()=>{nt(),Z(),xe.current=null},80))},[yt,nt,Z]),De=o.useCallback(K=>{var F;w.current=K.api;const W=wp(y);if(P.current=(W==null?void 0:W.activeTabId)??null,W!=null&&W.layout&&K.api.fromJSON(W.layout,{reuseExistingPanels:!1}),A.current=qo({hasStoredLayout:!!(W!=null&&W.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:r}),A.current||(Jo(K.api,e),Qo(K.api,e,v)),K.api.totalPanels===0&&e.length>0){const q=Hh(K.api,e,x);if(q){const oe=K.api.getPanel(q);oe&&mt(oe)}}else!A.current&&!Xe(x)&&at();E.current=!0,K.api.onDidActivePanelChange(q=>{var ke;if(P.current=(q==null?void 0:q.id)??null,I.current=!0,he(),q&&Lt(q.id)){const Ae=((ke=q.params)==null?void 0:ke.routeId)||q.id.slice(7),Me=_t(e,Ae);k((Me==null?void 0:Me.tabKey)??null),ve();return}if(k((q==null?void 0:q.id)??null),ve(),!q)return;const oe=ce.get(q.id);(oe==null?void 0:oe.streamSource)==="agent-stream"&&oe.agentType&&j(oe.routeId,Wc(),{agentType:oe.agentType,...oe.sessionId&&{targetSessionId:oe.sessionId}}).catch(()=>{})}),K.api.onDidLayoutChange(()=>{ve(),he(),J(q=>q+1)}),K.api.onWillDragPanel(()=>{G(!0),$(!1),nt()}),K.api.onWillDragGroup(()=>{G(!0),$(!1),nt()}),K.api.onWillShowOverlay(()=>{yt(),$(!0)}),K.api.onDidMovePanel(Re),K.api.onDidDrop(Re),K.api.onDidAddGroup(q=>{requestAnimationFrame(()=>{var oe,ke;try{const Ae=(oe=q.element)==null?void 0:oe.ownerDocument;if(!Ae||Ae===document)return;(ke=Ae.getElementById("dv-popout-window"))==null||ke.classList.add("adhdev-dockview");const Me=document.documentElement.getAttribute("data-theme");Me&&Ae.documentElement.setAttribute("data-theme",Me),Ae.body.className=document.body.className;const se=document.documentElement.getAttribute("style");se&&Ae.documentElement.setAttribute("style",se)}catch{}he(),J(Ae=>Ae+1)})}),k(((F=K.api.activePanel)==null?void 0:F.id)??null)},[mt,Xe,Re,yt,ce,r,u,y,nt,k,ve,x,v,j,he,e]);o.useLayoutEffect(()=>{const K=w.current;if(!K||!E.current||A.current&&qo({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:r}))return;A.current&&(A.current=!1);const W=O.current,F=new Set(W),q=e.map(Oe=>Oe.tabKey),oe=new Set(q),ke=Kh({previousVisibleConversationCount:W.length,visibleConversationCount:e.length,ides:r});let Ae=!1;for(const Oe of W)oe.has(Oe)||ke||(me.current[Oe]=Ke(Oe),Ae=!0);Ae&&Ee(),ke||(Jo(K,e),Qo(K,e,v));const Me=q.filter(Oe=>!F.has(Oe));let se=!1;for(const Oe of Me){const ze=K.getPanel(Oe),Ye=me.current[Oe];if(!ze||!Ye||Ye.kind==="grid")continue;if(ze.group.model.location.type===Ye.kind){delete me.current[Oe],se=!0;continue}if(Ye.kind==="floating"){K.addFloatingGroup(ze,{x:Ye.position.left??24,y:Ye.position.top??24,width:Ye.position.width,height:Ye.position.height}),delete me.current[Oe],se=!0;continue}}if(se&&Ee(),O.current=q,x&&Xe(x))return;!K.activePanel&&K.panels[0]&&mt(K.panels[0]),!!(K.activePanel&&K.getPanel(K.activePanel.id))||at()},[mt,Xe,at,r,u,Ee,Ke,x,v,e]),o.useEffect(()=>{E.current&&Xe(x)},[Xe,x]),o.useEffect(()=>{if(!R||typeof window>"u")return;const K=()=>Re();return window.addEventListener("pointerup",K),window.addEventListener("mouseup",K),window.addEventListener("dragend",K),()=>{window.removeEventListener("pointerup",K),window.removeEventListener("mouseup",K),window.removeEventListener("dragend",K)}},[Re,R]),o.useEffect(()=>()=>{typeof window>"u"||xe.current!=null&&window.clearTimeout(xe.current)},[]),o.useEffect(()=>{const K=F=>{const q=F.target;if(!q)return;const oe=q.querySelector("[data-tab-key]")||q.closest("[data-tab-key]");if(oe){const ke=oe.getAttribute("data-tab-key");if(ke&&F.dataTransfer){const Ae=q.closest(".dv-tab")||oe.closest(".dv-tab")||oe;F.dataTransfer.effectAllowed="move",F.dataTransfer.setData("text/tab-key",ke),Ae instanceof HTMLElement&&F.dataTransfer.setDragImage(Ae,Math.max(12,Math.round(Ae.clientWidth/2)),Math.max(10,Math.round(Ae.clientHeight/2)))}}};window.addEventListener("dragstart",K);const W=Xo(w.current);for(const F of W)F.addEventListener("dragstart",K);return()=>{window.removeEventListener("dragstart",K);for(const F of W)F.removeEventListener("dragstart",K)}},[H]),o.useEffect(()=>{var W;const K=(W=b.current)==null?void 0:W.querySelector(".adhdev-dockview");K instanceof HTMLElement&&Nr(K,C),U(),he(),Q()},[he,Q,U,C]),o.useEffect(()=>{he(),Q()},[he,Q]),o.useEffect(()=>{const K=W=>{if(W.defaultPrevented||Ne)return;const F=Qe(W);if(!F)return;const q=W.metaKey||W.ctrlKey||W.altKey;ca(W.target)&&!q||Gr(pe).setActiveTabShortcut!==F||(W.preventDefault(),W.stopPropagation(),Ue())};return window.addEventListener("keydown",K,!0),()=>window.removeEventListener("keydown",K,!0)},[Qe,pe,Ne,Ue]),o.useEffect(()=>{const K=b.current;if(!K)return;const W=F=>{var Me,se;if(!F.isTrusted)return;const q=(se=(Me=F.target)==null?void 0:Me.closest)==null?void 0:se.call(Me,".dv-scrollable");if(!q)return;F.preventDefault(),F.stopPropagation();const oe=Math.abs(F.deltaX),ke=Math.abs(F.deltaY),Ae=oe>ke?F.deltaX:F.deltaY;q.dispatchEvent(new WheelEvent("wheel",{deltaY:Ae,deltaMode:F.deltaMode,bubbles:!1,cancelable:!0}))};return K.addEventListener("wheel",W,{passive:!1,capture:!0}),()=>K.removeEventListener("wheel",W,{capture:!0})},[]),o.useEffect(()=>{const K=Xo(w.current);if(K.length===0)return;const W=K.map(F=>{let q=[],oe=null;const ke=()=>{oe!=null&&F.clearTimeout(oe),oe=null,q=[]},Ae=()=>{oe!=null&&F.clearTimeout(oe),oe=F.setTimeout(()=>{oe=null,q=[]},1200)},Me=je=>{if(!je.ctrlKey&&!je.metaKey&&!je.altKey)return;const Oe=Qe(je);if(!Oe)return;const ze=Gc();for(const[Ye,Ve]of Object.entries(ze))if(e.some(_e=>_e.tabKey===Ye)&&Ve===Oe){je.preventDefault(),Se(Ye);return}},se=je=>{if(je.defaultPrevented||Ne)return;const Oe=Qe(je);if(!Oe)return;const ze=je.metaKey||je.ctrlKey||je.altKey;if(ca(je.target)&&!ze)return;const Ye=Gr(pe),Ve=Object.entries(Ye).filter(([Le,pt])=>!!pt&&(Le==="splitActiveTabRight"||Le==="splitActiveTabDown"||Le==="floatActiveTab"||Le==="popoutActiveTab"||Le==="dockActiveTab"||Le==="focusLeftPane"||Le==="focusRightPane"||Le==="focusUpPane"||Le==="focusDownPane"||Le==="moveActiveTabToLeftPane"||Le==="moveActiveTabToRightPane"||Le==="moveActiveTabToUpPane"||Le==="moveActiveTabToDownPane"||Le==="selectPreviousGroupTab"||Le==="selectNextGroupTab"||Le==="setActiveTabShortcut"||Le==="hideCurrentTab")),_e=ze?[Oe]:[...q.slice(-1),Oe].slice(-2),_=_e.join(" "),ee=_e[_e.length-1],ue=Ve.find(([,Le])=>Le===_);if(ue){je.preventDefault(),ke(),tt(ue[0]);return}if(Ve.some(([,Le])=>Le.startsWith(`${_} `))){je.preventDefault(),q=_e,Ae();return}const Ce=Ve.find(([,Le])=>Le===ee);if(Ce){je.preventDefault(),ke(),tt(Ce[0]);return}if(Ve.some(([,Le])=>Le.startsWith(`${ee} `))){je.preventDefault(),q=[ee],Ae();return}ke()};return F.addEventListener("keydown",Me),F.addEventListener("keydown",se),()=>{ke(),F.removeEventListener("keydown",Me),F.removeEventListener("keydown",se)}});return()=>{for(const F of W)F()}},[Qe,pe,H,Se,Ne,tt,e]);const st=C==="light"?Fn:Un,Tt=((vt=(Fe=(ft=w.current)==null?void 0:ft.activePanel)==null?void 0:Fe.group.element)==null?void 0:vt.ownerDocument)??document;return t.jsxs(el.Provider,{value:ct,children:[t.jsx("div",{ref:b,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(Vl,{className:`h-full min-h-0 min-w-0 adhdev-dockview${R?" is-dragging-dockview":""}${B?" is-showing-dockview-overlay":""}`,components:{conversation:Fh,remote:Uh},defaultTabComponent:Vh,watermarkComponent:zh,onReady:De,singleTabMode:"default",tabAnimation:"smooth",theme:st,popoutUrl:"/popout.html"})}),V&&zs.createPortal(t.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:V.x,top:V.y},children:ut.map(K=>{if(K.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},K.id);let W=t.jsx(Od,{size:13,className:"shrink-0 opacity-70"}),F=()=>{};switch(K.id){case"dockInWindow":case"dockBackToGrid":W=t.jsx(Hd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ae(V.tabKey),L(null)};break;case"moveBackToMain":W=t.jsx(Kd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{re(V.tabKey),L(null)};break;case"floatAsPanel":W=t.jsx(Wd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{fe(V.tabKey),L(null)};break;case"openInNewWindow":W=t.jsx(Bd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{de(V.tabKey),L(null)};break;case"setShortcut":F=q=>{q.stopPropagation(),Be(V.tabKey),L(null)};break;case"removeShortcut":W=t.jsx(wt,{size:13,className:"shrink-0 opacity-70"}),F=()=>{const q={...Ie};delete q[V.tabKey],He(q),L(null)};break;case"hideTab":W=t.jsx(Ni,{size:13,className:"shrink-0 opacity-70"}),F=()=>{te(V.tabKey),L(null)};break}return t.jsxs("button",{className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${K.tone==="muted"?"text-text-muted":""}`,onClick:F,children:[W,t.jsx("span",{className:"flex-1 min-w-0",children:K.label}),K.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:K.shortcut}):null]},K.id)})}),V.sourceDocument.body),Ne&&zs.createPortal(t.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:()=>Be(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:K=>K.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",pe?"⌘+1":"Ctrl+1",", ",pe?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),Tt.body)]})}const tl="adhdev-recent-launch-args-v1",qh=8;function Yh(e){return String(e||"").trim().replace(/\s+/g," ")}function sl(e,s){return`${e.trim()}::${s.trim()}`}function rl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(tl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Xh(e){if(!(typeof window>"u"))try{window.localStorage.setItem(tl,JSON.stringify(e))}catch{}}function nl(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=rl().byKey[sl(r,n)])==null?void 0:i.items)||[]}function al(e,s,r){var d;const n=String(e||"").trim(),a=String(s||"").trim(),i=Yh(r);if(!n||!a||!i)return;const c=rl(),l=sl(n,a),u=((d=c.byKey[l])==null?void 0:d.items)||[],f=[i,...u.filter(h=>h!==i)].slice(0,qh);c.byKey[l]={items:f},Xh(c)}function ol(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Dr({title:e,description:s,action:r,children:n,className:a="",contentClassName:i=""}){return t.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),s&&t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:s})]}),r?t.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?t.jsx("div",{className:s||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function il({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?Uc(n):null;return t.jsxs(Dr,{title:"Saved history",description:La(),action:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||s,onClick:a,children:s?"Loading…":"Refresh"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:i,children:nf()})]}),children:[l?t.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:t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),t.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:l.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:l.providerSessionId}),t.jsx("div",{className:"mt-1",children:l.metaLine}),l.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:l.updatedLabel}),l.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:l.preview})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:c,disabled:e,children:"Clear"})]})}):t.jsx("div",{className:"text-[11px] text-text-muted",children:"Start fresh, or open saved history when you want continuity."}),r&&t.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function Ln(e){var n;if(!e)return null;const s=e.availableProviders||[];return s.some(a=>a.category==="cli"&&a.installed!==!1)?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":s.some(a=>a.category==="acp"&&a.installed!==!1)?"acp":null}function Cr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Jh({machines:e,ides:s,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:c,onListSavedSessions:l}){var nt,yt;const u=nr(),f=o.useMemo(()=>[...e].sort(va),[e]),[d,h]=o.useState(((nt=f[0])==null?void 0:nt.id)||""),m=o.useMemo(()=>f.find(Z=>Z.id===d)||f[0],[d,f]),k=o.useMemo(()=>((m==null?void 0:m.workspaces)||[]).map(Z=>({id:Z.id,path:Z.path,label:Z.label})),[m]),S=(m==null?void 0:m.defaultWorkspaceId)||null,[p,x]=o.useState(""),[v,g]=o.useState(""),[N,M]=o.useState(Ln(f[0])),[y,C]=o.useState(""),[j,w]=o.useState(""),[b,E]=o.useState([]),[A,I]=o.useState(""),[P,O]=o.useState([]),[V,L]=o.useState(!1),[R,G]=o.useState(!1),[B,$]=o.useState(""),[H,J]=o.useState(!1),[xe,me]=o.useState(()=>ht()),[ce,ge]=o.useState(null),[be,we]=o.useState(!1),[z,U]=o.useState(""),[Q,de]=o.useState(!1),[re,le]=o.useState(""),[te,fe]=o.useState([]),[ne,ie]=o.useState(!1),[ae,ye]=o.useState(""),[he,Se]=o.useState(!1),T=o.useRef(null),D=o.useRef(0);o.useEffect(()=>{var Z;!d&&((Z=f[0])!=null&&Z.id)&&h(f[0].id)},[d,f]),o.useEffect(()=>{!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||u(m.id,{minFreshMs:3e4}).catch(()=>{})},[u,m]);const Y=o.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(Z=>Z.category==="cli"&&Z.installed!==!1),[m]),X=o.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(Z=>Z.category==="acp"&&Z.installed!==!1),[m]),pe=o.useMemo(()=>((m==null?void 0:m.detectedIdes)||[]).map(Z=>({id:Z.type,label:Z.name||Z.type,meta:Z.running?"Detected locally":"Available to open"})),[m]),Ie=o.useMemo(()=>N==="cli"?Y.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"CLI provider"})):N==="acp"?X.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"ACP provider"})):pe,[X,N,Y,pe]);o.useEffect(()=>{var Re;if(!m)return;if(T.current!==m.id){T.current=m.id,x(S||((Re=k[0])==null?void 0:Re.id)||"__home__"),g(""),M(Ln(m)),C(""),w(""),I(""),O([]),G(!1),$(""),me(ht()),U("");return}x(De=>{var st;return De==="__custom__"||De==="__home__"||k.some(Tt=>Tt.id===De)?De:S||((st=k[0])==null?void 0:st.id)||"__home__"}),M(De=>De==="ide"&&pe.length>0||De==="cli"&&Y.length>0||De==="acp"&&X.length>0?De:Ln(m))},[X.length,Y.length,S,pe.length,m,k]),o.useEffect(()=>{var Z;N&&(Ie.some(Re=>Re.id===y)||C(((Z=Ie[0])==null?void 0:Z.id)||""))},[N,Ie,y]);const Ne=o.useCallback(async(Z,Re)=>{const De=D.current+1;return D.current=De,L(!0),$(""),l(Z,Re).then(st=>{D.current===De&&O(st)}).catch(st=>{D.current===De&&(O([]),$(st instanceof Error?st.message:"Could not load saved sessions"))}).finally(()=>{D.current===De&&(L(!1),G(!0))})},[l]),Be=o.useCallback((Z,Re)=>{E(nl(Z,Re))},[]);o.useEffect(()=>{D.current+=1,I(""),me(ht()),!m||!y||N==="ide"?E([]):Be(m.id,y),G(!1),O([]),$(""),L(!1)},[N,Be,Ne,m,y]),o.useEffect(()=>{if(!A)return;const Z=P.find(Re=>Re.providerSessionId===A);Z!=null&&Z.canResume||I("")},[P,A]);const He=p==="__custom__"?v.trim():p==="__home__"?"":((yt=k.find(Z=>Z.id===p))==null?void 0:yt.path)||"",Ue=o.useMemo(()=>m?s.filter(Z=>Z.id!==m.id&&Z.daemonId===m.id).map(Z=>Z.workspace):[],[s,m]),Qe=o.useMemo(()=>((m==null?void 0:m.recentLaunches)||[]).map(Z=>Z.workspace),[m]),tt=o.useCallback(Z=>{const Re=String(Z.workspace||"").trim();if(!Re)return;const De=k.find(st=>Cr(st.path)===Cr(Re));if(De){x(De.id),g("");return}x("__custom__"),g(Re)},[k]),ct=o.useCallback(Z=>{const Re=String(Z.workspace||"").trim();if(!Re)return{workspaceId:null,workspacePath:null};const De=k.find(st=>Cr(st.path)===Cr(Re));return De?{workspaceId:De.id,workspacePath:null}:{workspaceId:null,workspacePath:Re}},[k]),ut=o.useMemo(()=>P.find(Z=>Z.providerSessionId===A)||null,[P,A]),mt=o.useMemo(()=>{var Re;if(N!=="cli"||!m||!y)return null;const Z=((Re=Y.find(De=>De.type===y))==null?void 0:Re.displayName)||y;return{routeId:m.id,daemonId:m.id,providerSessionId:A||void 0,transport:"pty",mode:"chat",agentName:Z,agentType:y,status:"idle",title:Z,messages:[],ideType:y,workspaceName:He,displayPrimary:Z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${m.id}:${y}`,machineName:At(m,{fallbackId:m.id})}},[N,Y,He,m,A,y]),Xe=o.useCallback(()=>{var Re;if(!m)return;x("__custom__"),de(!0),ye("");const Z=sn(m.platform,tn(v.trim(),He,Ue,Qe,m.defaultWorkspacePath,(Re=k.find(De=>De.id===S))==null?void 0:Re.path,k.map(De=>De.path)));ie(!0),n(m.id,Z).then(De=>{le(De.path),g(De.path),fe(De.directories)}).catch(De=>{ye(De instanceof Error?De.message:"Could not load folder")}).finally(()=>ie(!1))},[v,S,Qe,Ue,n,He,m,k]),at=o.useCallback(Z=>{m&&(ie(!0),ye(""),n(m.id,Z).then(Re=>{le(Re.path),g(Re.path),fe(Re.directories)}).catch(Re=>{ye(Re instanceof Error?Re.message:"Could not load folder")}).finally(()=>ie(!1)))},[n,m]),ve=o.useCallback(async()=>{if(!m||!He)return;Se(!0),U("");const Z=await a(m.id,He);if(Se(!1),!Z.ok){U(Z.error||"Could not save workspace");return}U("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,He,m]),Ee=o.useCallback(async()=>{if(!m||!N||!y)return;we(!0),U("");const Z=j.trim()?j.trim().split(/\s+/).filter(Boolean):[],Re=N==="ide"?await i(m.id,y,{workspacePath:He||null}):await c(m.id,N,y,{workspaceId:p!=="__home__"&&p!=="__custom__"?p:null,workspacePath:p==="__custom__"&&He||null,resumeSessionId:N==="cli"&&A?A:null,cliArgs:Z});if(we(!1),!Re.ok){U(Re.error||"Could not start session");return}N!=="ide"&&j.trim()&&(al(m.id,y,j),Be(m.id,y)),r()},[N,j,Be,r,i,c,He,m,A,y,p]),Ke=N?mc(N,N==="cli"&&!!A):"Start",ot=N?fc(N,N==="cli"&&!!A):"Starting…";return m?t.jsxs(t.Fragment,{children:[t.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:t.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:[t.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:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),t.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."})]}),t.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:t.jsx(wt,{size:16})})]}),t.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:[t.jsx(Dr,{title:"Machine",children:t.jsx("select",{value:m.id,onChange:Z=>h(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:be,children:f.map(Z=>t.jsx("option",{value:Z.id,children:At(Z,{fallbackId:Z.id})},Z.id))})}),t.jsxs(Dr,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Xe,disabled:be,children:"Browse…"}),children:[t.jsxs("select",{value:p,onChange:Z=>{const Re=Z.target.value;x(Re),Re==="__custom__"?Xe():U("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:be,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),k.map(Z=>t.jsxs("option",{value:Z.id,children:[Z.id===S?"⭐ ":"",Zr(Z.path,Z.label)||Z.path]},Z.id)),t.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:p==="__home__"?"Launch without a workspace.":He||"Select a workspace folder."}),p==="__custom__"&&He&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Xe,disabled:be,children:[t.jsx(Ss,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ve,disabled:be||he,children:he?"Saving…":"Save workspace"})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:Y.length>0},{id:"ide",label:"IDE",enabled:pe.length>0},{id:"acp",label:"ACP",enabled:X.length>0}].map(Z=>t.jsx("button",{type:"button",className:`btn btn-sm ${N===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>M(Z.id),disabled:!Z.enabled||be,children:Z.label},Z.id))})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:N==="ide"?"Choose IDE":N==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Ie.map(Z=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${y===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>C(Z.id),disabled:be,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.meta})]},Z.id)),Ie.length===0&&t.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),N!=="ide"&&t.jsxs(Dr,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:j,onChange:Z=>w(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:be}),b.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:b.map(Z=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>w(Z),disabled:be,title:Z,children:Z},Z))})]}),N==="cli"&&t.jsx(il,{busy:be,savedSessionsLoading:V,savedSessionsError:B,selectedSession:ut,onRefresh:()=>{!m||!y||Ne(m.id,y)},onOpenHistory:()=>{!m||!y||(J(!0),ol({hasLoadedInitialResults:R,isLoading:V})&&Ne(m.id,y))},onClearSelection:()=>I("")}),z&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${z.includes("saved")||z.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:z})]}),t.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:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:r,disabled:be,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:Ee,disabled:be||!N||!y||p==="__custom__"&&!He,children:[t.jsx(ga,{size:14}),be?ot:Ke]})]})]})}),Q&&t.jsx(an,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:re,directories:te,busy:ne,error:ae,onClose:()=>de(!1),onNavigate:at,onConfirm:Z=>{g(Z),le(Z),x("__custom__"),de(!1)}}),H&&mt&&t.jsx(_a,{activeConv:mt,ides:[],isCreatingChat:!1,isRefreshingHistory:V,savedSessions:P,isSavedSessionsLoading:V,isResumingSavedSessionId:ce,savedHistoryFilters:xe,onSavedHistoryFiltersChange:me,onClose:()=>J(!1),onNewChat:()=>{I(""),J(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!m||!y||Ne(m.id,y)},onResumeSavedSession:Z=>{if(!m||!y||ce||!Z.canResume)return;const Re=ct(Z);I(Z.providerSessionId),tt(Z),ge(Z.providerSessionId),J(!1),we(!0),U(""),c(m.id,"cli",y,{workspaceId:Re.workspaceId,workspacePath:Re.workspacePath,resumeSessionId:Z.providerSessionId}).then(De=>{if(!De.ok){U(De.error||"Could not resume session");return}r()}).finally(()=>{we(!1),ge(De=>De===Z.providerSessionId?null:De)})}})]}):null}function Qh({isMobile:e,showMobileChatMode:s,visibleConversationCount:r}){const[n,a]=o.useState(!1),[i,c]=o.useState(!1),[l,u]=o.useState(!1),[f,d]=o.useState(!1),[h,m]=o.useState(!1),[k,S]=o.useState("quickstart"),[p,x]=o.useState("workspace"),v=o.useMemo(()=>!s&&!e,[s,e]),g=o.useCallback(w=>{a(w),w&&c(!1)},[]),N=o.useCallback(w=>{c(w),w&&a(!1)},[]),M=o.useCallback(()=>{S(r===0?"quickstart":"shortcuts"),x("workspace"),u(!0),a(!1),c(!1)},[r]),y=o.useCallback(()=>{u(!1)},[]),C=o.useCallback(()=>{d(!0)},[]),j=o.useCallback(()=>{d(!1)},[]);return o.useEffect(()=>{if(!v){m(!1);return}m(!0);const w=window.setTimeout(()=>{m(!1)},1e4);return()=>window.clearTimeout(w)},[v]),{inboxOpen:n,hiddenOpen:i,shortcutHelpOpen:l,newSessionOpen:f,guideNudgeVisible:h,guideTab:k,shortcutSection:p,isDesktopDashboard:v,setGuideTab:S,setShortcutSection:x,handleInboxOpenChange:g,handleHiddenOpenChange:N,handleOpenShortcutHelp:M,closeShortcutHelp:y,openNewSession:C,closeNewSession:j}}function Zh(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 ex(e){return e instanceof Error?e.message:String(e||"")}function tx(e){const s=ex(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function sx({showMobileChatMode:e,isMobile:s,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetActiveCliViewMode:f,mobileChatConversations:d,hiddenConversations:h,ides:m,actionLogs:k,sendDaemonCommand:S,setActionLogs:p,setCliViewModeOverrides:x,isStandalone:v,initialDataLoaded:g,userName:N,requestedMobileTabKey:M,onRequestedMobileTabConsumed:y,requestedMachineId:C,onRequestedMachineConsumed:j,requestedMobileSection:w,onRequestedMobileSectionConsumed:b,containerRef:E,isSplitMode:A,numGroups:I,groupSizes:P,groupedConvs:O,clearedTabs:V,focusedGroup:L,focusGroup:R,moveTabToGroup:G,splitTabRelative:B,closeGroup:$,handleResizeStart:H,groupActiveTabIds:J,setGroupActiveTab:xe,groupTabOrders:me,setGroupTabOrder:ce,toggleHiddenTab:ge,visibleConversations:be,requestedDesktopTabKey:we,onRequestedDesktopTabConsumed:z,onDesktopActiveTabChange:U,onRequestScrollToBottom:Q,onHideConversation:de,onShowHiddenConversation:re,onShowAllHiddenConversations:le,scrollToBottomRequest:te,machineEntries:fe,layoutProfile:ne,onBrowseMachineDirectory:ie,onSaveMachineWorkspace:ae,onLaunchMachineIde:ye,onLaunchMachineProvider:he,onListMachineSavedSessions:Se,notifications:T,notificationUnreadCount:D,liveSessionInboxState:Y,onMarkNotificationRead:X,onMarkNotificationUnread:pe,onDeleteNotification:Ie}){const Ne=St.useRef(null),{inboxOpen:Be,hiddenOpen:He,shortcutHelpOpen:Ue,newSessionOpen:Qe,guideNudgeVisible:tt,guideTab:ct,shortcutSection:ut,isDesktopDashboard:mt,setGuideTab:Xe,setShortcutSection:at,handleInboxOpenChange:ve,handleHiddenOpenChange:Ee,handleOpenShortcutHelp:Ke,closeShortcutHelp:ot,openNewSession:nt,closeNewSession:yt}=Qh({isMobile:s,showMobileChatMode:e,visibleConversationCount:be.length}),Z=St.useCallback(se=>{var je;zs.flushSync(()=>{re(se)}),(je=Ne.current)==null||je.restoreHiddenTabToSavedLocation(se.tabKey)},[re]),Re=St.useCallback(se=>{var Oe;const je=d.find(ze=>Qn(ze,se))||h.find(ze=>Qn(ze,se));je&&(h.some(ze=>ze.tabKey===je.tabKey)&&Z(je),U(je.tabKey),(Oe=Ne.current)==null||Oe.activateConversationTab(je.tabKey),Q(je.tabKey,"notification-open")),X(se.id),ve(!1)},[Z,h,d,U,X,Q]),De=St.useCallback(()=>{var je;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((je=Ne.current)==null||je.resetAllPanelsToMain(),Ee(!1))},[Ee]),st=St.useCallback(async se=>{var Ve;if(!r)return;const je=(Ve=r.modalButtons)==null?void 0:Ve[se];if(!je)return;const Oe=Js(r);if(!Oe)return;const ze=je.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Ye=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(ze);try{await S(Oe,"resolve_action",{button:je,action:Ye?"approve":"reject",buttonIndex:se,...js(r)})}catch(_e){tx(_e)||console.error("[Shortcut approval] Failed:",_e)}},[r,S]),{isMac:Tt,actionDefinitions:ft,actionShortcuts:Fe,shortcutListening:vt,shortcutListeningDraft:K,setShortcutListening:W,setShortcutListeningDraft:F,saveShortcuts:q}=$h({enabled:mt&&!Ue,onTrigger:se=>{var je,Oe,ze,Ye,Ve,_e,_,ee,ue,Pe,Ce,Te,Le,pt,lt,Ut;if(se==="openShortcutHelp"){Ke();return}if(se==="hideCurrentTab"){r&&de(r);return}if(se==="toggleHiddenTabs"){Ee(!He);return}if(se==="openHistoryForActiveTab"){r&&!qe(r)&&i(r);return}if(se==="openRemoteForActiveTab"){r&&!Je(r)&&!qe(r)&&c(r);return}if(se==="splitActiveTabRight"){(je=Ne.current)==null||je.splitActiveTabRight();return}if(se==="splitActiveTabDown"){(Oe=Ne.current)==null||Oe.splitActiveTabDown();return}if(se==="floatActiveTab"){(ze=Ne.current)==null||ze.floatActiveTab();return}if(se==="popoutActiveTab"){(Ye=Ne.current)==null||Ye.popoutActiveTab();return}if(se==="dockActiveTab"){(Ve=Ne.current)==null||Ve.dockActiveTab();return}if(se==="focusLeftPane"){(_e=Ne.current)==null||_e.focusLeftPane();return}if(se==="focusRightPane"){(_=Ne.current)==null||_.focusRightPane();return}if(se==="focusUpPane"){(ee=Ne.current)==null||ee.focusUpPane();return}if(se==="focusDownPane"){(ue=Ne.current)==null||ue.focusDownPane();return}if(se==="moveActiveTabToLeftPane"){(Pe=Ne.current)==null||Pe.moveActiveTabToLeftPane();return}if(se==="moveActiveTabToRightPane"){(Ce=Ne.current)==null||Ce.moveActiveTabToRightPane();return}if(se==="moveActiveTabToUpPane"){(Te=Ne.current)==null||Te.moveActiveTabToUpPane();return}if(se==="moveActiveTabToDownPane"){(Le=Ne.current)==null||Le.moveActiveTabToDownPane();return}if(se==="triggerPrimaryApprovalAction"){st(0);return}if(se==="triggerSecondaryApprovalAction"){st(1);return}if(se==="triggerTertiaryApprovalAction"){st(2);return}if(se==="setActiveTabShortcut"){(pt=Ne.current)==null||pt.setShortcutForActiveTab();return}if(se==="selectPreviousGroupTab"){(lt=Ne.current)==null||lt.activatePreviousTabInGroup();return}if(se==="selectNextGroupTab"){(Ut=Ne.current)==null||Ut.activateNextTabInGroup();return}!r||!Je(r)||qe(r)||se==="toggleCliView"&&f(u==="chat"?"terminal":"chat")}}),oe=St.useCallback(()=>{ot(),W(null),F([])},[ot,W,F]),ke=St.useMemo(()=>ut==="all"?ft:ft.filter(se=>Zh(se)===ut),[ft,ut]),Ae=St.useCallback(()=>{const se=Object.fromEntries(ft.map(je=>[je.id,""]));q(se)},[ft,q]),Me=St.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const se=Object.fromEntries(ft.map(je=>[je.id,je.defaultShortcut]));q(se)},[ft,q]);return St.useEffect(()=>{const se=je=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?je.metaKey&&je.key.toLowerCase()==="w":je.ctrlKey&&je.key.toLowerCase()==="w")&&(je.preventDefault(),r&&de&&de(r))};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[r,de]),St.useEffect(()=>{if(!Ue||vt)return;const se=je=>{je.key==="Escape"&&(je.preventDefault(),oe())};return window.addEventListener("keydown",se,!0),()=>window.removeEventListener("keydown",se,!0)},[oe,Ue,vt]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(Qm,{activeConv:r,wsStatus:n,isConnected:a,conversations:be,hiddenConversations:h,onOpenHistory:i,onHideConversation:de,onShowConversation:Z,onShowAllHidden:le,onResetPanelsToMain:De,notifications:T,notificationUnreadCount:D,onOpenNotification:Re,onMarkNotificationRead:X,onMarkNotificationUnread:pe,onDeleteNotification:Ie,inboxOpen:Be,onInboxOpenChange:ve,hiddenOpen:He,onHiddenOpenChange:Ee,onOpenNewSession:s?void 0:nt,actionShortcuts:Fe,onOpenRemote:()=>{!r||Je(r)||qe(r)||c(r)},onStopCli:l,activeCliViewMode:u,onSetCliViewMode:f}),e?t.jsx(Nh,{conversations:d,hiddenConversations:h,ides:m,actionLogs:k,sendDaemonCommand:S,setActionLogs:p,setCliViewModeOverrides:x,isStandalone:v,userName:N,requestedActiveTabKey:M,onRequestedActiveTabConsumed:y,requestedMachineId:C,onRequestedMachineConsumed:j,requestedMobileSection:w,onRequestedMobileSectionConsumed:b,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowHiddenConversation:Z,onShowAllHiddenConversations:le,onOpenNewSession:nt,liveSessionInboxState:Y}):s?t.jsx(Ph,{containerRef:E,isSplitMode:A,numGroups:I,groupSizes:P,groupedConvs:O,clearedTabs:V,ides:m,actionLogs:k,sendDaemonCommand:S,setActionLogs:p,isStandalone:v,hasRegisteredMachines:fe.length>0,userName:N,focusedGroup:L,focusGroup:R,moveTabToGroup:G,splitTabRelative:B,closeGroup:$,handleResizeStart:H,groupActiveTabIds:J,setGroupActiveTab:xe,groupTabOrders:me,setGroupTabOrder:ce,toggleHiddenTab:ge,onOpenNewSession:nt,allowTabShortcuts:!1,liveSessionInboxState:Y}):t.jsx(Gh,{visibleConversations:be,clearedTabs:V,ides:m,actionLogs:k,sendDaemonCommand:S,setActionLogs:p,isStandalone:v,hasRegisteredMachines:fe.length>0,initialDataLoaded:g,userName:N,toggleHiddenTab:ge,actionShortcuts:Fe,registerActionHandlers:se=>{Ne.current=se},onActiveTabChange:U,requestedActiveTabKey:we,onRequestedActiveTabConsumed:z,onRequestScrollToBottom:Q,scrollToBottomRequest:te,onOpenNewSession:nt,liveSessionInboxState:Y,layoutProfile:ne}),Qe&&t.jsx(Jh,{machines:fe,ides:m,onClose:yt,onBrowseDirectory:ie,onSaveWorkspace:ae,onLaunchIde:ye,onLaunchProvider:he,onListSavedSessions:Se}),Ue&&t.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:oe,children:t.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:se=>se.stopPropagation(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),t.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."})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:oe,"aria-label":"Close dashboard guide",children:t.jsx(wt,{size:14})})]}),t.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(se=>t.jsx("button",{type:"button",className:`btn btn-sm ${ct===se.id?"btn-primary":"btn-secondary"}`,onClick:()=>Xe(se.id),children:se.label},se.id))}),ct==="overview"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Tt?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),ct==="quickstart"&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),t.jsxs("div",{children:[t.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."]})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]})]})]})]}),ct==="shortcuts"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[t.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(se=>t.jsx("button",{type:"button",className:`btn btn-sm ${ut===se.id?"btn-primary":"btn-secondary"}`,onClick:()=>at(se.id),children:se.label},se.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ae,children:"Disable all"}),t.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:Me,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:ke.map(se=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${vt===se.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:se.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:se.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:se.defaultShortcut})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.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:vt===se.id?K.length>0?`${K.join(" ")} ...`:"Listening...":Fe[se.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{W(se.id),F([])},children:vt===se.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const je={...Fe};je[se.id]="",q(je)},children:"Disable"})]})]})},se.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Tt?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:Ke,className:`fixed right-4 bottom-24 z-40 hidden md:inline-flex items-center rounded-full border border-border-subtle bg-bg-primary/88 backdrop-blur py-2 text-xs text-text-secondary hover:text-text-primary transition-all ${tt?"gap-2 px-2.5":"justify-center w-10 px-0"}`,style:{boxShadow:"0 6px 18px rgba(0,0,0,0.12)"},title:"Dashboard guide","aria-label":"Open dashboard guide",children:[t.jsx("span",{className:"inline-flex items-center justify-center w-5 h-5 rounded-full bg-bg-secondary text-[11px] font-semibold text-text-primary shrink-0",children:"?"}),tt&&t.jsx("span",{children:"Guide"})]})]})}const Rn=[{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 rx({onClose:e}){const[s,r]=o.useState(0),n=Rn[s],a=s===Rn.length-1;return t.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:[t.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:[t.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:t.jsx(wt,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Rn.map((i,c)=>t.jsx("div",{style:{width:c===s?24:8,height:8,borderRadius:4,background:c===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),t.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),t.jsxs("div",{style:{textAlign:"center"},children:[t.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[t.jsx("span",{children:n.icon})," ",n.title]}),t.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&t.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:[t.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&t.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 →"})]}),t.jsx("div",{className:"flex justify-end items-center mt-6",children:t.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),t.jsx("style",{children:`
|
|
54
|
+
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
55
|
+
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
56
|
+
`})]})}function nx({hasExtensions:e,ideName:s,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?t.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[t.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:s}),n.map(i=>{const c=r===i.tabKey,l=i.status==="waiting_approval",u=i.status==="generating";return t.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:[t.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"0 0 6px var(--accent-primary)":"none"}}),i.title,l&&t.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 ax({ideData:e,allIdes:s,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,c]=o.useState(()=>a||"native"),l=o.useMemo(()=>hc(s),[s]),u=o.useMemo(()=>e?Da(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),f=o.useMemo(()=>u.find(p=>p.streamSource==="native"),[u]),d=o.useMemo(()=>u.filter(p=>p.streamSource==="agent-stream"),[u]),h=o.useMemo(()=>e?_t(u,e.id):null,[u,e]);o.useEffect(()=>{a&&c(a)},[a]),o.useEffect(()=>{if(a||!h)return;const p=h.streamSource==="native"?"native":h.tabKey;!p||i===p||i==="native"&&c(p)},[i,h,a]),o.useEffect(()=>{var p;i!=="native"&&(d.some(x=>x.tabKey===i)||c(((p=d[0])==null?void 0:p.tabKey)||"native"))},[i,d]),o.useEffect(()=>{i==="native"&&(f||d[0]&&c(d[0].tabKey))},[i,f,d]);const m=o.useMemo(()=>i==="native"&&f?f:d.find(p=>p.tabKey===i)||h||f||d[0],[i,f,h,d]),k=o.useMemo(()=>d.map(p=>({tabKey:p.tabKey,title:cc(p)||n,status:p.status})),[d,n]),S=o.useCallback(p=>{if(p)return u.find(x=>Qn(x,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[u]);return{activeChatTab:i,setActiveChatTab:c,activeConv:m,conversations:u,extensionTabs:k,hasExtensions:k.length>0,resolveConversationByTarget:S}}function ox({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:i,setActionLogs:c,isStandalone:l,userName:u,onOpenHistory:f,onConversationChange:d,onClose:h}){const[m,k]=o.useState("split"),[S,p]=o.useState(()=>Vt(e)?"native":e.tabKey),x=o.useRef(null),v=o.useMemo(()=>s||r.find(R=>R.id===e.routeId),[e.routeId,s,r]),g=o.useMemo(()=>et((v==null?void 0:v.type)||""),[v==null?void 0:v.type]),{conversations:N,extensionTabs:M,hasExtensions:y}=ax({ideData:v,allIdes:r,connectionStates:n,ideName:g||"IDE",preferredTabKey:Vt(e)?void 0:e.tabKey}),C=o.useMemo(()=>v?_t(N,v.id):null,[v,N]);o.useEffect(()=>{const R=x.current,G={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(x.current=G,!(R&&R.routeId===G.routeId&&R.tabKey===G.tabKey&&R.streamSource===G.streamSource)){if(Vt(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(S==="native"){if(N.some(R=>R.streamSource==="native"))return;(C==null?void 0:C.streamSource)==="agent-stream"&&p(C.tabKey);return}if(!N.some(R=>R.tabKey===S)){if((C==null?void 0:C.streamSource)==="agent-stream"){p(C.tabKey);return}p("native")}},[N,S,C]);const j=o.useMemo(()=>S==="native"?N.find(R=>R.streamSource==="native")||e:N.find(R=>R.tabKey===S)||e,[e,N,S]),w=Ac(j),b=o.useMemo(()=>w.status||w.modalMessage||w.modalButtons?{...j,...w.status?{status:w.status}:{},...w.modalMessage!==void 0?{modalMessage:w.modalMessage}:{},...w.modalButtons!==void 0?{modalButtons:w.modalButtons}:{}}:j,[j,w]),E=sr(b),A=nn({sendDaemonCommand:i,activeConv:b,setActionLogs:c,isStandalone:l}),{connScreenshot:I,screenshotUsage:P,handleRemoteAction:O}=Yc({doId:E,targetSessionId:Gi(b),connState:b.connectionState||"new",viewMode:m}),V=o.useMemo(()=>a.filter(R=>R.routeId===b.tabKey),[a,b.tabKey]);o.useEffect(()=>{d==null||d(b)},[b,d]),o.useEffect(()=>{const R=G=>{G.key==="Escape"&&h()};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[h]);const L=o.useCallback(R=>{R.stopPropagation()},[]);return t.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:h,children:t.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:L,children:[t.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:[t.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[t.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:t.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:[t.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(Ct,{size:16})}),t.jsx("span",{className:"truncate",children:ka(j)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:"Close"})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[t.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(R=>{const G=m===R;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${G?"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:()=>k(R),title:R==="split"?"Split view":"Remote only",children:R==="split"?t.jsx(Cd,{size:15}):t.jsx(Ct,{size:15})},R)})}),t.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),t.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>f(j),title:"Chat History",children:[t.jsx(xa,{size:14,className:"md:mr-1.5"}),t.jsx("span",{className:"hidden md:inline",children:"History"})]}),t.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${m==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[m!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${m==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(nx,{hasExtensions:y,ideName:g||"IDE",activeChatTab:S,extensionTabs:M,onSelectTab:p}),t.jsx(Pi,{activeConv:b,onModalButton:A.handleModalButton}),t.jsx(ra,{activeConv:b,ideEntry:v,showMetaChips:!1,handleSendChat:A.handleSendChat,isSendingChat:A.isSendingChat,sendFeedbackMessage:A.sendFeedbackMessage,handleFocusAgent:A.handleFocusAgent,isFocusingAgent:A.isFocusingAgent,actionLogs:V,userName:u})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${m==="split"?"order-1 md:order-2":""}`,children:t.jsx(Li,{addLog:()=>{},connState:b.connectionState||"new",connScreenshot:I,screenshotUsage:P,transportType:b.transport,onAction:O})})]})]})})}function ix({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=Gm(e);return t.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:[t.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.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:[t.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[t.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",i,"?"]}),t.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:s?"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."})]}),t.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s&&t.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),t.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"}),t.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function cx({historyModal:e,remoteDialog:s,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){var c;return t.jsxs(t.Fragment,{children:[t.jsx(Ym,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&t.jsx(_a,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),s.conversation&&t.jsx(ox,{activeConv:s.conversation,ideEntry:s.ideEntry,ides:s.ides,connectionStates:s.connectionStates,actionLogs:s.actionLogs,sendDaemonCommand:s.sendDaemonCommand,setActionLogs:s.setActionLogs,isStandalone:s.isStandalone,userName:s.userName,onOpenHistory:s.onOpenHistory,onConversationChange:s.onConversationChange,onClose:s.onClose}),r.open&&r.targetConv&&(Je(r.targetConv)||qe(r.targetConv))&&t.jsx(ix,{activeConv:r.targetConv,canSaveAndStop:Je(r.targetConv)&&!qe(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),t.jsx(pc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&t.jsx(rx,{onClose:i.onClose})]})}function lx({daemons:e,targetVersion:s,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:i}){return e.length===0?null:t.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:[t.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:t.jsx(er,{size:14})}),t.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[t.jsxs("span",{children:[r?"Daemon update required":"Update available",s?t.jsxs(t.Fragment,{children:[": ",t.jsxs("strong",{children:["v",s]})]}):null]}),e.map(c=>{const l=At(c,{fallbackId:c.id}),u=n[c.id],f=c.version||c.daemonVersion||"unknown",d=c.versionUpdateRequired===!0;return t.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[t.jsx("span",{className:"font-medium text-text-primary",children:l}),t.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",f]}),d&&t.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?t.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?t.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?t.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):t.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:d?"Update now":"Upgrade"})]},c.id)})]}),!r&&t.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:t.jsx(wt,{size:16})})]})}function dx(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function ux(e){const s=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?s===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 mx(e){const s=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",s,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&s&&s!==r),autoReadKey:i,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function fx(e){const s=e.machine;return typeof(s==null?void 0:s.cpus)!="number"||typeof(s==null?void 0:s.totalMem)!="number"||typeof(s==null?void 0:s.arch)!="string"||typeof(s==null?void 0:s.release)!="string"}function px(e){return{metadataDaemonIds:e.map(s=>s.id),runtimeDaemonIds:e.filter(s=>fx(s)).map(s=>s.id)}}function hx(){var Ja,Qa,Za,eo;const{sendCommand:e}=jt(),s=nr(),r=Mc(),n=fa(),a=Ms(),[i,c]=Gl(),l=i.get("activeTab"),u=((Ja=n.state)==null?void 0:Ja.openRemoteForTabKey)||null,f=((Qa=n.state)==null?void 0:Qa.openMachineId)||null,d=((Za=n.state)==null?void 0:Za.mobileSection)||null,h=nc(),m=h.ides||[],k=h.initialLoaded??!0,{updateRouteChats:S,setToasts:p}=h,[x,v]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),g=h.toasts||[],N=h.wsStatus||"connected",M=h.isConnected??!0,y=h.connectionStates||{},C=h.showReconnected||!1,{layoutProfile:j,groupAssignments:w,updateGroupAssignments:b,focusedGroup:E,updateFocusedGroup:A,focusGroup:I,groupActiveTabIds:P,updateGroupActiveTabIds:O,setGroupActiveTab:V,groupTabOrders:L,updateGroupTabOrders:R,setGroupTabOrder:G,groupSizes:B,updateGroupSizes:$,isMobile:H,hasHydratedStoredLayout:J,hydrateStoredLayout:xe,focusConversationTab:me}=Ip(),[ce,ge]=o.useState(()=>Ka());o.useEffect(()=>zf(ge),[]);const be=o.useMemo(()=>dx({isMobile:H,mobileViewMode:ce}),[H,ce]),[we,z]=o.useState([]),[U,Q]=o.useState({}),[de,re]=o.useState({});tr("Dashboard",{ideCount:m.length,toastCount:g.length,focusedGroup:E,groupCount:Object.keys(w).length,actionLogCount:we.length});const le=o.useMemo(()=>m.filter(We=>We.type==="adhdev-daemon").sort(va),[m]),te=le[0],fe=!!te;o.useEffect(()=>{const{metadataDaemonIds:We,runtimeDaemonIds:kt}=px(le);for(const Dt of We)s(Dt,{minFreshMs:3e4}).catch(()=>{});for(const Dt of kt)r(Dt,{minFreshMs:3e4}).catch(()=>{})},[s,r,le]);const ne=(te==null?void 0:te.terminalBackend)||null,ie=te?At(te,{fallbackId:te.id}):null,ae=(te==null?void 0:te.id)||null,ye=o.useMemo(()=>sp(m,U),[m,U]),{hiddenTabs:he,hideTarget:Se,toggleTarget:T,showTarget:D,showAllTabs:Y}=tp(),{conversations:X,visibleConversations:pe,visibleTabKeys:Ie,resolveConversationBySessionId:Ne,resolveConversationByTarget:Be}=mp({ides:ye,connectionStates:y,clearedTabs:de,hiddenTabs:he}),He=o.useMemo(()=>new Map(X.map(We=>[We.tabKey,We])),[X]);Pm(pe,be),o.useEffect(()=>{Object.keys(U).length!==0&&Q(We=>rp(We,m))},[m,U]);const Ue=o.useMemo(()=>ou(m),[m]),{notifications:Qe,unreadCount:tt}=Hp({conversations:X,liveSessionInboxState:Ue}),{handleMarkDashboardNotificationRead:ct,handleMarkDashboardNotificationUnread:ut,handleDeleteDashboardNotification:mt}=Fp({notifications:Qe,sendDaemonCommand:e}),Xe=o.useRef(null),at=o.useRef(null),ve=o.useRef(null),Ee=o.useRef(null),Ke=o.useRef(null),{containerRef:ot,normalizedGroupAssignments:nt,numGroups:yt,isSplitMode:Z,groupedConvs:Re,moveTabToGroup:De,closeGroup:st,handleResizeStart:Tt,splitTabRelative:ft}=_p({groupAssignments:w,updateGroupAssignments:b,updateFocusedGroup:A,updateGroupActiveTabIds:O,updateGroupTabOrders:R,groupSizes:B,updateGroupSizes:$,isMobile:H,visibleConversations:pe,visibleTabKeys:Ie}),{activeConv:Fe,openDesktopConversation:vt,requestScrollToBottom:K,scrollToBottomRequest:W,setDesktopActiveTab:F}=Zp({isMobile:H,conversations:X,visibleConversations:pe,groupActiveTabIds:P,focusedGroup:E,groupedConvs:Re,setSearchParams:c});o.useEffect(()=>{const We=()=>{ve.current&&(clearTimeout(ve.current),ve.current=null),Ee.current&&(clearTimeout(Ee.current),Ee.current=null),Ke.current&&(document.removeEventListener("visibilitychange",Ke.current),Ke.current=null),at.current=null};if(H){We(),Xe.current=null;return}if(!(Fe!=null&&Fe.sessionId)){We(),Xe.current=null;return}const kt=Or(Fe,Ue),Dt=mx({tabKey:Fe.tabKey,historySessionId:rr(Fe)||"",lastMessageHash:Fe.lastMessageHash||"",lastMessageAt:Number(Fe.lastMessageAt||0),timestamp:es(Fe),liveState:kt}),ir=Dt.autoReadKey,cr=ux({autoReadKey:ir,shouldMarkSeen:Dt.shouldMarkSeen,completedKey:Xe.current,pendingKey:at.current});if(!Dt.shouldMarkSeen){cr.shouldCancelPending&&We(),Xe.current=ir;return}if(!cr.shouldSchedule)return;cr.shouldCancelPending&&We();const to=()=>{if(document.visibilityState!=="visible"||Xe.current===ir)return;Xe.current=ir,at.current=null,ve.current=null,Ee.current=null,Ke.current&&(document.removeEventListener("visibilitychange",Ke.current),Ke.current=null);const lr=Dt.readAt;e(Fe.daemonId||Fe.routeId,"mark_session_seen",{sessionId:Fe.sessionId,seenAt:lr}).catch(()=>{})};if(at.current=cr.nextPendingKey,document.visibilityState==="visible"){ve.current=setTimeout(to,1500);const lr=()=>{document.visibilityState!=="visible"&&ve.current&&(clearTimeout(ve.current),ve.current=null)};Ke.current=lr,document.addEventListener("visibilitychange",lr);return}const so=()=>{document.visibilityState==="visible"&&(Ee.current&&clearTimeout(Ee.current),Ee.current=setTimeout(to,800),Ke.current&&(document.removeEventListener("visibilitychange",Ke.current),Ke.current=null))};Ke.current=so,document.addEventListener("visibilitychange",so)},[Fe,H,Ue,e]),o.useEffect(()=>()=>{ve.current&&clearTimeout(ve.current),Ee.current&&clearTimeout(Ee.current),Ke.current&&document.removeEventListener("visibilitychange",Ke.current)},[]);const{requestedDesktopTabKey:q,requestedMobileTabKey:oe,consumeRequestedActiveTab:ke}=fp({isMobile:H,urlActiveTab:l,resolveConversationBySessionId:Ne,setSearchParams:c}),{remoteDialogConv:Ae,remoteDialogIdeEntry:Me,remoteDialogActiveConv:se,setRemoteDialogActiveConv:je,openRemoteDialog:Oe,closeRemoteDialog:ze,cliStopDialogOpen:Ye,cliStopTargetConv:Ve,requestCliStop:_e,cancelCliStop:_,confirmCliStop:ee}=sh({isMobile:H,location:n,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:q,conversations:X,ides:m,resolveConversationByTarget:Be,activeConv:Fe,sendDaemonCommand:e}),{historyModalOpen:ue,openHistoryModal:Pe,closeHistoryModal:Ce,historyTargetConv:Te,isSavedSessionHistoryTarget:Le,isHistoryCreatingChat:pt,isHistoryRefreshingHistory:lt,handleHistorySwitchSession:Ut,handleHistoryNewChat:pl,handleHistoryRefresh:hl,savedHistorySessions:xl,savedHistoryFilters:bl,setSavedHistoryFilters:gl,isSavedHistoryLoading:yl,resumingSavedHistorySessionId:vl,handleRefreshSavedHistory:wl,handleResumeSavedHistorySession:jl}=eh({activeConv:Fe,remoteDialogConv:Ae,remoteDialogActiveConv:se,ides:m,sendDaemonCommand:e,updateRouteChats:S,setToasts:p,setClearedTabs:re,setSearchParams:c}),kl=o.useMemo(()=>pe,[pe]),or=H&&ce==="chat",Sl=o.useMemo(()=>X.filter(We=>Oa(he,We)),[X,he]),qa=o.useCallback(We=>{const kt=new URLSearchParams(i);kt.set("activeTab",We),c(kt,{replace:!0})},[i,c]),{trackPendingLaunch:Nl}=Yp({ides:m,conversations:X,onOpenSession:qa}),{handleBrowseMachineDirectory:Cl,handleSaveMachineWorkspace:Il,handleLaunchMachineIde:Ml,handleLaunchMachineProvider:Al,handleListMachineSavedSessions:Tl,setActiveCliViewMode:Ll}=Xp({sendDaemonCommand:e,trackPendingLaunch:Nl,onOpenSession:qa,activeConv:Fe,ides:m,setCliViewModeOverrides:Q});np({visibleConversations:pe,clearedTabs:de,setClearedTabs:re,setActionLogs:z}),pp({ides:m,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Be});const{isRefreshingHistory:Rl,handleRefreshHistory:Pl}=Kc({sendDaemonCommand:e,activeConv:Fe,chats:(eo=m.find(We=>We.id===(Fe==null?void 0:Fe.routeId)))==null?void 0:eo.chats,updateRouteChats:S,setToasts:p,setClearedTabs:re});Ap({urlActiveTab:H&&!or?l:null,conversations:X,resolveConversationBySessionId:Ne,normalizedGroupAssignments:nt,hasHydratedStoredLayout:H&&!or?J:!0,hydrateStoredLayout:H&&!or?xe:()=>{},focusConversationTab:me,setSearchParams:c,historyModalOpen:ue,activeConv:Fe,isRefreshingHistory:Rl,ides:m,handleRefreshHistory:Pl});const _l=o.useMemo(()=>!Fe||!Je(Fe)||qe(Fe)?null:Ts(Fe),[Fe]),{versionMismatchDaemons:Dl,hasRequiredVersionDaemons:Ya,appVersion:El,versionBannerDismissed:$l,setVersionBannerDismissed:Bl,upgradingDaemons:Kl,handleBannerUpgrade:Ol}=Dp({ides:m,sendDaemonCommand:e}),Xa=o.useCallback(We=>{D(We),vt(We)},[vt,D]),Wl=o.useCallback(We=>{Se(We)},[Se]);return t.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[t.jsx(Xm,{terminalBackend:ne,isStandalone:fe,machineLabel:ie,machineKey:ae}),(!$l||Ya)&&t.jsx(lx,{daemons:Dl,targetVersion:El,required:Ya,upgradingDaemons:Kl,onUpgrade:Ol,onDismiss:()=>Bl(!0)}),t.jsx(sx,{showMobileChatMode:or,isMobile:H,activeConv:Fe,wsStatus:N,isConnected:M,onOpenHistory:We=>{We&&je(We),Pe()},onOpenRemote:Oe,onStopCli:_e,activeCliViewMode:_l,onSetActiveCliViewMode:Ll,mobileChatConversations:kl,ides:m,actionLogs:we,sendDaemonCommand:e,setActionLogs:z,setCliViewModeOverrides:Q,isStandalone:fe,initialDataLoaded:k,userName:h.userName,requestedMobileTabKey:oe,onRequestedMobileTabConsumed:ke,requestedMachineId:f,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:ot,isSplitMode:Z,numGroups:yt,groupSizes:B,groupedConvs:Re,clearedTabs:de,focusedGroup:E,focusGroup:I,moveTabToGroup:De,splitTabRelative:ft,closeGroup:st,handleResizeStart:Tt,groupActiveTabIds:P,setGroupActiveTab:V,groupTabOrders:L,setGroupTabOrder:G,toggleHiddenTab:We=>T(He.get(We)||{tabKey:We}),visibleConversations:pe,hiddenConversations:Sl,requestedDesktopTabKey:q,onRequestedDesktopTabConsumed:ke,onDesktopActiveTabChange:F,onRequestScrollToBottom:K,onHideConversation:Wl,onShowHiddenConversation:Xa,onShowAllHiddenConversations:Y,scrollToBottomRequest:W,machineEntries:le,layoutProfile:j,onBrowseMachineDirectory:Cl,onSaveMachineWorkspace:Il,onLaunchMachineIde:Ml,onLaunchMachineProvider:Al,onListMachineSavedSessions:Tl,notifications:Qe,notificationUnreadCount:tt,liveSessionInboxState:Ue,onMarkNotificationRead:ct,onMarkNotificationUnread:ut,onDeleteNotification:mt}),t.jsx("style",{children:`
|
|
57
|
+
body { overflow: hidden; overscroll-behavior: none; }
|
|
58
|
+
`}),t.jsx(cx,{historyModal:{open:ue,targetConv:Te,ides:m,isCreatingChat:pt,isRefreshingHistory:Le?!1:lt,savedSessions:xl,savedHistoryFilters:bl,onSavedHistoryFiltersChange:gl,isSavedSessionsLoading:yl,isResumingSavedSessionId:vl,onClose:Ce,onNewChat:pl,onSwitchSession:Ut,onRefreshHistory:Le?wl:hl,onResumeSavedSession:jl},remoteDialog:{conversation:Ae,ideEntry:Me,ides:m,connectionStates:y,actionLogs:we,sendDaemonCommand:e,setActionLogs:z,isStandalone:fe,userName:h.userName,onOpenHistory:We=>{We&&je(We),Pe()},onConversationChange:je,onClose:ze},cliStopDialog:{open:Ye,targetConv:Ve,onCancel:_,onStopNow:async()=>{await ee("hard")},onSaveAndStop:async()=>{await ee("save")}},connectionBanner:{wsStatus:N,showReconnected:C,onReconnect:h.retryServerConnection},toastOverlay:{toasts:g,onDismiss:We=>p(kt=>kt.filter(Dt=>Dt.id!==We)),onClick:We=>{if(We.targetKey){const kt=Be(We.targetKey);kt&&(me(kt.tabKey,nt),Xa(kt),K(kt.tabKey,"toast-open"))}}},onboarding:{open:x,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}v(!1)}}})]})}function xx({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,u]=o.useState(null),[f,d]=o.useState(null),[h,m]=o.useState(!1),[k,S]=o.useState(null),[p,x]=o.useState(!1),[v,g]=o.useState(""),N=o.useRef(null),M=o.useCallback(B=>{N.current=B},[]),y=o.useCallback((B,$,H=!1)=>{c(J=>[...J.slice(-100),{timestamp:Date.now(),level:B,message:$}]),setTimeout(()=>{var J;return(J=a.current)==null?void 0:J.scrollIntoView({behavior:"smooth"})},100),H&&dt.showToast($,B==="error"||B==="warn"?"warning":"success")},[a]),C=o.useCallback(B=>{const $=B instanceof Error?B.message:String(B||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),j=o.useCallback(async(B,$)=>{var H;if(!e||l)return!1;u(B),y("info",`Launching ${et(B)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const J={ideType:B,enableCdp:!0};(H=$==null?void 0:$.workspace)!=null&&H.trim()?J.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(J.useDefaultWorkspace=!0);const xe=await r(e,"launch_ide",J);return y(xe!=null&&xe.success?"info":"error",xe!=null&&xe.success?`${et(B)} launched`:`Failed: ${xe==null?void 0:xe.error}`,!0),!!(xe!=null&&xe.success)}catch(J){return y("error",`Launch error: ${J.message}`,!0),!1}finally{u(null)}},[e,l,y,r]),w=o.useCallback(async B=>{if(!e)return{success:!1};const{cliType:$,dir:H,workspaceId:J,useDefaultWorkspace:xe,useHome:me,argsStr:ce,model:ge,resumeSessionId:be}=B;if(!$)return y("warn","Select a CLI or ACP provider first",!0),{success:!1};const we=ce?ce.split(/\s+/).filter(Boolean):void 0,z=(H==null?void 0:H.trim())||(J?"(saved id)":xe?"(default workspace)":me?"(home)":"");y("info",`Launching ${$}${z?` in ${z}`:""}${ge?` (model: ${ge})`:""}...`),d($);try{const U={cliType:$,cliArgs:we,initialModel:ge||void 0};H!=null&&H.trim()?U.dir=H.trim():J?U.workspaceId=J:xe?U.useDefaultWorkspace=!0:me&&(U.useHome=!0),be&&(U.resumeSessionId=be);const Q=await r(e,"launch_cli",U),de=(Q==null?void 0:Q.result)||Q;return Q!=null&&Q.success?(y("info",`${$} launched`,!0),(de==null?void 0:de.launchSource)==="home"?y("info","📂 Running in home directory (explicit choice)"):(de==null?void 0:de.launchSource)==="defaultWorkspace"&&y("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:de==null?void 0:de.sessionId}):(y("error",`Failed: ${(Q==null?void 0:Q.error)||(de==null?void 0:de.error)}`,!0),(Q==null?void 0:Q.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&S({cliType:$,argsStr:ce,model:ge}),{success:!1,sessionId:de==null?void 0:de.sessionId})}catch(U){return C(U)?(y("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(y("error",`Launch error: ${U.message}`,!0),{success:!1})}finally{d(null)}},[e,y,C,r]),b=o.useCallback(async(B,$,H,J)=>e?B?$.trim()?w({cliType:B,dir:$,argsStr:H,model:J}):(S({cliType:B,argsStr:H,model:J}),{success:!1}):(y("warn","Select a provider",!0),{success:!1}):{success:!1},[e,y,w]),E=o.useCallback(async(B,$,H)=>{if(e&&window.confirm(`Stop ${B}?
|
|
59
|
+
This will terminate the process.`))try{const J=await r(e,"stop_cli",{cliType:B,dir:$,targetSessionId:H});J!=null&&J.success?y("info",`${B} stopped`,!0):y("error",`Stop failed: ${(J==null?void 0:J.error)||"Unknown error"}`,!0)}catch(J){y("error",`Stop failed: ${J.message}`,!0)}},[e,y,r]),A=o.useCallback(async B=>{try{await r(B.daemonId,"restart_ide",{ideType:B.type}),y("info",`${et(B.type)} restart initiated`,!0)}catch($){y("error",`Restart failed: ${$.message}`,!0)}},[y,r]),I=o.useCallback(async B=>{if(window.confirm(`Stop ${et(B.type)}?
|
|
60
|
+
This will disconnect CDP and optionally kill the process.`))try{const $=await r(B.daemonId,"stop_ide",{ideType:B.type,killProcess:!0});$!=null&&$.success?y("info",`${et(B.type)} stopped`,!0):y("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){y("error",`Stop failed: ${$.message}`,!0)}},[y,r]),P=o.useCallback(async()=>{if(e)try{const B=await r(e,"detect_ides",{});y("info",`Found ${((B==null?void 0:B.result)||[]).length} IDE(s)`,!0)}catch(B){y("error",`Detection failed: ${B.message}`,!0)}},[e,y,r]),O=o.useCallback(async B=>{if(!e||!B.trim())return!1;m(!0);try{const $=await r(e,"workspace_add",{path:B.trim()});return $!=null&&$.success?(y("info",`Workspace added: ${B.trim()}`),!0):(y("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return y("error",$.message),!1}finally{m(!1)}},[e,y,r]),V=o.useCallback(async B=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){m(!0);try{const $=await r(e,"workspace_remove",{id:B});$!=null&&$.success?y("info","Workspace removed",!0):y("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){y("error",$.message,!0)}finally{m(!1)}}},[e,y,r]),L=o.useCallback(async B=>{var $;if(e){m(!0);try{const H=await r(e,"workspace_set_default",B===null?{clear:!0}:{id:B});if(H!=null&&H.success){y("info",B?"Default workspace updated":"Default workspace cleared",!0);const J=typeof H.defaultWorkspacePath=="string"?H.defaultWorkspacePath:"";J&&(($=N.current)==null||$.call(N,J))}else y("error",(H==null?void 0:H.error)||"workspace_set_default failed",!0)}catch(H){y("error",H.message,!0)}finally{m(!1)}}},[e,y,r]),R=o.useCallback(async B=>{var H;if(!e||!B.trim())return;const $=B.trim();m(!0);try{const J=await r(e,"workspace_set_default",{path:$});J!=null&&J.success?(y("info","Default workspace set from history"),(H=N.current)==null||H.call(N,$)):y("error",(J==null?void 0:J.error)||"Could not set default (path missing on disk?)")}catch(J){y("error",J.message)}finally{m(!1)}},[e,y,r]),G=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:v}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:v})}catch(B){y("warn",`Live nickname updated, but account sync failed: ${B.message}`)}y("info",`Nickname set to "${v||"(cleared)"}"`),x(!1)}catch(B){y("error",`Failed: ${B.message}`)}},[e,v,s,y,n,r]);return{logs:i,launchingIde:l,launchingAgentType:f,workspaceBusy:h,launchPick:k,setLaunchPick:S,editingNickname:p,setEditingNickname:x,nicknameInput:v,setNicknameInput:g,addLog:y,handleLaunchIde:j,runLaunchCliCore:w,handleLaunchCli:b,handleStopCli:E,handleRestartIde:A,handleStopIde:I,handleDetectIdes:P,handleWorkspaceAdd:O,handleWorkspaceRemove:V,handleWorkspaceSetDefault:L,handleWorkspaceResumePath:R,handleSaveNickname:G,setOnDefaultWorkspaceChanged:M}}function bx({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var A;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:f,handleWorkspaceSetDefault:d}=i,[h,m]=o.useState(!1),[k,S]=o.useState(""),[p,x]=o.useState([]),[v,g]=o.useState(!1),[N,M]=o.useState(""),y=o.useCallback(async I=>{g(!0),M("");try{const P=await rn(c,e,I);S(P.path),x(P.directories)}catch(P){M(P instanceof Error?P.message:"Could not load folder")}finally{g(!1)}},[e,c]),C=o.useCallback(()=>{m(!0);const I=[...r.map(O=>O.workspace),...n.map(O=>O.workspace),...a.map(O=>O.workspace)],P=sn(s.platform,tn(I,s.defaultWorkspacePath,(s.workspaces||[]).map(O=>O.path)));y(P)},[a,n,r,y,s.defaultWorkspacePath,s.platform,s.workspaces]),j=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,w=s.availableMem??s.freeMem??s.totalMem,b=j&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-w)/s.totalMem*100))):0,E=((A=s.loadavg)==null?void 0:A[0])||0;return t.jsxs("div",{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[t.jsx(mr,{icon:t.jsx(Ci,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?du(s.uptime):"Waiting…"}),t.jsx(mr,{icon:t.jsx(Ct,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(mr,{icon:t.jsx(ba,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(mr,{icon:t.jsx(Md,{size:16}),label:"ACPs",value:`${a.length}`})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),t.jsxs("div",{className:"flex gap-6",children:[t.jsx(fo,{value:j?Math.min(Math.round(E/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:j?`${E.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(fo,{value:b,max:100,label:"Memory",color:"#3b82f6",detail:j?`${pn(s.totalMem-w)} / ${pn(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${pn(s.totalMem)} total`})]})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[t.jsx(Ss,{size:14})," Workspaces"]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[t.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),t.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:s.defaultWorkspaceId||"",onChange:I=>void d(I.target.value===""?null:I.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(I=>t.jsx("option",{value:I.id,children:I.label||I.path},I.id))]}),s.defaultWorkspacePath&&t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:s.defaultWorkspacePath,children:s.defaultWorkspacePath})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.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:C,children:"Select workspace…"}),t.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(s.workspaces||[]).length>0&&t.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(s.workspaces||[]).map(I=>t.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:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[I.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:Zr(I.path,I.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:I.path,children:I.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void f(I.id),children:"Remove"})]},I.id))})]}),h&&t.jsx(an,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:k,directories:p,busy:v,error:N,confirmLabel:"Add workspace",onClose:()=>m(!1),onNavigate:I=>{y(I)},onConfirm:I=>{(async()=>{if(!I)return;await u(I)&&m(!1)})()}})]})}function gx(e){if(!e||typeof e!="object")return null;const s=e,r=s.result&&typeof s.result=="object"?s.result:s;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function yx(e,s,r){const n=[];for(const[a,i]of Object.entries(e.settings)){const c=i;if(c.length===0)continue;const l=s.find(u=>u.type===a);n.push({type:a,displayName:(l==null?void 0:l.displayName)||a,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[a]||{}})}return n}function Pn(e){if(!e||typeof e!="object")return!1;const s=e;return(s.sourceMode==="normal"||s.sourceMode==="no-upstream")&&typeof s.disableUpstream=="boolean"&&(s.explicitProviderDir===null||typeof s.explicitProviderDir=="string")&&typeof s.userDir=="string"&&typeof s.upstreamDir=="string"&&Array.isArray(s.providerRoots)}function Zo(e){if(!e||typeof e!="object")return null;if(Pn(e))return e;const s=e,r=s.result;return Pn(r)?r:Pn(s.sourceConfig)?s.sourceConfig:null}function vx(e){const s=e.trim();return s||null}const ei=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],wx=[{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 jx({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[u,f]=o.useState([]),[d,h]=o.useState(""),[m,k]=o.useState([]),[S,p]=o.useState(""),x=o.useRef(null),v=o.useRef(null),g=w=>{f(b=>b.includes(w)?b.filter(E=>E!==w):[...b,w])},N=()=>f([...ei]),M=()=>f([]);o.useEffect(()=>{var w;(w=x.current)==null||w.scrollIntoView({behavior:"smooth"})},[m]),o.useEffect(()=>()=>{v.current&&clearInterval(v.current)},[]);const y=o.useCallback(()=>{v.current&&clearInterval(v.current),v.current=setInterval(async()=>{try{const w=await r(e,"provider_auto_fix_status",{providerType:s.type});(w==null?void 0:w.running)===!1&&a==="running"&&(i("done"),k(b=>[...b,`
|
|
61
|
+
✅ Auto-fix completed!`]),v.current&&clearInterval(v.current))}catch{}},3e3)},[e,s.type,r,a]),C=async()=>{if(u.length!==0){i("running"),k(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,d?`💬 Comment: ${d}`:"",""]),p("");try{const w=await r(e,"provider_auto_fix",{providerType:s.type,functions:u,agent:c,...d?{comment:d}:{}});w!=null&&w.success&&(w!=null&&w.started||w!=null&&w.running)?(k(b=>[...b,"✅ Agent started. Monitoring progress..."]),y()):(i("error"),p((w==null?void 0:w.error)||"Failed to start auto-fix"))}catch(w){i("error"),p((w==null?void 0:w.message)||"Connection failed")}}},j=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),k(w=>[...w,`
|
|
62
|
+
⚠️ Auto-fix cancelled.`]),i("done"),v.current&&clearInterval(v.current)}catch{}};return t.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:t.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:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),t.jsxs("div",{children:[t.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),t.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),t.jsx("div",{className:"flex gap-2",children:wx.map(w=>t.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:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===w.value?w.color:"var(--text-primary)"},children:w.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:w.desc})]},w.value))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:N,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),t.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),t.jsx("button",{onClick:M,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:ei.map(w=>t.jsxs("button",{onClick:()=>g(w),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(w)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(w)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(w)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(w)?"☑ ":"☐ ",w]},w))})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",t.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),t.jsx("textarea",{value:d,onChange:w=>h(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")&&t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[m.map((w,b)=>t.jsx("div",{className:w.startsWith("✅")?"text-green-400":"",style:w.startsWith("❌")||w.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:w},b)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:x})]}),S&&t.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:S})]})]}),t.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[t.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&u.length>0&&`${u.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),t.jsxs("div",{className:"flex gap-2",children:[a==="config"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:C,disabled:u.length===0,className:"machine-btn",style:{background:u.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:u.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:u.length>0?"#a78bfa":void 0,opacity:u.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&t.jsx("button",{onClick:j,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{i("config"),k([]),p("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function kx({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var y;const i=s.filter(C=>C.category==="ide"),[c,l]=o.useState(((y=i[0])==null?void 0:y.type)||""),[u,f]=o.useState(""),[d,h]=o.useState(""),[m,k]=o.useState(!1),[S,p]=o.useState(""),[x,v]=o.useState(!1),g=C=>{const j=C.toLowerCase().replace(/[^a-z0-9-]/g,"");f(j),(!d||d===N(u))&&h(N(j))},N=C=>C.split("-").map(j=>j.charAt(0).toUpperCase()+j.slice(1)).join(" "),M=async()=>{if(!(!u||!d||!c)){k(!0),p("");try{const C=await r(e,"provider_clone",{type:u,name:d,category:"ide",location:"user",cloneFrom:c});C!=null&&C.success||C!=null&&C.created?(v(!0),a==null||a(u)):p((C==null?void 0:C.error)||"Failed to create provider")}catch(C){p((C==null?void 0:C.message)||"Connection failed")}k(!1)}};return t.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:t.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:C=>C.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[t.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:x?t.jsxs("div",{className:"text-center py-6",children:[t.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),t.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[t.jsx("code",{className:"text-violet-400",children:u})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",u,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",u]})," or use Auto-Fix to implement scripts."]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(C=>t.jsxs("button",{onClick:()=>l(C.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===C.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===C.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:C.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===C.type?"#a78bfa":"var(--text-secondary)"},children:C.displayName})]},C.type))})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),t.jsx("input",{value:u,onChange:C=>g(C.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"}),t.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",t.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",u||"...","/"]})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),t.jsx("input",{value:d,onChange:C=>h(C.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),S&&t.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:S})]})}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:x?t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:M,disabled:!u||!d||m,className:"machine-btn",style:{background:u&&d?"rgba(34,197,94,0.12)":void 0,borderColor:u&&d?"rgba(34,197,94,0.3)":void 0,color:u&&d?"#86efac":void 0,opacity:!u||!d||m?.4:1},children:m?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Sx({machineId:e,providers:s,sendDaemonCommand:r}){var A;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[f,d]=o.useState("all"),[h,m]=o.useState(null),[k,S]=o.useState(!1),[p,x]=o.useState(null),[v,g]=o.useState("normal"),[N,M]=o.useState(""),[y,C]=o.useState(!1),j=o.useCallback(async()=>{if(e)try{const I=await r(e,"get_provider_source_config",{}),P=Zo(I);P&&(x(P),g(P.sourceMode),M(P.explicitProviderDir||""))}catch{}},[e,r]),w=o.useCallback(async()=>{if(e){c(!0);try{const I=await r(e,"get_provider_settings",{}),P=gx(I);if(P){const O=yx(P,s);O.sort((V,L)=>V.category.localeCompare(L.category)||V.displayName.localeCompare(L.displayName)),a(O)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&w(),p||j()},[]);const b=async(I,P,O)=>{u(`${I}.${P}`),a(V=>V.map(L=>L.type===I?{...L,values:{...L.values,[P]:O}}:L));try{const V=await r(e,"set_provider_setting",{providerType:I,key:P,value:O});V!=null&&V.success||w()}catch{w()}u(null)},E=async()=>{C(!0);try{const I=await r(e,"set_provider_source_config",{providerSourceMode:v,providerDir:vx(N)}),P=Zo(I);P?(x(P),g(P.sourceMode),M(P.explicitProviderDir||"")):await j(),await w()}catch{await j()}C(!1)};return t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(I=>t.jsx("button",{onClick:()=>d(I),className:`machine-btn text-[10px] px-2 py-0.5 ${f===I?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:I.toUpperCase()},I))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>S(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),t.jsx("button",{onClick:w,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Existing running sessions may need restart."})]}),t.jsx("button",{onClick:j,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),t.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),t.jsxs("select",{value:v,onChange:I=>g(I.target.value),className:"machine-input text-[11px]",children:[t.jsx("option",{value:"normal",children:"normal"}),t.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),t.jsx("input",{type:"text",value:N,onChange:I=>M(I.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void E(),disabled:y,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:y?"Applying…":"Apply + Reload"})]}),t.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((A=p==null?void 0:p.providerRoots)==null?void 0:A.join(" → "))||"loading…"]})]})]}),f!=="all"&&n.filter(I=>I.category===f).length>1&&(()=>{const I=n.filter(L=>L.category===f),P=new Map;for(const L of I)for(const R of L.schema){if(R.type!=="boolean")continue;const G=P.get(R.key),B=!!(L.values[R.key]??R.default);G?(G.onCount+=B?1:0,G.total+=1):P.set(R.key,{label:R.label||R.key,onCount:B?1:0,total:1})}const O=[...P.entries()].filter(([,L])=>L.total===I.length);if(O.length===0)return null;const V=async(L,R)=>{for(const G of I)await b(G.type,L,R)};return t.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[t.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",f.toUpperCase()," providers (",I.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:O.map(([L,R])=>{const G=R.onCount===R.total,B=R.onCount===0;return t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:"text-text-secondary font-medium",children:R.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",R.onCount,"/",R.total,")"]}),t.jsx("button",{onClick:()=>void V(L,!0),disabled:G,className:`machine-btn text-[9px] px-1.5 py-px ${G?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void V(L,!1),disabled:B,className:`machine-btn text-[9px] px-1.5 py-px ${B?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},L)})})]})})(),i&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(I=>f==="all"||I.category===f).map(I=>t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[t.jsx("span",{className:"text-lg",children:I.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:I.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:I.category==="acp"?"rgba(139,92,246,0.08)":I.category==="cli"?"rgba(59,130,246,0.08)":I.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:I.category==="acp"?"#a78bfa":I.category==="cli"?"#60a5fa":I.category==="ide"?"#86efac":"var(--status-warning)"},children:I.category}),I.category==="ide"&&t.jsx("button",{onClick:()=>m(s.find(P=>P.type===I.type)||{type:I.type,name:I.displayName,displayName:I.displayName,icon:I.icon,category:I.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"})]}),t.jsx("div",{className:"flex flex-col gap-2",children:I.schema.map(P=>t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[P.label||P.key,l===`${I.type}.${P.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),P.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:P.description})]}),t.jsx("div",{className:"shrink-0",children:P.type==="boolean"?t.jsx("button",{onClick:()=>b(I.type,P.key,!(I.values[P.key]??P.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:I.values[P.key]??P.default?"#8b5cf6":"var(--border-subtle)"},children:t.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:I.values[P.key]??P.default?21:3}})}):P.type==="number"?t.jsx("input",{type:"number",value:Number(I.values[P.key]??P.default??0)||0,min:P.min,max:P.max,onChange:O=>{const V=parseInt(O.target.value)||0;P.min!==void 0&&V<P.min||P.max!==void 0&&V>P.max||b(I.type,P.key,V)},className:"machine-input w-20 text-center text-[11px]"}):P.type==="select"&&P.options?t.jsx("select",{value:String(I.values[P.key]??P.default??""),onChange:O=>b(I.type,P.key,O.target.value),className:"machine-input text-[11px]",children:P.options.map(O=>t.jsx("option",{value:O,children:O},O))}):t.jsx("input",{type:"text",value:String(I.values[P.key]??P.default??""),onBlur:O=>b(I.type,P.key,O.target.value),className:"machine-input w-[120px] text-[11px]"})})]},P.key))})]},I.type))}),h&&t.jsx(jx,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>m(null)}),k&&t.jsx(kx,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>S(!1),onCreated:()=>{S(!1),w()}})]})}const Nx=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Cx({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function Ix(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function Mx(e){return e.trim().toLowerCase()}function cn(e,s){const r=Mx(s);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Va(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Qs(e,s=220){const r=Va(e);return r?r.length>s?`${r.slice(0,s)}…`:r:""}function Ax(e){const s=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(s))return{kind:s.length>0?"structured":"empty",entries:s.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 s=="string"){const r=s.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function cl(e,s){return e.filter(r=>cn([r.level,r.message],s))}function Tx(e,s){return e.split(`
|
|
63
|
+
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>cn([r],s))}function ll(e,s){return e.filter(r=>cn([r.level,r.category,r.stage,r.interactionId,Va(r.payload)],s))}function dl(e,s){return e.filter(r=>cn([r.kind,r.topic,r.interactionId,Va(r.payload)],s))}function ti(e){return e==="warn"||e==="error"}function Lx({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){return{all:e.length+s.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=>ti(a.level)).length+r.filter(a=>ti(a.level)).length}}function Rx({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(i=>`${new Date(i.timestamp).toISOString()} ${i.level.toUpperCase()} ${i.message}`)].join(`
|
|
64
|
+
`)):s.length>0&&a.push(["[daemon logs]",...s].join(`
|
|
65
|
+
`)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${Qs(i.payload,500)}`.trim())].join(`
|
|
66
|
+
`)),n.length>0&&a.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${Qs(i.payload,500)}`.trim())].join(`
|
|
67
|
+
`)),a.join(`
|
|
68
|
+
|
|
69
|
+
`)}function Px({daemonLogs:e,trace:s,webEvents:r,daemonLogKind:n,daemonFetchError:a,traceFetchError:i,searchQuery:c}){const l=cl(e,c),u=ll(s,c),f=dl(r,c),d=l.filter(k=>k.level==="warn"||k.level==="error").map(k=>({source:"daemon",level:k.level,timestamp:k.timestamp,label:"daemon",detail:k.message})),h=u.filter(k=>k.level==="warn"||k.level==="error").map(k=>({source:"trace",level:k.level,timestamp:k.ts,label:`${k.category}.${k.stage}`,detail:Qs(k.payload,320)||`${k.category}.${k.stage}`})),m=[...d,...h].sort((k,S)=>S.timestamp-k.timestamp);return{daemonCount:l.length,traceCount:u.length,webCount:f.length,issueCount:m.length,latestIssue:m[0]||null,hasAnyData:n==="text"||l.length>0||u.length>0||f.length>0,hasBlockingError:!!(a||i)}}function si(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function ri(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 _n(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 _x({machineId:e,sendDaemonCommand:s}){var he,Se;const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[u,f]=o.useState([]),[d,h]=o.useState([]),[m,k]=o.useState(0),[S,p]=o.useState(0),[x,v]=o.useState(null),[g,N]=o.useState(!0),[M,y]=o.useState("info"),[C,j]=o.useState("info"),[w,b]=o.useState("all"),[E,A]=o.useState(""),[I,P]=o.useState(!0),[O,V]=o.useState(!0),[L,R]=o.useState(""),[G,B]=o.useState(""),[$,H]=o.useState(0),[J,xe]=o.useState({daemon:!0,trace:!1,web:!1}),me=o.useRef(null),ce=o.useRef(!1),ge=o.useMemo(()=>Ix(u,w),[u,w]),be=o.useMemo(()=>cl(r,E),[r,E]),we=o.useMemo(()=>Tx(c,E),[c,E]),z=o.useMemo(()=>ll(ge,E),[ge,E]),U=o.useMemo(()=>dl(d,E),[d,E]),Q=o.useMemo(()=>C==="issues"?be.filter(T=>T.level==="warn"||T.level==="error"):C==="info"?be.filter(T=>T.level!=="debug"):be,[be,C]),de=o.useMemo(()=>C==="all"?we:[],[we,C]),re=o.useMemo(()=>C==="issues"?z.filter(T=>T.level==="warn"||T.level==="error"):C==="info"?z.filter(T=>T.level!=="debug"):z,[z,C]),le=o.useMemo(()=>C==="issues"?[]:U,[U,C]),te=o.useMemo(()=>Lx({daemonLogs:be,daemonRawLines:we,trace:z,webEvents:U}),[be,we,z,U]),fe=o.useMemo(()=>Px({daemonLogs:r,trace:ge,webEvents:d,daemonLogKind:a,daemonFetchError:L,traceFetchError:G,searchQuery:E}),[L,a,r,ge,E,G,d]),ne=o.useCallback(async()=>{if(!e)return;const[T,D]=await Promise.allSettled([s(e,"get_logs",{count:200,minLevel:M,since:m}),s(e,"get_debug_trace",Cx({count:120,since:S,category:w}))]);if(T.status==="fulfilled"){const Y=T.value,X=(Y==null?void 0:Y.result)||Y,pe=Ax(X);if(P(!1),R((Y==null?void 0:Y.success)===!1?String((Y==null?void 0:Y.error)||"Could not load daemon logs"):""),i(pe.kind),l(pe.rawText),pe.entries.length>0){n(Ne=>(m>0?[...Ne,...pe.entries]:pe.entries).slice(-300));const Ie=pe.entries.reduce((Ne,Be)=>Math.max(Ne,Number(Be.timestamp||0)),m);Ie>m&&k(Ie)}else pe.kind!=="structured"&&m===0&&n([])}else P(!1),R(T.reason instanceof Error?T.reason.message:"Could not load daemon logs");if(D.status==="fulfilled"){const Y=D.value,X=(Y==null?void 0:Y.result)||Y;if((Y==null?void 0:Y.success)===!1)B(String((Y==null?void 0:Y.error)||"Could not load daemon trace"));else if(Array.isArray(X==null?void 0:X.trace)){B(""),f(X.trace.slice(-120));const pe=X.trace.reduce((Ie,Ne)=>Math.max(Ie,Number(Ne.ts||0)),S);pe>S&&p(pe)}else B(""),f([]);V(!1)}else V(!1),B(D.reason instanceof Error?D.reason.message:"Could not load daemon trace");h(ks.list({limit:120})),v(Date.now())},[m,S,M,e,s,w]);o.useEffect(()=>{if(!e||(ne(),!g))return;const T=setInterval(()=>{ne()},3e3);return()=>clearInterval(T)},[g,ne,e,$]),o.useEffect(()=>{if(g&&(Q.length>0||de.length>0||re.length>0||le.length>0)){const T=ce.current?"smooth":"instant";setTimeout(()=>{var D;(D=me.current)==null||D.scrollIntoView({behavior:T}),ce.current=!0},50)}},[Q.length,de.length,re.length,le.length,g]),o.useEffect(()=>{f([]),p(0),V(!0)},[w]);const ie=((he=fe.latestIssue)==null?void 0:he.level)==="error"?"danger":((Se=fe.latestIssue)==null?void 0:Se.level)==="warn"?"warning":"good",ae=L||G?"danger":g?"good":"neutral",ye=o.useCallback(async()=>{var D;const T=Rx({daemonLogs:Q,daemonRawLines:de,trace:re,webEvents:le});if(!T.trim()){dt.showToast("복사할 visible logs가 없습니다.","info");return}try{await((D=navigator.clipboard)==null?void 0:D.writeText(T)),dt.showToast("Visible logs를 클립보드에 복사했습니다.","success")}catch(Y){dt.showToast(Y instanceof Error?Y.message:"Could not copy visible logs","warning")}},[Q,de,re,le]);return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"Level"}),["debug","info","warn","error"].map(T=>t.jsx("button",{onClick:()=>{y(T),n([]),l(""),i("empty"),k(0),P(!0)},className:`machine-btn text-[10px] px-2 py-0.5 ${M===T?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:T.toUpperCase()},T)),t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider ml-3 mr-1",children:"Trace"}),Nx.map(T=>t.jsx("button",{onClick:()=>b(T.value),className:`machine-btn text-[10px] px-2 py-0.5 ${w===T.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:T.label},T.value))]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${te.info})`},{id:"issues",label:`Issues (${te.issues})`},{id:"all",label:`All (${te.all})`}].map(T=>t.jsx("button",{type:"button",onClick:()=>j(T.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${C===T.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:T.label},T.id))}),t.jsx("input",{value:E,onChange:T=>A(T.target.value),placeholder:"Search visible logs, trace, events…",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"}),t.jsx("button",{onClick:()=>{ye()},className:"machine-btn",children:"Copy visible"}),t.jsx("button",{onClick:()=>N(T=>!T),className:`machine-btn ${g?"text-green-500 border-green-500/30":""}`,children:g?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>H(T=>T+1),className:"machine-btn",children:"↻ Refresh"}),t.jsx("button",{onClick:()=>{n([]),l(""),i("empty"),f([]),h([]),k(0),p(0),v(null),R(""),B(""),P(!0),V(!0),ks.clear()},className:"machine-btn",children:"Clear"})]})]}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[t.jsxs("div",{className:`rounded-xl border p-3 ${_n(fe.issueCount>0?"warning":"good")}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Visible signals"}),t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:["daemon ",Q.length+de.length," · trace ",re.length," · web ",le.length]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:E.trim()?`Filtered by “${E.trim()}”`:"Showing the latest buffered entries"})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${_n(ie)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Attention needed"}),fe.latestIssue?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[fe.latestIssue.source," · ",fe.latestIssue.label]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:fe.latestIssue.detail}),t.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:[fe.issueCount," warn/error signal(s) · ",si(fe.latestIssue.timestamp)]})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No recent warn/error signal"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use search or lower the log level if you need more context."})]})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${_n(ae)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Fetch status"}),t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:L||G?"Needs attention":g?"Live polling every 3s":"Paused"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",si(x)]}),(L||G)&&t.jsxs("div",{className:"text-[11px] text-red-300 mt-2 space-y-1",children:[L&&t.jsxs("div",{children:["Daemon logs: ",L]}),G&&t.jsxs("div",{children:["Daemon trace: ",G]})]})]})]}),t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>xe(T=>({...T,daemon:!T.daemon})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:a==="text"?`${de.length} visible raw line(s) from file fallback`:`${Q.length} visible structured line(s)`})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:J.daemon?"Hide":"Show"})]}),J.daemon&&t.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:[I&&!fe.hasAnyData&&!L&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!I&&L&&a==="empty"&&t.jsx("div",{className:"p-6 text-center text-red-300",children:L}),!I&&a==="empty"&&!L&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),a==="text"&&de.length===0&&c&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:C==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),a==="structured"&&Q.length===0&&r.length>0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),a==="text"&&de.map((T,D)=>t.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:T},`raw-${D}`)),a!=="text"&&Q.map((T,D)=>t.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${ri(T.level)}`,children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(T.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:T.level==="error"?"ERR":T.level==="warn"?"WRN":T.level==="debug"?"DBG":"INF"}),t.jsx("span",{className:"break-words",children:T.message})]},`log-${D}`))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>xe(T=>({...T,trace:!T.trace})),children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",w==="session_host"?" · session_host only":""]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[re.length," visible trace event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:J.trace?"Hide":"Show"})]}),J.trace&&t.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:[O&&re.length===0&&!G&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!O&&G&&re.length===0&&t.jsx("div",{className:"p-6 text-center text-red-300",children:G}),!O&&re.length===0&&!G&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:E.trim()?"No trace entries match the current search.":w==="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."}),re.map(T=>t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${ri(T.level)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(T.ts).toLocaleTimeString()}),t.jsx("span",{children:T.level.toUpperCase()}),t.jsxs("span",{children:[T.category,".",T.stage]}),T.interactionId&&t.jsxs("span",{children:["ix=",T.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Qs(T.payload,360)||"No payload"})]},T.id))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>xe(T=>({...T,web:!T.web})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[le.length," visible browser event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:J.web?"Hide":"Show"})]}),J.web&&t.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:[le.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:E.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),le.map(T=>t.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(T.ts).toLocaleTimeString()}),t.jsx("span",{children:T.kind}),T.topic&&t.jsxs("span",{children:["topic=",T.topic]}),T.interactionId&&t.jsxs("span",{children:["ix=",T.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Qs(T.payload,360)||"No payload"})]},T.id))]})]})]}),t.jsx("div",{ref:me})]})}function Dx(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 s=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return s?s==="auto_resumed"?"restored after restart":s==="resume_failed"?"restore failed":s==="host_restart_interrupted"?"host restart interrupted":s==="orphan_snapshot"?"snapshot recovered":s.replace(/_/g," "):null}function Ex(e){var a;const s=[],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),u=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?s.push(i):(c==="stopped"||c==="failed")&&(u||l)?r.push(i):n.push(i)}return{liveRuntimes:s,recoverySnapshots:r,inactiveRecords:n}}function $x(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Dn(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 En(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function $n(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function ni(e){if(!e)return"unknown";const s=Date.now()-e,r=Math.max(0,Math.round(s/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 Bx(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Kx(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 Ox(e){var r;const s=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}`;s.set(i,(s.get(i)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function Wx({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),f=Qf(e,{enabled:!!e,includeSessions:!0,limit:jo,intervalMs:pm}),d=f.diagnostics,h=f.loading,m=f.applyDiagnostics,k=o.useMemo(()=>Dx({diagnostics:d,loading:h,refreshing:l,error:n}),[d,h,l,n]),S=o.useMemo(()=>new Map(s.map(A=>[A.sessionId||A.id,A])),[s]),p=o.useCallback(async()=>{if(e){u(!0);try{const A=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:jo}),I=En(A);if(!(I!=null&&I.success))throw new Error((I==null?void 0:I.error)||"Could not load hosted runtime diagnostics");m(I.diagnostics||I.result||null),a("")}catch(A){const I=A instanceof Error?A.message:"Could not load hosted runtime diagnostics";a(I)}finally{u(!1)}}},[m,e,r]);o.useEffect(()=>{!e||d||h||l||p()},[d,h,e,p,l]);const x=o.useCallback(async(A,I)=>{const P=`${A}:${I.sessionId}`;if(!(A==="session_host_stop_session"&&!window.confirm(`Stop ${I.displayName}?
|
|
70
|
+
This will terminate the hosted runtime.`))){c(P);try{const O=await r(e,A,{sessionId:I.sessionId}),V=En(O);if(!(V!=null&&V.success))throw new Error((V==null?void 0:V.error)||"Session host action failed");const L=A==="session_host_resume_session"?"resumed":A==="session_host_restart_session"?"restarted":"stopped";dt.showToast(`Session host ${L}: ${I.displayName}`,"success"),await p()}catch(O){const V=O instanceof Error?O.message:"Session host action failed";dt.showToast(V,"warning"),a(V)}finally{c(O=>O===P?null:O)}}},[e,p,r]),v=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
71
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const I=await r(e,"session_host_prune_duplicate_sessions",{}),P=En(I);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const O=P.result||{},V=Array.isArray(O.prunedSessionIds)?O.prunedSessionIds.length:0,L=typeof O.duplicateGroupCount=="number"?O.duplicateGroupCount:0;dt.showToast(`Pruned ${V} duplicate runtime(s) across ${L} group(s)`,"success"),await p()}catch(I){const P=I instanceof Error?I.message:"Duplicate prune failed";dt.showToast(P,"warning"),a(P)}finally{c(I=>I==="session_host_prune_duplicate_sessions"?null:I)}}},[e,p,r]),g=o.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((A,I)=>(I.lastActivityAt||0)-(A.lastActivityAt||0)),[d==null?void 0:d.sessions]),N=o.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:Ex(g),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,g]),M=N.liveRuntimes,y=N.recoverySnapshots,C=N.inactiveRecords,j=o.useMemo(()=>Ox(M),[M]),w=o.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),b=o.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(A=>A.level==="warn"||A.level==="error")||null,[d==null?void 0:d.recentLogs]),E=(A,I)=>{var H;const P=i===`session_host_resume_session:${A.sessionId}`,O=i===`session_host_restart_session:${A.sessionId}`,V=i===`session_host_stop_session:${A.sessionId}`,L=ul(A.meta),R=S.get(A.sessionId),G=A.attachedClients.length===1?"1 client":`${A.attachedClients.length} clients`,B=I==="recovery"?"Recover":"Resume",$=$x(I);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:A.displayName||(R==null?void 0:R.cliName)||A.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Kx(A.lifecycle)}`,children:A.lifecycle}),L&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:L})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:A.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||A.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:A.runtimeKey}),A.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",A.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((H=A.writeOwner)==null?void 0:H.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Bx(A.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(wi,{size:11})," ",G]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",ni(A.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",$]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[I==="recovery"&&(A.lifecycle==="interrupted"||A.lifecycle==="failed"||A.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_resume_session",A)},children:P?`${B}ing…`:B}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_restart_session",A)},children:O?"Restarting…":"Restart"}),I==="live"&&(A.lifecycle==="running"||A.lifecycle==="starting"||A.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{x("session_host_stop_session",A)},children:V?"Stopping…":"Stop"})]})]})},A.sessionId)};return t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[t.jsx(ls,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:rf()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{v()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${k.toneClass}`,children:k.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||l,children:[t.jsx(er,{size:13}),h||l?"Refreshing…":"Refresh"]})]})]}),n&&!d&&t.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:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(qs,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),d&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:y.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.recentRequests.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),t.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:ni(d.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:$n(d.hostStartedAt)})]})]}),b&&t.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:[t.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[t.jsx(qs,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:b.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[$n(b.timestamp),b.sessionId?` · ${b.sessionId}`:""]})]}),t.jsxs("div",{className:"mb-4 space-y-4",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(ba,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Dn("live")}),M.length===0?t.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."}):t.jsx("div",{className:"space-y-2",children:M.map(A=>E(A,"live"))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(ls,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Dn("recovery")}),y.length===0?t.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."}):t.jsx("div",{className:"space-y-2",children:y.map(A=>E(A,"recovery"))})]}),C.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Dn("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:C.map(A=>E(A,"inactive"))})]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),w.length===0?t.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."}):t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:w.map(A=>{var P;const I=g.find(O=>O.sessionId===A.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(I==null?void 0:I.displayName)||((P=S.get(A.sessionId))==null?void 0:P.cliName)||A.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[A.action,A.lifecycle?` · ${A.lifecycle}`:"",A.detail?` · ${A.detail}`:"",A.error?` · ${A.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${A.success===!1?"text-red-300":"text-text-secondary"}`,children:$n(A.timestamp)})]},`${A.sessionId}:${A.timestamp}:${A.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Hx({machine:e,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return t.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:t.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:[t.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),t.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."}),t.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?t.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=>t.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:s.cliType,workspaceId:i.id,argsStr:s.argsStr,model:s.model})},children:[t.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:s.cliType,useHome:!0,argsStr:s.argsStr,model:s.model})},children:"Home directory"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function Bn({icon:e,children:s}){return t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,t.jsx("span",{children:s})]})}function Kn({children:e,className:s=""}){return t.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${s}`,children:e})}function Fx({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),d=Hs(e,"0.9.13");return t.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&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Bn,{icon:t.jsx(Ft,{size:13}),children:"Current Chats"}),t.jsx(Kn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const m=Zn(h);return t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(h),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:rt(h)}),m>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Jr(m)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:us(h)})]},h.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Bn,{icon:t.jsx(Ci,{size:13}),children:"Recent Launches"}),t.jsx(Kn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:m,updatedLabel:k}=zc(h);return t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(h),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:h.label}),k&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:m})]},h.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Bn,{icon:t.jsx(qs,{size:13}),children:"Daemon Update"}),t.jsx(Kn,{className:"border-amber-500/20 bg-amber-500/5",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:d?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:d?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),t.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:[t.jsx(er,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Ux(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const zx={ide:{label:"IDE",plural:"IDEs",accent:"border-blue-500/[0.12]"},cli:{label:"CLI",plural:"CLIs",accent:"border-violet-500/[0.12]"},acp:{label:"ACP Agent",plural:"ACP agents",accent:"border-emerald-500/[0.12]"}};function Ir(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function On({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:f}){const d=Ms(),{handleLaunchIde:h,handleStopCli:m,handleRestartIde:k,handleStopIde:S,handleDetectIdes:p,launchingIde:x,launchingAgentType:v,addLog:g}=c,[N,M]=o.useState(null),y=o.useCallback(_=>{_&&d(Gt(_))},[d]),C=zx[e],j=e==="ide",w=e==="acp",b=o.useMemo(()=>n.filter(_=>_.category===e&&(e==="ide"||_.installed!==!1)),[e,n]),E=o.useMemo(()=>new Map(b.map(_=>[_.type,_.displayName||_.type])),[b]),[A,I]=o.useState(""),[P,O]=o.useState(""),[V,L]=o.useState([]),[R,G]=o.useState(""),[B,$]=o.useState(""),[H,J]=o.useState([]),[xe,me]=o.useState(!1),[ce,ge]=o.useState(!1),[be,we]=o.useState(""),[z,U]=o.useState(!1),[Q,de]=o.useState(()=>ht()),[re,le]=o.useState(null),[te,fe]=o.useState(f?"__custom__":u||s.defaultWorkspaceId||""),[ne,ie]=o.useState(f||""),[ae,ye]=o.useState([]),[he,Se]=o.useState(!1),[T,D]=o.useState(""),[Y,X]=o.useState([]),[pe,Ie]=o.useState(!1),[Ne,Be]=o.useState(""),He=o.useRef(null),[Ue,Qe]=o.useState(null),tt=o.useRef("__home__"),[ct,ut]=o.useState("__home__"),[mt,Xe]=o.useState(!1),at=o.useRef(0),ve=ae.filter(_=>!a.some(ee=>ee.type===_&&bt(ee.status)!=="stopped")),Ee=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!te&&fe(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(f){fe("__custom__"),ie(f);return}u&&(fe(u),ie(""))},[u,f]),o.useEffect(()=>{j||A&&(b.some(_=>_.type===A)||(I(""),$("")))},[b,j,A]);const Ke=(()=>{if(te==="__custom__")return ne.trim();if(!te)return"";const _=(s.workspaces||[]).find(ee=>ee.id===te);return(_==null?void 0:_.path)||""})(),ot=o.useCallback(_=>{const ee=Ee.current[_];ee&&(clearTimeout(ee),delete Ee.current[_]),ye(ue=>ue.includes(_)?ue.filter(Pe=>Pe!==_):ue)},[]),nt=o.useRef(new Set),yt=o.useCallback(async _=>{if(l){Ie(!0),Be("");try{const ee=await rn(l,r,_);D(ee.path),ie(ee.path),X(ee.directories)}catch(ee){Be(ee instanceof Error?ee.message:"Could not load folder")}finally{Ie(!1)}}},[r,l]),Z=o.useCallback(()=>{if(!l)return;fe("__custom__"),Se(!0);const _=a.map(ue=>ue.workspace),ee=sn(s.platform,tn(ne.trim(),Ke,f,_,s.defaultWorkspacePath,(s.workspaces||[]).map(ue=>ue.path)));yt(ee)},[ne,f,yt,s.defaultWorkspacePath,s.platform,s.workspaces,a,Ke,l]),Re=o.useCallback(_=>{const ee=String(_.workspace||"").trim();if(!ee)return;const ue=(s.workspaces||[]).find(Pe=>Ir(Pe.path)===Ir(ee));if(ue){fe(ue.id),ie("");return}fe("__custom__"),ie(ee)},[s.workspaces]),De=o.useCallback(_=>{const ee=String(_.workspace||"").trim();if(!ee)return{workspaceId:null,workspacePath:"",useHome:!0};const ue=(s.workspaces||[]).find(Pe=>Ir(Pe.path)===Ir(ee));return ue?{workspaceId:ue.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ee,useHome:!1}},[s.workspaces]),st=o.useCallback(async _=>{if(!l||!_||e!=="cli"){J([]),me(!1),ge(!1),we("");return}const ee=at.current+1;at.current=ee,me(!0),we("");try{const ue=await l(r,"list_saved_sessions",{providerType:_,kind:"cli",limit:30});if(at.current!==ee)return;const Pe=(ue==null?void 0:ue.result)??ue;J(Array.isArray(Pe==null?void 0:Pe.sessions)?Pe.sessions:[])}catch(ue){if(at.current!==ee)return;J([]),we(ue instanceof Error?ue.message:"Could not load saved sessions")}finally{at.current===ee&&(me(!1),ge(!0))}},[e,r,l]),Tt=o.useMemo(()=>{if(e!=="cli"||!A)return null;const _=E.get(A)||A;return{routeId:r,daemonId:r,providerSessionId:B||void 0,transport:"pty",mode:"chat",agentName:_,agentType:A,status:"idle",title:_,messages:[],ideType:A,workspaceName:Ke,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${A}`}},[e,r,E,Ke,B,A]),ft=o.useCallback(_=>{if(e==="ide"||!_){L([]);return}L(nl(r,_))},[e,r]);o.useEffect(()=>{at.current+=1,$(""),ft(A),ge(!1),J([]),we(""),me(!1)},[e,ft,st,A]);const Fe=o.useMemo(()=>H.find(_=>_.providerSessionId===B)||null,[H,B]);o.useEffect(()=>{if(!B)return;const _=H.find(ee=>ee.providerSessionId===B);_!=null&&_.canResume||$("")},[H,B]);const vt=o.useCallback((_,ee)=>{He.current=ee,tt.current=_.selectedWorkspaceKey||"__home__",ut(_.selectedWorkspaceKey||"__home__"),Qe(_)},[]),K=o.useCallback(()=>{He.current&&(Xe(!0),He.current().finally(()=>{He.current=null,Xe(!1),Qe(null)}))},[]),W=o.useCallback(_=>{if(!_)return;ye(ue=>ue.includes(_)?ue:[...ue,_]);const ee=Ee.current[_];ee&&clearTimeout(ee),Ee.current[_]=setTimeout(()=>{ye(ue=>ue.includes(_)?ue.filter(Pe=>Pe!==_):ue),delete Ee.current[_]},2e4)},[]);o.useEffect(()=>{for(const ee of a)bt(ee.status)!=="stopped"&&(ae.includes(ee.type)&&!nt.current.has(ee.type)&&(nt.current.add(ee.type),g("info",`${E.get(ee.type)||ee.type} launched`,!0)),ot(ee.type));const _=new Set(a.filter(ee=>bt(ee.status)!=="stopped").map(ee=>ee.type));nt.current.forEach(ee=>{!ae.includes(ee)&&!_.has(ee)&&nt.current.delete(ee)})},[g,ot,a,ae,E]),o.useEffect(()=>()=>{Object.values(Ee.current).forEach(clearTimeout),Ee.current={}},[]);const[F,q]=o.useState({}),[oe,ke]=o.useState(null);o.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const ee=await l(r,"get_ide_extensions",{}),ue=(ee==null?void 0:ee.result)||ee;ue!=null&&ue.success&&(ue!=null&&ue.ideExtensions)&&q(ue.ideExtensions)}catch{}})()},[j,r,l]);const Ae=_=>j?et(_.type):e==="cli"?_.cliName:_.acpName,Me=j?s.detectedIdes||[]:[],se=o.useCallback(async _=>{const ee=(_==null?void 0:_.type)||A,ue=(_==null?void 0:_.workspacePath)??Ke;if(j){await h(ee,ue?{workspace:ue}:void 0)&&W(ee);return}const Pe=await c.runLaunchCliCore({cliType:ee,dir:_!=null&&_.workspaceId?void 0:ue||void 0,workspaceId:(_==null?void 0:_.workspaceId)||void 0,useHome:(_==null?void 0:_.useHome)||!(_!=null&&_.workspaceId)&&!ue,argsStr:(_==null?void 0:_.argsStr)??(P||void 0),model:(_==null?void 0:_.model)??(w&&R||void 0),resumeSessionId:(_==null?void 0:_.resumeSessionId)||!w&&e==="cli"&&ee===A&&B||void 0});if(Pe.success||Pe.pending){const Ce=(_==null?void 0:_.argsStr)??P;!j&&(Ce!=null&&Ce.trim())&&(al(r,ee,Ce),ft(ee)),W(ee),Pe.success&&Pe.sessionId&&y(Pe.sessionId)}},[c,h,w,j,P,R,ft,W,r,y,Ke,B,A]),je=mc(j?"ide":w?"acp":"cli",!j&&!w&&!!B),Oe=fc(j?"ide":w?"acp":"cli",!j&&!w&&!!B),ze=()=>{var Ce;const _=j?et(A):E.get(A)||A,ee=!j&&!w&&!!B,{options:ue,selectedKey:Pe}=os({machine:s,currentWorkspaceId:te&&te!=="__custom__"?te:null,currentWorkspacePath:Ke});vt({title:ee?Ra(_):ss("start-fresh",_),description:ee?Pa():rs("start-fresh"),confirmLabel:je,busyLabel:Oe,workspaceOptions:ue,selectedWorkspaceKey:Pe,details:[{label:"Mode",value:C.label},{label:"Provider",value:_},...!j&&e==="cli"&&B?[{label:"Resume",value:((Ce=H.find(Te=>Te.providerSessionId===B))==null?void 0:Ce.title)||B}]:[],...!j&&P.trim()?[{label:"Arguments",value:P.trim()}]:[],...w&&R.trim()?[{label:"Model",value:R.trim()}]:[]]},async()=>{const Te=ue.find(Le=>Le.key===tt.current);Te!=null&&Te.workspaceId?(fe(Te.workspaceId),ie("")):Te!=null&&Te.workspacePath?(fe("__custom__"),ie(Te.workspacePath)):(fe(""),ie("")),await se({workspaceId:(Te==null?void 0:Te.workspaceId)??null,workspacePath:(Te==null?void 0:Te.workspacePath)??"",useHome:!(Te!=null&&Te.workspaceId)&&!(Te!=null&&Te.workspacePath)})})},Ye=_=>{j?S(_):m(_.type,_.workspace,_.id)},Ve=o.useCallback(async(_,ee,ue=!1)=>{if(_.mode===ee){ue&&_.sessionId&&y(_.sessionId);return}if(!l||!_.sessionId){ue&&_.sessionId&&y(_.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_.type,mode:ee}),ue&&y(_.sessionId)}catch(Pe){const Ce=Pc(Pe);Rc(Pe)?console.warn(Ce?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Pe instanceof Error?Pe.message:String(Pe)):console.error("Failed to switch CLI view mode:",Pe)}},[r,y,l]),_e=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:te,onChange:_=>{const ee=_.target.value;if(fe(ee),ee==="__custom__"&&l){Z();return}ee!=="__custom__"&&ie("")},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:(s.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(_=>t.jsxs("option",{value:_.id,children:[_.id===s.defaultWorkspaceId?"⭐ ":"",Zr(_.path,_.label)]},_.id)),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]}):t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),te==="__custom__"&&(l?t.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:Z,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:ne,onChange:_=>ie(_.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}))]}),t.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:te==="__custom__"?Ke?t.jsx("span",{className:"font-mono truncate block",title:Ke,children:Ke}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Ke?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:te===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:Ke,children:Ke})]}):"No workspace selected. This launches in the home directory."})]});return t.jsxs("div",{children:[t.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${C.accent} relative overflow-hidden`,children:[t.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[t.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",C.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?Me.length>0?Me.map(_=>{const ee=a.find(Le=>(Le.type||"").toLowerCase()===(_.type||"").toLowerCase()&&bt(Le.status)!=="stopped"),ue=_.running||!!ee,Pe=!!ee&&ee.cdpConnected,Ce=ae.includes(_.type||_.id||""),Te=A===(_.type||"");return t.jsxs("button",{onClick:()=>{if(Pe&&ee){const Le=ee.sessionId;Le?d(Gt(Le),{state:{openRemoteForTabKey:Le}}):d("/dashboard",{state:{openRemoteForTabKey:ee.id}});return}Ce||I(Le=>Le===(_.type||"")?"":_.type||"")},disabled:!!x||Ce,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Pe?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Te?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:x&&x!==_.type?.4:1},children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(_.type)}),ue&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Pe?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.name||et(_.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Pe?"text-green-400":Ce?"text-orange-400":Te?"text-accent-primary":"text-text-muted"}`,children:Pe?"Open Session":Ce?"Starting...":Te?"Configure":"Select"})]})]},_.type)}):t.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.",t.jsxs("button",{onClick:p,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[t.jsx(Sd,{size:14})," Scan System"]})]}):b.length>0?b.map(_=>{const ee=A===_.type,ue=ae.includes(_.type),Ce=!!a.find(Te=>Te.type===_.type&&bt(Te.status)!=="stopped");return t.jsxs("button",{onClick:()=>I(Te=>Te===_.type?"":_.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ee?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:_.icon}),Ce&&t.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)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ue?"text-orange-400":ee?"text-accent-primary":"text-text-muted"}`,children:ue?"Starting...":ee?"Configure":"Select"})]})]},_.type)}):t.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.",t.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."})]})}),A&&(j?Me.find(_=>_.type===A):b.find(_=>_.type===A))&&t.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:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:j?et(A):E.get(A)||A})]}),_e,!j&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&t.jsx(il,{busy:!!v||!!x||ae.includes(A),savedSessionsLoading:xe,savedSessionsError:be,selectedSession:Fe,onRefresh:()=>void st(A),onOpenHistory:()=>{A&&(U(!0),ol({hasLoadedInitialResults:ce,isLoading:xe})&&st(A))},onClearSelection:()=>$("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:R,onChange:_=>G(_.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"})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),t.jsx("input",{type:"text",placeholder:"Optional flags...",value:P,onChange:_=>O(_.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),V.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:V.map(_=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>O(_),title:_,children:_},_))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:ze,disabled:!!v||!!x||ae.includes(A),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:v===A||x===A?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ae.filter(_=>!a.some(ee=>ee.type===_&&bt(ee.status)!=="stopped")).length,")"]}),a.length===0&&ve.length===0?t.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 ",C.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[ve.map(_=>t.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:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(_)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?et(_):E.get(_)||_}),t.jsx("div",{className:"text-[11px] text-text-muted",children:v===_?"Launching process...":"Waiting for process and session to register..."})]})]}),t.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:${_}`)),a.map(_=>{const ee=j?_:null,ue=!j&&!w?_:null,Pe=bt(_.status);return t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center mb-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(_.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ae(_),(ee==null?void 0:ee.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ee.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:_.workspace||"—"}),(ue==null?void 0:ue.mode)&&t.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)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ue.runtimeKey&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),t.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ue.runtimeKey]}),t.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 Ce;(Ce=navigator.clipboard)==null||Ce.writeText(`adhdev attach ${ue.runtimeKey}`),M(ue.runtimeKey||null),window.setTimeout(()=>{M(Te=>Te===ue.runtimeKey?null:Te)},1200)},children:N===ue.runtimeKey?"Copied":"Copy"})]}),ue.runtimeWriteOwner&&t.jsx("span",{style:{color:ue.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ue.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Ux(ue.runtimeWriteOwner)})]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Pe==="stopped"?"bg-red-500/[0.08] text-red-500":Pe==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Pe}),j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Ce=_.sessionId;if(Ce){d(Gt(Ce),{state:{openRemoteForTabKey:Ce}});return}d("/dashboard",{state:{openRemoteForTabKey:_.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:t.jsx(Ct,{size:13})}),t.jsx("button",{onClick:()=>{const Ce=_.workspace||"",{options:Te,selectedKey:Le}=os({machine:s,currentWorkspacePath:Ce});vt({title:ss("restart-ide",et(_.type)),description:rs("restart-ide"),confirmLabel:Cs("restart-ide"),busyLabel:Is("restart-ide"),workspaceOptions:Te,selectedWorkspaceKey:Le,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:et(_.type)}]},async()=>{const pt=Te.find(Ut=>Ut.key===tt.current),lt=(pt==null?void 0:pt.workspacePath)??"";if(lt&<!==Ce){await se({type:_.type,workspacePath:lt});return}await k(_)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:t.jsx(er,{size:14})})]}),w&&t.jsx("button",{onClick:()=>{const Ce=_.sessionId;Ce&&y(Ce)},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:!_.sessionId,children:t.jsx(Ft,{size:14})}),ue&&Pe!=="stopped"&&t.jsxs(t.Fragment,{children:[ue.mode&&t.jsx(Aa,{mode:ue.mode,onChange:Ce=>void Ve(ue,Ce,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Ce=_.sessionId;Ce&&y(Ce)},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:!_.sessionId,children:ue.mode==="chat"?t.jsx(Ft,{size:14}):t.jsx(Ct,{size:13})})]}),Pe==="stopped"?t.jsx("button",{onClick:()=>{const Ce=_.workspace||"",Te=j?et(_.type):Ae(_),{options:Le,selectedKey:pt}=os({machine:s,currentWorkspacePath:Ce});vt({title:ss("restart-stopped",Te),description:rs("restart-stopped"),confirmLabel:Cs("restart-stopped"),busyLabel:Is("restart-stopped"),workspaceOptions:Le,selectedWorkspaceKey:pt,details:[{label:"Mode",value:C.label},{label:"Provider",value:Te}]},async()=>{const lt=Le.find(Ut=>Ut.key===tt.current);await se({type:_.type,workspaceId:(lt==null?void 0:lt.workspaceId)??null,workspacePath:(lt==null?void 0:lt.workspacePath)??"",useHome:!(lt!=null&<.workspaceId)&&!(lt!=null&<.workspacePath)})})},disabled:ae.includes(_.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:ae.includes(_.type)?"⏳":t.jsx(ga,{size:14})}):t.jsx("button",{onClick:()=>Ye(_),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:t.jsx(wt,{size:14})})]})]}),ee&&ee.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ee.aiAgents.map(Ce=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Di(Ce.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ce.name," · ",bt(Ce.status)]},Ce.id))}),ee&&(F[ee.type]||[]).length>0&&l&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(F[ee.type]||[]).map(Ce=>t.jsxs("button",{disabled:oe===`${ee.type}.${Ce.type}`,onClick:async()=>{const Te=`${ee.type}.${Ce.type}`;ke(Te);try{await l(r,"set_ide_extension",{ideType:ee.type,extensionType:Ce.type,enabled:!Ce.enabled}),q(Le=>({...Le,[ee.type]:(Le[ee.type]||[]).map(pt=>pt.type===Ce.type?{...pt,enabled:!pt.enabled}:pt)}))}catch(Le){console.error("Extension toggle failed:",Le)}finally{ke(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 ${Ce.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Ce.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ce.name,t.jsx("span",{className:"text-[9px] font-normal",children:Ce.enabled?"ON":"OFF"})]},Ce.type))})]})]},_.id)})]}),he&&l&&t.jsx(an,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:T,directories:Y,busy:pe,error:Ne,confirmLabel:"Use this folder",onClose:()=>Se(!1),onNavigate:_=>{yt(_)},onConfirm:_=>{ie(_),fe("__custom__"),Se(!1)}}),Ue&&t.jsx(Ua,{title:Ue.title,description:Ue.description,details:Ue.details,workspaceOptions:Ue.workspaceOptions,selectedWorkspaceKey:ct,onWorkspaceChange:_=>{tt.current=_,ut(_)},confirmLabel:Ue.confirmLabel,busyLabel:Ue.busyLabel,busy:mt,onConfirm:K,onCancel:()=>{He.current=null,Qe(null)}}),z&&Tt&&t.jsx(_a,{activeConv:Tt,ides:[],isCreatingChat:!1,isRefreshingHistory:xe,savedSessions:H,isSavedSessionsLoading:xe,isResumingSavedSessionId:re,savedHistoryFilters:Q,onSavedHistoryFiltersChange:de,onClose:()=>U(!1),onNewChat:()=>{$(""),U(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{st(A)},onResumeSavedSession:_=>{if(!_.canResume||re)return;const ee=De(_);$(_.providerSessionId),Re(_),le(_.providerSessionId),U(!1),se({type:_.providerType,workspaceId:ee.workspaceId,workspacePath:ee.workspacePath,useHome:ee.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{le(ue=>ue===_.providerSessionId?null:ue)})}})]})}const ai=[{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 Vx({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:f,initialWorkspacePath:d,sendDaemonCommand:h}){var p;const[m,k]=o.useState(u);o.useEffect(()=>{k(u)},[u]);const S=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return t.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[t.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),t.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[t.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:ai.map(x=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${m===x.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>k(x.id),children:[t.jsx("span",{children:x.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${m===x.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:S[x.id]})]},x.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(p=ai.find(x=>x.id===m))==null?void 0:p.helper})]}),m==="ide"&&t.jsx(On,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d}),m==="cli"&&t.jsx(On,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d}),m==="acp"&&t.jsx(On,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d})]})}function Gx({onNicknameSynced:e}={}){var le,te,fe,ne,ie,ae,ye,he,Se;const{id:s}=ql(),r=Ms(),n=fa(),{sendCommand:a}=jt(),i=nr(),c=Mc(),l=nc(),u=l.ides||[],f=l.initialLoaded??!0,d=u.find(T=>T.id===s&&T.type==="adhdev-daemon"),h=u.some(T=>T.type==="adhdev-daemon"),[m,k]=o.useState("workspace"),[S,p]=o.useState("ide"),x=o.useRef(null),[v,g]=o.useState(null),N=o.useRef("__home__"),[M,y]=o.useState("__home__"),[C,j]=o.useState(!1),w=o.useRef(null);o.useEffect(()=>{!s||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,d,s]),o.useEffect(()=>{if(!s||!d||m!=="overview")return;const T=d.machine;(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")&&c(s,{minFreshMs:3e4}).catch(()=>{})},[m,c,d,s]),Jf(s&&m==="overview"?[s]:[],{enabled:m==="overview",intervalMs:dm});const b=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},E=xx({machineId:s,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:w});o.useEffect(()=>dt.onToast(D=>{l.setToasts(X=>{if(X.some(Ne=>Ne.message===D.message&&D.timestamp-Ne.timestamp<3e3))return X;const Ie={id:D.id,message:D.message,type:D.type,timestamp:D.timestamp,targetKey:D.targetKey,actions:D.actions};return[...X.slice(-4),Ie]});const Y=D.duration||5e3;setTimeout(()=>l.setToasts(X=>X.filter(pe=>pe.id!==D.id)),Y)}),[l]);const A=(d==null?void 0:d.availableProviders)||[],I={};for(const T of A)I[T.type]=T.icon;const P=T=>I[T]||"",O=d?{id:d.id,hostname:Ei(d,{fallbackId:d.id}),platform:((le=d.machine)==null?void 0:le.platform)||"unknown",arch:((te=d.machine)==null?void 0:te.arch)||"",cpus:((fe=d.machine)==null?void 0:fe.cpus)||0,totalMem:((ne=d.machine)==null?void 0:ne.totalMem)||0,freeMem:(ie=d.machine)==null?void 0:ie.freeMem,availableMem:(ae=d.machine)==null?void 0:ae.availableMem,loadavg:(ye=d.machine)==null?void 0:ye.loadavg,uptime:(he=d.machine)==null?void 0:he.uptime,release:((Se=d.machine)==null?void 0:Se.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,V=u.filter(T=>T.daemonId===s&&T.type!=="adhdev-daemon").filter(T=>!Xs(T)&&!ys(T)).map(T=>({id:T.id,sessionId:T.sessionId,type:T.type,version:T.version||"",instanceId:T.instanceId||"",status:T.status,workspace:T.workspace||null,terminals:T.terminals||0,aiAgents:bu(T.aiAgents||(T.agents||[]).map(D=>({id:D.name,name:D.name,status:D.status,version:D.version}))),activeChat:T.activeChat||null,chats:T.chats||[],childSessions:T.childSessions||[],cdpConnected:T.cdpConnected||!1,daemonId:s})),L=u.filter(T=>T.daemonId===s&&Xs(T)).map(T=>({id:T.id,sessionId:T.sessionId,type:T.type,cliName:T.cliName||T.type,status:T.status,workspace:T.workspace||"",activeChat:T.activeChat||null,providerSessionId:T.providerSessionId,mode:T.mode,runtimeKey:T.runtimeKey,runtimeDisplayName:T.runtimeDisplayName,runtimeWorkspaceLabel:T.runtimeWorkspaceLabel,runtimeWriteOwner:T.runtimeWriteOwner||null,runtimeAttachedClients:T.runtimeAttachedClients||[],daemonId:s})),R=u.filter(T=>T.daemonId===s&&ys(T)).map(T=>({id:T.id,sessionId:T.sessionId,type:T.type,acpName:T.cliName||T.type,status:T.status,workspace:T.workspace||"",activeChat:T.activeChat||null,providerSessionId:T.providerSessionId,daemonId:s})),G=d?At(d,{fallbackId:s}):"",B="workspace",$=n.state,H=$==null?void 0:$.initialMachineTab,J=$==null?void 0:$.initialWorkspaceCategory,xe=$==null?void 0:$.initialWorkspaceId,me=$==null?void 0:$.initialWorkspacePath,ce=H==="ides"||H==="clis"||H==="acps"?"workspace":H||B,ge=H==="ides"?"ide":H==="clis"?"cli":H==="acps"?"acp":J,be=[...V.map(T=>{var D,Y,X,pe,Ie;return{id:`ide:${T.type}:${T.workspace||""}`,label:((D=T.activeChat)==null?void 0:D.title)||T.type,kind:"ide",providerType:T.type,subtitle:T.workspace||void 0,workspace:T.workspace||void 0,lastLaunchedAt:((Ie=(pe=(X=(Y=T.activeChat)==null?void 0:Y.messages)==null?void 0:X.at)==null?void 0:pe.call(X,-1))==null?void 0:Ie.timestamp)||0}}),...L.map(T=>{var D,Y,X,pe,Ie;return{id:`cli:${T.type}:${T.workspace||""}`,label:((D=T.activeChat)==null?void 0:D.title)||T.cliName,kind:"cli",providerType:T.type,providerSessionId:T.providerSessionId,subtitle:T.workspace||void 0,workspace:T.workspace||void 0,lastLaunchedAt:((Ie=(pe=(X=(Y=T.activeChat)==null?void 0:Y.messages)==null?void 0:X.at)==null?void 0:pe.call(X,-1))==null?void 0:Ie.timestamp)||0}}),...R.map(T=>{var D,Y,X,pe,Ie;return{id:`acp:${T.type}:${T.workspace||""}`,label:((D=T.activeChat)==null?void 0:D.title)||T.acpName,kind:"acp",providerType:T.type,providerSessionId:T.providerSessionId,subtitle:ds(T.summaryMetadata)||T.workspace||void 0,workspace:T.workspace||void 0,lastLaunchedAt:((Ie=(pe=(X=(Y=T.activeChat)==null?void 0:Y.messages)==null?void 0:X.at)==null?void 0:pe.call(X,-1))==null?void 0:Ie.timestamp)||0}})].sort((T,D)=>(D.lastLaunchedAt||0)-(T.lastLaunchedAt||0)),we=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(T=>({id:T.id,label:T.title||T.providerName||T.providerType,kind:T.kind,providerType:T.providerType,providerSessionId:T.providerSessionId,subtitle:ds(T.summaryMetadata)||T.workspace||void 0,workspace:T.workspace,summaryMetadata:T.summaryMetadata,lastLaunchedAt:T.lastLaunchedAt})):be,z=o.useMemo(()=>{var D;const T=((D=l.connectionStates)==null?void 0:D[s||""])||void 0;return u.filter(Y=>Y.daemonId===s&&Y.type!=="adhdev-daemon").flatMap(Y=>Da(Y,{connectionStates:s&&T?{[s]:T}:void 0,defaultConnectionState:T})).filter(Y=>!(Y.transport==="pty"&&Y.mode==="terminal")).sort((Y,X)=>Zn(X)-Zn(Y))},[u,l.connectionStates,s]),U=o.useCallback(T=>{const D=Ca(T);D&&r(Gt(D))},[r]),Q=o.useCallback(()=>{x.current&&(j(!0),x.current().finally(()=>{x.current=null,j(!1),g(null)}))},[]),de=o.useCallback(T=>{if(!O)return;const{options:D,selectedKey:Y}=os({machine:O,currentWorkspacePath:T.workspace}),X=async()=>{p(T.kind),k("workspace")};x.current=async()=>{const pe=D.find(Be=>Be.key===N.current),Ie=(pe==null?void 0:pe.workspacePath)??null,Ne=(pe==null?void 0:pe.workspaceId)??null;if(T.kind==="ide"&&T.providerType){await E.handleLaunchIde(T.providerType,Ie?{workspace:Ie}:void 0);return}if((T.kind==="cli"||T.kind==="acp")&&T.providerType){await E.runLaunchCliCore({cliType:T.providerType,dir:Ne?void 0:Ie||"",workspaceId:Ne||void 0,model:T.kind==="acp"&&Bi(T.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:T.providerSessionId});return}await X()},N.current=Y,y(Y),g({title:T.kind==="ide"?ss("restart-ide",T.label):T.providerSessionId?Ra(T.label):ss("start-fresh",T.label),description:T.kind==="ide"?rs("restart-ide"):T.providerSessionId?Pa():rs("start-fresh"),confirmLabel:T.kind==="ide"?Cs("restart-ide"):T.providerSessionId?Ur(!0):Cs("start-fresh"),busyLabel:T.kind==="ide"?Is("restart-ide"):T.providerSessionId?Ta(!0):Is("start-fresh"),workspaceOptions:D,details:[{label:"Mode",value:T.kind.toUpperCase()},...T.providerType?[{label:"Provider",value:T.providerType}]:[]]})},[E,O]);if(o.useEffect(()=>{k(ce)},[B,ce,s]),o.useEffect(()=>{ge&&p(ge)},[ge,s]),!O)return f?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:b,className:"machine-btn-back",children:"← Back"})]}):t.jsx("div",{className:"p-10 text-center text-text-muted",children:t.jsx("p",{children:"⏳ Loading machine..."})});const re=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ct,{size:14})," Workspace"]}),count:V.length+L.length+R.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(ls,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Yr,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Nd,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(jd,{size:14})," Logs"]})}];return t.jsxs("div",{className:"flex flex-col h-full",children:[t.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:[t.jsx("div",{className:"flex items-center justify-between w-full",children:t.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[t.jsx("button",{onClick:b,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),t.jsxs("div",{className:"flex flex-col min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[E.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:E.nicknameInput,onChange:T=>E.setNicknameInput(T.target.value),onKeyDown:T=>{T.key==="Enter"&&E.handleSaveNickname(),T.key==="Escape"&&E.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]"}),t.jsx("button",{onClick:E.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"}),t.jsx("button",{onClick:()=>E.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"})]}):t.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{E.setEditingNickname(!0),E.setNicknameInput(O.machineNickname||"")},title:"Click to set nickname",children:G}),t.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"})]}),t.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:[t.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[O.platform," · ",O.arch]}),t.jsxs("span",{children:[O.cpus," cores"]}),(d==null?void 0:d.version)&&t.jsxs("span",{children:["v",d.version]}),O.p2p.available&&t.jsxs("span",{children:["P2P ",O.p2p.state==="connected"?"connected":O.p2p.state]}),O.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:O.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:re.map(T=>t.jsxs("button",{onClick:()=>k(T.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${m===T.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[T.label,T.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${m===T.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:T.count})]},T.id))})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:t.jsx("div",{className:"max-w-7xl mx-auto h-full",children:t.jsxs("div",{className:"h-full",children:[m==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(Fx,{machineEntry:d,providers:A,recentLaunches:we,currentConversations:z,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:de,onOpenConversation:U}),t.jsx(Vx,{machine:O,machineId:s,providers:A,ideSessions:V,cliSessions:L,acpSessions:R,actions:E,getIcon:P,initialCategory:S,initialWorkspaceId:xe,initialWorkspacePath:me,sendDaemonCommand:a})]}),m==="providers"&&t.jsx(Sx,{machineId:s,providers:A,sendDaemonCommand:a}),m==="overview"&&t.jsx(bx,{machineId:s,machine:O,ideSessions:V,cliSessions:L,acpSessions:R,actions:E,sendDaemonCommand:a}),m==="session-host"&&t.jsx(Wx,{machineId:s,cliSessions:L,sendDaemonCommand:a}),m==="logs"&&t.jsx(_x,{machineId:s,sendDaemonCommand:a})]})})}),E.launchPick&&O&&t.jsx(Hx,{machine:O,launchPick:E.launchPick,actions:E}),v&&t.jsx(Ua,{title:v.title,description:v.description,details:v.details,workspaceOptions:v.workspaceOptions,selectedWorkspaceKey:M,onWorkspaceChange:T=>{N.current=T,y(T)},confirmLabel:v.confirmLabel,busyLabel:v.busyLabel,busy:C,onConfirm:Q,onCancel:()=>{x.current=null,g(null)}}),t.jsx(pc,{toasts:l.toasts||[],onDismiss:T=>l.setToasts(D=>D.filter(Y=>Y.id!==T)),onClickToast:T=>{T.targetKey&&r(Gt(T.targetKey))}}),t.jsx("style",{children:`
|
|
72
|
+
@keyframes toast-in {
|
|
73
|
+
from { opacity: 0; transform: translateX(40px); }
|
|
74
|
+
to { opacity: 1; transform: translateX(0); }
|
|
75
|
+
}
|
|
76
|
+
`})]})}function Ga(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function qx(e){if(typeof window>"u")return e;const s=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=Ga();return r&&!s.searchParams.has("token")&&s.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?s.toString():`${s.pathname}${s.search}${s.hash}`}async function Et(e,s){return await fetch(qx(e),{credentials:"same-origin",...s})}function ml(){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 Yx{constructor(){Ge(this,"adapters",new Map);Ge(this,"states",new Map);Ge(this,"runtimeListeners",new Map);Ge(this,"screenshotCallbacks",new Map);Ge(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,a=!1,i,c){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:a,cols:i,rows:c})}emitSessionOutput(s,r,n){!s||typeof r!="string"||!r||this.emitRuntimeEvent(s,{type:"session_output",sessionId:s,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(s,r){const n=this.runtimeListeners.get(s)||new Set;return n.add(r),this.runtimeListeners.set(s,n),()=>{const a=this.runtimeListeners.get(s);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(s))}}async requestRuntimeSnapshot(s,r){if(!r)return{success:!1,error:"sessionId is required"};const n=await Et(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok){let i=`Runtime snapshot unavailable (${n.status})`;try{const c=await n.json();c!=null&&c.error&&(i=c.error)}catch{}return{success:!1,error:i}}const a=await n.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof a.seq=="number"?a.seq:0,text:typeof a.text=="string"?a.text:"",truncated:!!a.truncated,cols:typeof a.cols=="number"?a.cols:void 0,rows:typeof a.rows=="number"?a.rows:void 0}),{success:!0}}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(a=>a(r))}}const Ot=new Yx;function Xx(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Ga();return r?`${s}?token=${encodeURIComponent(r)}`:s}const Mr=Xx(),oi=3e3,Jx=3e4;let Rt=null,Qx=0;const qr=new Map;let Jt=null,Us=null;function ii(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function Es(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function Zx(e){return e==="connected"?"connected":e}async function Er(e,s,r){const n=bc(e,r||{}),a=Rt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Qx}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{qr.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);qr.set(i,{resolve:f=>{clearTimeout(u),c(f)},reject:f=>{clearTimeout(u),l(f)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function la(e,s){const r=Rt;if(!r||r.readyState!==WebSocket.OPEN||!s||s.type!=="subscribe"&&s.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}function eb(e,s,r){const n=Rt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=bc(e,{sessionId:s,targetSessionId:s,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class tb{constructor(s){Ge(this,"daemonId");Ge(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Er(this.daemonId,s,r)}async sendInput(s,r){return Er(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Jt&&(clearInterval(Jt),Jt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Er(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());Ot.emitScreenshot(this.daemonId,a)}}catch{}};r(),Jt=setInterval(r,2e3)}stopScreenshots(s){Jt&&(clearInterval(Jt),Jt=null)}}let Mt=null;function sb(e){return(!Mt||Mt.daemonId!==e)&&(Mt=new tb(e)),Mt}function rb({children:e}){const s=o.useRef(Gs()),r=Gs();s.current=r;const{setUserName:n}=cs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((p,x)=>{l(p),Us==null||Us(p,x)},[]),f=o.useRef(null),d=o.useRef(),h=o.useRef(oi),m=o.useRef(!0),k=o.useRef(!1),S=o.useRef("initial_connect");return o.useEffect(()=>{m.current=!0,k.current=!1;function p(){var g,N;if(!m.current||((g=f.current)==null?void 0:g.readyState)===WebSocket.OPEN||((N=f.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Mr}...`),Es("connect_attempt",{url:Mr,reason:S.current,delayMs:h.current});let v;try{v=new WebSocket(Mr)}catch(M){console.error("[Standalone WS] Failed to create WebSocket:",M),x();return}f.current=v,v.onopen=()=>{if(!m.current){v.close();return}u("connected"),h.current=oi,Es("open",{url:Mr,reason:S.current}),qt.resubscribeAll({sendData:la}),console.log("[Standalone WS] Connected")},Rt=v,v.onmessage=M=>{var y,C;try{const j=JSON.parse(M.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const w=qr.get(j.requestId);w&&(qr.delete(j.requestId),j.type==="error"?w.reject(new Error(((y=j.data)==null?void 0:y.message)||"Command failed")):w.resolve(j.data));return}if(j.type==="session_output"){const w=j.sessionId||j.cliId||j.cliType;w&&Ot.emitSessionOutput(w,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Ot.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated,typeof j.cols=="number"?j.cols:void 0,typeof j.rows=="number"?j.rows:void 0);return}if(j.type==="topic_update"){const w=j.update;w&&qt.publish(w);return}if(j.type==="status"||j.type==="initial_state"){const w=j.data;if(!w)return;const{injectEntries:b,markLoaded:E,getIdes:A}=s.current,I=w.instanceId||"standalone",P=A().find(L=>L.id===I),O=sb(I);Ot.register(I,O),Ot.setState(I,"connected"),u("connected",I),Ot.emitStatus(I,w);const V=Fr(w,{daemonId:I,existingDaemon:P,existingEntries:A()});ii("ws_status",{type:j.type,daemonId:I,sessions:(w.sessions||[]).map(L=>({id:L.id,parentId:L.parentId,providerType:L.providerType,kind:L.kind,transport:L.transport,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,title:L.title})),recentLaunches:(w.recentLaunches||[]).map(L=>({id:L.id,providerType:L.providerType,kind:L.kind,workspace:L.workspace,lastLaunchedAt:L.lastLaunchedAt}))}),ii("entries",{daemonId:I,entries:V.filter(L=>L.type!=="adhdev-daemon").map(L=>({id:L.id,type:L.type,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,sessionId:L.sessionId}))}),V.length>0&&b(V,{authoritativeDaemonIds:[I]}),E(),c.current!==I&&((C=i.current)==null||C.call(i),c.current=I,i.current=qt.subscribe({sendData:la},I,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${I}`,params:{includeSessions:!0}},L=>{if(L.topic!=="daemon.metadata")return;const R=s.current.getIdes(),G=R.find($=>$.id===I),B=Fr(L.status,{daemonId:I,existingDaemon:G,existingEntries:R,timestamp:L.timestamp});B.length>0&&s.current.injectEntries(B),L.userName&&a.current&&a.current(L.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},v.onclose=M=>{m.current&&(Mt==null||Mt.stopScreenshots(),Mt&&Ot.setState(Mt.daemonId,"disconnected"),u("disconnected"),f.current=null,S.current=`close:${M.code}${M.wasClean?":clean":":unclean"}`,Es("close",{code:M.code,reason:M.reason||"",wasClean:M.wasClean}),x())},v.onerror=M=>{k.current||!m.current||(S.current="error",Es("error",{message:M instanceof Event?"event":String(M),readyState:v.readyState}),console.warn("[Standalone WS] Error, will reconnect:",M))}}function x(){if(!m.current)return;clearTimeout(d.current);const v=h.current;console.log(`[Standalone WS] Reconnecting in ${v}ms...`),Es("schedule_reconnect",{reason:S.current,delayMs:v}),d.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Jx),p()},v)}return p(),()=>{var v;m.current=!1,k.current=!0,(v=i.current)==null||v.call(i),i.current=null,c.current=null,clearTimeout(d.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),Mt&&(Mt.stopScreenshots(),Ot.unregister(Mt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function nb({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Us=(c,l)=>{r(c),l&&a(l)},()=>{Us=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=Zx(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(md,{connectionOverrides:i,children:t.jsx(rb,{children:e})})}const fl="adhdev_standalone_font_preferences",is={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},ln=[{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"}],Zs=[{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"}],ab=new Set(ln.map(e=>e.id)),ob=new Set(Zs.map(e=>e.id));function Bt(e){const s=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:$r("chat",s.chat),code:$r("code",s.code),terminal:$r("terminal",s.terminal)}}function $r(e,s){const r=is[e],n=s&&typeof s=="object"&&!Array.isArray(s)?s:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?ab:ob).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Br(e,s){var a;const r=$r(e,s);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?ln:Zs;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function ib(e){const s=Bt(e),r=Br("chat",s.chat),n=Br("code",s.code),a=Br("terminal",s.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Zt(e,s=document.documentElement){const r=Bt(e),n=ib(r);s.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))s.style.setProperty(a,i);return r}function da(e){const s=Bt(e);try{localStorage.setItem(fl,JSON.stringify(s))}catch{}return s}function cb(){try{const e=localStorage.getItem(fl);if(e)return Bt(JSON.parse(e))}catch{}return is}function lb(){return Zt(cb())}function $s(e,s){var n;const r=e==="chat"?ln:Zs;return((n=r.find(a=>a.id===s))==null?void 0:n.label)||r[0].label}const db=[{id:"dashboard",path:"/dashboard",icon:t.jsx(vi,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(ls,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Yr,{}),label:"Settings"}];function ub({children:e}){const s=Ms(),r=fa(),n=o.useMemo(()=>db.map(i=>({...i,active:r.pathname.startsWith(i.path),onSelect:()=>s(i.path)})),[r.pathname,s]),a=o.useMemo(()=>[{id:"docs",label:t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Docs"}),t.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:t.jsx(ji,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:t.jsx(ki,{}),active:r.pathname==="/about",onSelect:()=>s("/about"),title:"About"}],[r.pathname,s]);return t.jsx(kf,{brand:({collapsed:i})=>t.jsxs(t.Fragment,{children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&t.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:i})=>i?null:t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.13"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>t.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:[t.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&t.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const mb=[{icon:t.jsx(ls,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Ft,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Si,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Ct,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(Ys,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(ji,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],fb=[{icon:t.jsx(Id,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(vi,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Xr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(wd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(wi,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(kd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],pb=[{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 hb(){return t.jsxs(wc,{icon:t.jsx(ki,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:t.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.13"]}),children:[t.jsx(Nt,{children:t.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[t.jsxs("div",{className:"max-w-2xl",children:[t.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),t.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."}),t.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."})]}),t.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[t.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 ↗"}),t.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 ↗"}),t.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 ↗"})]})]})}),t.jsx(Nt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:mb.map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.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]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Nt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:t.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:gc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:vc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:yc.map(e=>`${e.icon} ${e.name}`)}].map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[t.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),t.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(s=>t.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:s},s))})]},e.label))})}),t.jsx(Nt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:fb.map(e=>t.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.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]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Nt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:t.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:t.jsxs("table",{className:"w-full text-[13px]",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-bg-secondary",children:[t.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),t.jsx("tbody",{children:pb.map((e,s)=>t.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[t.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?t.jsx("span",{className:"text-emerald-500",children:"✓"}):t.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:t.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),t.jsx(kc,{icon:t.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:t.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),t.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[t.jsx($d,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Wn(e,s,r){return{...e,[s]:r}}function Hn({surface:e,title:s,description:r,value:n,options:a,onChange:i}){return t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:s}),t.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.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=>t.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&t.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})}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",t.jsx("span",{className:"font-mono break-all",children:Br(e,n)})]})]})]})}function xb({value:e,savedValue:s,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:u}){const f=JSON.stringify(e)!==JSON.stringify(s);return t.jsxs("div",{className:"flex flex-col gap-4",children:[t.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&&t.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&&t.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}),t.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[t.jsx(Hn,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:ln,onChange:d=>i(Wn(e,"chat",d))}),t.jsx(Hn,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Zs,onChange:d=>i(Wn(e,"code",d))}),t.jsx(Hn,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Zs,onChange:d=>i(Wn(e,"terminal",d))})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),t.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",$s("chat",e.chat.preset)," · Code: ",$s("code",e.code.preset)," · Terminal: ",$s("terminal",e.terminal.preset)]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",$s("chat",is.chat.preset)," / ",$s("code",is.code.preset)]})]}),t.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:t.jsxs("div",{className:"chat-container-content",children:[t.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:t.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[t.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[t.jsx("span",{className:"chat-sender",children:"Hermes"}),t.jsx("span",{className:"chat-time",children:"now"})]}),t.jsxs("div",{className:"chat-markdown",children:[t.jsxs("p",{children:["Readable prose, ",t.jsx("strong",{children:"bold text"}),", and ",t.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),t.jsx("pre",{children:t.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),t.jsxs("div",{className:"chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"▸"}),t.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),t.jsxs("div",{className:"chat-msg-terminal",children:[t.jsx("div",{className:"chat-msg-header",children:"Terminal"}),t.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:c,disabled:r||!f,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),t.jsx("button",{type:"button",onClick:l,disabled:r||!f,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),t.jsx("button",{type:"button",onClick:u,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function bb(){const{ides:e}=cs(),s=e.find(z=>z.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=jt(),{userName:a}=cs(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[f,d]=o.useState(null),[h,m]=o.useState(is),[k,S]=o.useState(!1),[p,x]=o.useState(""),[v,g]=o.useState(""),[N,M]=o.useState("127.0.0.1"),[y,C]=o.useState(""),[j,w]=o.useState(""),[b,E]=o.useState(""),[A,I]=o.useState(""),[P,O]=o.useState(""),[V,L]=o.useState(!1),R=async()=>{const U=await(await Et("/auth/session")).json();u(U)},G=async()=>{const U=await(await Et("/api/v1/standalone/preferences")).json();d(U),M(U.standaloneBindHost);const Q=Bt(U.standaloneFontPreferences);m(Q),Zt(Q),da(Q)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([R(),G()]).catch(z=>{I(z instanceof Error?z.message:String(z))})},[]),o.useEffect(()=>{Zt(h)},[h]);const B=z=>{const U=z.target.value.trim();s!=null&&s.id&&U!==a&&n(s.id,"set_user_name",{userName:U}).catch(console.error)},[$,H]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=z=>{H(z);try{localStorage.setItem("adhdev_sound",z?"1":"0")}catch{}},xe=async()=>{x(""),g(""),S(!0);try{const z=Bt(h),U=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:z})}),Q=await U.json();if(!U.ok)throw new Error((Q==null?void 0:Q.error)||"Failed to save standalone font preferences");const de=Bt(Q.standaloneFontPreferences);d(Q),m(de),Zt(de),da(de),g("Standalone chat fonts saved for this self-hosted dashboard.")}catch(z){x(z instanceof Error?z.message:String(z))}finally{S(!1)}},me=()=>{const z=Bt(f==null?void 0:f.standaloneFontPreferences);x(""),g(""),m(z),Zt(z)},ce=()=>{x(""),g(""),m(is),Zt(is)},ge=async()=>{I(""),O(""),L(!0);try{const z=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),U=await z.json();if(!z.ok)throw new Error((U==null?void 0:U.error)||"Failed to save standalone network preference");d(U),M(U.standaloneBindHost),O(U.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(z){I(z instanceof Error?z.message:String(z))}finally{L(!1)}},be=async()=>{if(I(""),O(""),j.trim().length<4){I("Password must be at least 4 characters.");return}if(j!==b){I("New password and confirmation do not match.");return}L(!0);try{const z=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:j})}),U=await z.json();if(!z.ok)throw new Error((U==null?void 0:U.error)||"Failed to save password");u(U),await G(),C(""),w(""),E(""),O(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),ml()}catch(z){I(z instanceof Error?z.message:String(z))}finally{L(!1)}},we=async()=>{I(""),O(""),L(!0);try{const z=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),U=await z.json();if(!z.ok)throw new Error((U==null?void 0:U.error)||"Failed to clear password");u(U),await G(),C(""),w(""),E(""),O("Standalone password disabled.")}catch(z){I(z instanceof Error?z.message:String(z))}finally{L(!1)}};return t.jsxs(wc,{icon:t.jsx(Yr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(gr,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&t.jsx(gr,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),t.jsx(Nt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:t.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[t.jsx("span",{className:"text-text-muted",children:"Version"}),t.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.13"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"Current bind"}),t.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Default bind"}),t.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.standaloneBindHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Auth"}),t.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),t.jsx(Nt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.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."}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.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:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:N==="127.0.0.1",onChange:()=>M("127.0.0.1")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),t.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."})]})]}),t.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:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:N==="0.0.0.0",onChange:()=>M("0.0.0.0")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),t.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."})]})]})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:()=>{ge()},disabled:V,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:V?"Saving…":"Save default network mode"}),t.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(Nt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.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."}),A&&t.jsx(gr,{variant:"error",children:A}),P&&t.jsx(gr,{variant:"success",children:P}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.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:y,onChange:z=>C(z.target.value)}),t.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:j,onChange:z=>w(z.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:b,onChange:z=>E(z.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{be()},disabled:V,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:V?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{we()},disabled:V,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"})]})]})}),t.jsx(Nt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?t.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):t.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(z=>t.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${z.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:z.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:z.type})]},z.type))})}),t.jsx(Nt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Rf,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Nt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),t.jsx(Ef,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),t.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."}),t.jsx(Uf,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),t.jsx(xb,{value:h,savedValue:Bt(f==null?void 0:f.standaloneFontPreferences),saving:k,error:p,notice:v,onChange:m,onSave:()=>{xe()},onResetToSaved:me,onResetToDefaults:ce})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),t.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."}),t.jsx(Gf,{})]})]})}),t.jsx(Nt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Af,{}),t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ed,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:$,onChange:J})]})}),t.jsx(Nt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:t.jsx("div",{className:"flex flex-col gap-3",children:t.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:[t.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[t.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[t.jsx(vd,{size:16,className:"text-text-secondary"})," Display Name"]}),t.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),t.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:z=>c(z.target.value),onBlur:B,onKeyDown:z=>{z.key==="Enter"&&z.currentTarget.blur()}})]})})})]})}wf();Hf();lb();const gb=bi({baseUrl:"",getToken:Ga});function yb({children:e}){const[s,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[f,d]=o.useState(!1),h=async()=>{a(!0),u("");try{const S=await(await Et("/auth/session")).json();r(S)}catch(k){u(k instanceof Error?k.message:String(k))}finally{a(!1)}};o.useEffect(()=>{h()},[]),o.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let k=!1;return(async()=>{try{const S=await Et("/api/v1/standalone/preferences");if(!S.ok)return;const p=await S.json();if(k)return;const x=Bt(p.standaloneFontPreferences);Zt(x),da(x)}catch{}})(),()=>{k=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const m=async k=>{k.preventDefault(),d(!0),u("");try{const S=await Et("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),p=await S.json();if(!S.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),ml()}catch(S){u(S instanceof Error?S.message:String(S))}finally{d(!1)}};return n?t.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):s?!s.required||s.authenticated?t.jsx(t.Fragment,{children:e}):t.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:t.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:[t.jsxs("div",{children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),t.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.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."})]}),s.hasPasswordAuth?t.jsxs("form",{className:"flex flex-col gap-3",onSubmit:m,children:[t.jsx("input",{type:"password",value:i,onChange:k=>c(k.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}),t.jsx("button",{type:"submit",disabled:f||!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:f?"Signing in…":"Unlock dashboard"})]}):t.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&&t.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})]})}):t.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 ci(){const{ides:e,initialLoaded:s}=cs();if(!s)return t.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?t.jsx(zn,{to:`/machines/${r.id}`,replace:!0}):t.jsx(zn,{to:"/dashboard",replace:!0})}function vb(){const e=o.useMemo(()=>({sendCommand:Er,sendData:la,sendPtyInput:eb}),[]);return t.jsx(Yl,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(hd,{client:gb,children:t.jsx(yb,{children:t.jsx(nb,{children:t.jsx(bd,{value:e,children:t.jsx(ub,{children:t.jsxs(Xl,{children:[t.jsx(Yt,{path:"/dashboard",element:t.jsx(hx,{})}),t.jsx(Yt,{path:"/machine",element:t.jsx(ci,{})}),t.jsx(Yt,{path:"/machines/:id",element:t.jsx(Gx,{})}),t.jsx(Yt,{path:"/machines",element:t.jsx(ci,{})}),t.jsx(Yt,{path:"/about",element:t.jsx(hb,{})}),t.jsx(Yt,{path:"/settings",element:t.jsx(bb,{})}),t.jsx(Yt,{path:"*",element:t.jsx(zn,{to:"/dashboard",replace:!0})})]})})})})})})})}Km({connectionManager:Ot});Jl(document.getElementById("root")).render(t.jsx(vb,{}));
|