@adhdev/daemon-standalone 0.9.23 → 0.9.25
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 +9 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-CCt9RFKL.css +1 -0
- package/public/assets/{index-CO9PvKP8.js → index-DaZ-j9ka.js} +26 -26
- package/public/index.html +2 -2
- package/vendor/session-host-daemon/index.js +6 -4
- package/vendor/session-host-daemon/index.js.map +1 -1
- package/vendor/session-host-daemon/index.mjs +6 -4
- package/vendor/session-host-daemon/index.mjs.map +1 -1
- package/public/assets/index-C-TSgji3.css +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
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 Gl=Object.defineProperty;var ql=(e,t,r)=>t in e?Gl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ge=(e,t,r)=>ql(e,typeof t!="symbol"?t+"":t,r);import{r as o,j as s,M as ma,a as fa,b as mi,c as fi,u as As,R as St,d as zs,t as Yl,e as Xl,D as Jl,f as Un,g as zn,h as pa,i as Ql,k as Zl,B as ed,l as td,m as Yt,N as Vn,n as sd}from"./vendor-BRZ4K-AC.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();function rd(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(a),r.length>t&&r.splice(0,r.length-t),a},list(n={}){const a=Math.max(1,Math.floor(n.limit||100));return r.filter(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=rd();function no(e){const t={};for(const r of e)r.transport&&(t[r.transport]=(t[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:t}}function nd(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function ad(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function pi(e,t){if(!e)return t??null;if(!t)return e??null;const r=ad(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:t.messages,a=e.activeModal||(e.status==="waiting_approval"?t.activeModal:null),i={...t,...e,activeModal:a,inputContent:e.inputContent??t.inputContent};return r?{...i,messages:n}:i}function Bs(e,t){const r=nd(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(t==null?void 0:t.parentSessionId)??null,providerSessionId:e.providerSessionId??(t==null?void 0:t.providerSessionId),providerName:r??(t==null?void 0:t.providerName)??(t==null?void 0:t.cliName)??(t==null?void 0:t.type)??e.providerName??e.providerType,title:e.title??(t==null?void 0:t.title)??r??(t==null?void 0:t.providerName)??e.providerName??e.providerType,workspace:e.workspace??(t==null?void 0:t.workspace)??null,mode:e.mode??(t==null?void 0:t.mode),capabilities:e.capabilities??(t==null?void 0:t.sessionCapabilities)??(t==null?void 0:t.capabilities)??[],cdpConnected:e.cdpConnected??(t==null?void 0:t.cdpConnected),activeChat:pi(e.activeChat,t==null?void 0:t.activeChat),controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel)}}function hi(e,t,r){if(!(t!=null&&t.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const n=t.map(a=>{const i=e.find(c=>c.id===a.id);return i?Bs(a,i):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(t.map(i=>i.id));for(const i of e)a.has(i.id)||n.push(i)}return n}function ao(e){return!!e&&typeof e=="object"&&"text"in e}function ha(e,t){const r=(t==null?void 0:t.joiner)??" ",n=(t==null?void 0:t.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(i=>typeof i=="string"?i:ao(i)?String(i.text||""):"").join(r):ao(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Vs(e){return ha(e,{normalizeWhitespace:!0})}const xi=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}),bi=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function oo(e){var r,n;let t=0;return e.activeChat!==void 0&&(t+=4),(r=e.childSessions)!=null&&r.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(n=e.agents)!=null&&n.length&&(t+=1),t}function gi(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,i=t.serverVersion??e.serverVersion??r.serverVersion,c=t.versionMismatch===!0||e.versionMismatch===!0,l=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,u=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),i&&(n.serverVersion=i),u&&(n.versionUpdateReason=u),a&&i&&a===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||c&&a&&i&&a!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function od(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function dn(e){if(!e||typeof e!="object")return"";const t=e,r=od(Vs(t.content).slice(0,512));return[String(t.id||""),String(t._localId||""),String(t._turnKey||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),r].join(":")}function id(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=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 Gn(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function qn(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(Gn(e)&&Gn(t)){const c=e.messages;Array.isArray(c)&&c===t.messages&&r.add(c)}if(Array.isArray(e)&&Array.isArray(t)){const c=Math.min(e.length,t.length);for(let l=0;l<c;l+=1)qn(e[l],t[l],r);return}const n=e,a=t,i=new Set([...Object.keys(n),...Object.keys(a)]);for(const c of i)c!=="messages"&&qn(n[c],a[c],r)}function Ks(e,t){return Array.isArray(e)?e.map(r=>Ks(r,t)):!e||typeof e!="object"?e:Gn(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?id(a,t):Ks(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Ks(n,t)]))}function cd(e,t){try{const r=new WeakSet;return qn(e,t,r),JSON.stringify(Ks(e,r))===JSON.stringify(Ks(t,r))}catch{return!1}}function Yn(e,t,r){return cd(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function yi(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function ld(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function io(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,i=hi(e.childSessions,t.childSessions,{preserveMissing:n}),c=pi(t.activeChat,e.activeChat);return gi(e,t,{...e,...t,chats:a,childSessions:i,activeChat:c,_lastUpdate:r})}function dd(e,t,r){var a,i;const n={};t.status&&t.status!==e.status&&(n.status=t.status),t.cdpConnected!==void 0&&(n.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(n.childSessions=hi(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((i=e.chats)!=null&&i.length)&&(n.chats=t.chats);for(const c of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion"])ld(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function ud(e,t,r,n){const a=dd(e,t,n),i=Object.keys(a).length>0?gi(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return Yn(e,i,r)}function md(e){const t=new Set(e.map(a=>a.id)),r=new Set,n=new Set;for(const a of e){const i=yi(a);i&&r.add(i),i&&a.type!=="adhdev-daemon"&&n.add(i)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n}}function fd(e,t,r,n,a,i){return!a.has(t)||!i.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function pd(e,t,r,n){return!!(r.has(t)&&e.transport&&!n.has(t))}function hd(e,t,r){var f,d;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(h=>({...h,_lastUpdate:n}));const i=new Map;for(const h of t)i.set(h.id,h);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:u}=md(e);for(const h of e){const m=i.get(h.id);if(!m){i.set(h.id,{...h,_lastUpdate:n});continue}const w=oo(h),S=oo(m),p=yi(h),x=!a.has(p);if(w>S){const N=io(m,h,n,x);i.set(h.id,Yn(m,N,n));continue}if(w<S){i.set(h.id,ud(m,h,n,x));continue}const j=h.timestamp||n,b=m._lastUpdate||m.timestamp||0;if(j>=b){const N=io(m,h,n,x);i.set(h.id,Yn(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 w=m.daemonId||h.split(":")[0];if(!l.has(w))continue;if(a.has(w)&&!c.has(h)){i.delete(h);continue}const S=n-(m._lastUpdate||m.timestamp||0);fd(m,w,S,c,a,u)&&i.delete(h)}for(const[h,m]of i){const w=m.daemonId||h.split(":")[0];if(pd(m,w,l,u))continue;n-(m._lastUpdate||m.timestamp||0)>3e5&&m.status!=="online"&&i.delete(h)}return Array.from(i.values())}function xd(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function bd({children:e,connectionOverrides:t}){const[r,n]=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((j,b)=>{n(N=>{let T=!1;const y=N.map(C=>C.id!==j||C.chats===b?C:(T=!0,{...C,chats:b}));return T?y:N})},[]),m=o.useCallback((j,b)=>{n(N=>{const T=N.length===0?j:hd(j,N,b),y=!xd(N,T);return y&&ks.record({kind:"dashboard.entries_applied",payload:{incoming:no(j),next:no(T)}}),y?T:N})},[]),w=o.useCallback(()=>i(!0),[]),S=o.useMemo(()=>({injectEntries:m,markLoaded:w,getIdes:()=>d.current}),[m,w]),p=t,x=o.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(p==null?void 0:p.wsStatus)??"connected",isConnected:(p==null?void 0:p.isConnected)??!0,connectionStates:(p==null?void 0:p.connectionStates)??{},connectionTransports:(p==null?void 0:p.connectionTransports)??{},showReconnected:(p==null?void 0:p.showReconnected)??!1,retryConnection:p==null?void 0:p.retryConnection,retryServerConnection:p==null?void 0:p.retryServerConnection,connectionLoginUrl:p==null?void 0:p.connectionLoginUrl,isP2PActive:(p==null?void 0:p.isP2PActive)??!1,p2pStates:(p==null?void 0:p.p2pStates)??{},userRole:p==null?void 0:p.userRole,userName:u,setUserName: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.connectionLoginUrl,p==null?void 0:p.isP2PActive,p==null?void 0:p.p2pStates,p==null?void 0:p.userRole,u]);return s.jsx(bi.Provider,{value:S,children:s.jsx(xi.Provider,{value:x,children:e})})}function cs(){return o.useContext(xi)}function Gs(){return o.useContext(bi)}function vi(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function i(l){const u=r==null?void 0:r(),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")&&!t?`${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,w=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(w)}}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 gd=vi({baseUrl:"http://localhost:3847"}),yd=o.createContext(gd);function vd({client:e,children:t}){return s.jsx(yd.Provider,{value:e,children:t})}const wd={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},wi=o.createContext(wd);function jd({value:e,children:t}){return s.jsx(wi.Provider,{value:e,children:t})}function jt(){return o.useContext(wi)}function kd(e){let t=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)t^=n.charCodeAt(a),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function Sd(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function ji(e){return e?kd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Sd(e.content)]):""}const $e={size:18};function ki({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function xa({size:e=$e.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function ls({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function Si({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Nd({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Cd({size:e=$e.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function Ni({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Id({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Yr({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Ci({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Ad({size:e=$e.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Ft({size:e=$e.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Ct({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function ba({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("polyline",{points:"14 2 14 8 20 8"}),s.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),s.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Md({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Ss({size:e=$e.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function er({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function qs({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Ys({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function Ii({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Ai({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),s.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Mi({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function Td({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function ga({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Ld({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function ya({size:e=$e.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Ti({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function wt({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Rd({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),s.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),s.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),s.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Pd({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function _d({size:e=$e.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function Dd({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function Xr({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Ed({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"5"}),s.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),s.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),s.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),s.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),s.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),s.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),s.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),s.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function $d({size:e=$e.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Bd({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Kd({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Od({size:e=$e.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Wd({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function Hd({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function Fd({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function Ud({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function zd({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function Vd({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function Gd({size:e=$e.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const Li=200,co=650,un=new Map;function lo(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function qd(e){if(!Array.isArray(e)||e.length===0)return"0:empty";const t=e[e.length-1];return`${e.length}:${ji(t)}`}function Yd(e,t){return!e&&t}function uo(e,t=Li){return!!e&&e.fromBottom>=t}function Xd({hasSelection:e,userScrolledUp:t}){return!(e||t)}function Jd({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function mo(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function Ri(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Qd(e,t,r){return Number(e.receivedAt||r[Kr(e,t)]||0)||0}function Pi(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Zd(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function dr(e,t){if(!e)return t;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||t}catch{return e.split(/[\\/]/).filter(Boolean).pop()||t}}function 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 fo(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Pi(e)?s.jsx(ma,{remarkPlugins:[fa,mi,fi],children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function ur({parts:e,renderAsPreformatted:t}){return s.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return s.jsx("div",{children:fo(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=mn(r);return a?s.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?s.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=mn(r);return a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:dr(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||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 s.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[s.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),fo(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return s.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function Kr(e,t){const r=e,n=ha(e.content,{joiner:`
|
|
3
|
-
`});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${t}`].filter(Boolean).join("|")}const
|
|
4
|
-
`});if(d==="thought"){const g=typeof((C=t.meta)==null?void 0:C.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(_d,{size:13}),s.jsx("span",{children:g})]}),s.jsx("div",{className:"chat-msg-body",children:w})]})}if(d==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),m&&h?s.jsx("div",{className:"tool-text w-full",children:s.jsx(ur,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:w})]});if(d==="terminal"){const g=(k=t.meta)!=null&&k.isRunning?"⏳":"✅",D=typeof((v=t.meta)==null?void 0:v.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:g}),s.jsx("span",{children:D})]}),m&&h?s.jsx("div",{className:"chat-msg-body",children:s.jsx(ur,{parts:h,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:w})]})}if(d==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:m&&h?s.jsx(ur,{parts:h,renderAsPreformatted:!1}):w.slice(0,100)});const S=t.meta,x=(typeof(S==null?void 0:S.renderMode)=="string"?S.renderMode.trim():"")==="preformatted",j=w,b=!1,N=j,T=x,y=!T&&Pi(N);return s.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${f?"self-end":"self-start"}`,children:(j||m||f)&&s.jsxs("div",{className:`chat-bubble ${f?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${j||m?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:f?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:Ri(r)})]}),(j||m)&&s.jsx("div",{className:"chat-markdown",children:m&&h?s.jsx(ur,{parts:h,renderAsPreformatted:T}):T?s.jsx("pre",{className:"chat-preformatted",children:N}):y?s.jsx(ma,{remarkPlugins:[fa,mi,fi],children:N}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:N})}),b]})})},(e,t)=>e.message===t.message&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),su=o.forwardRef(function({messages:t,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:w=0,loadError:S,scrollToBottomRequestNonce:p,isVisible:x=!0},j){const b=o.useRef(null),N=o.useRef(null),T=o.useRef(null),y=o.useRef(0),C=o.useRef(""),k=o.useRef(!1),v=o.useRef(null),g=o.useRef(!1),D=o.useRef(null),M=o.useRef(!1),[I,P]=o.useState(new Set),K=o.useRef(!1),V=o.useRef(!1),L=o.useRef(x),R=()=>{const F=b.current;return F?F.scrollHeight-F.scrollTop-F.clientHeight<Li:!0},G=o.useCallback((F="auto")=>{const Q=b.current;Q&&Q.scrollTo({top:Q.scrollHeight,behavior:F})},[]),B=o.useCallback(()=>{var fe;const F=b.current,Q=(fe=window.getSelection)==null?void 0:fe.call(window);if(!F||!Q||Q.rangeCount===0||Q.isCollapsed){M.current=!1;return}const ue=Q.anchorNode,te=Q.focusNode;M.current=!!(ue&&te&&F.contains(ue)&&F.contains(te))},[]),E=qd(t),W=o.useCallback(()=>{const F=b.current;!F||!l||un.set(l,{top:F.scrollTop,fromBottom:Math.max(0,F.scrollHeight-F.scrollTop-F.clientHeight),messageFingerprint:E})},[l,E]),J=o.useCallback((F="auto")=>{v.current!=null&&cancelAnimationFrame(v.current),v.current=requestAnimationFrame(()=>{v.current=null,G(F)})},[G]),be=o.useCallback(()=>{K.current=!1,g.current=!0,V.current=!0,D.current!=null&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>{g.current=!1,D.current=null},co)},[]);o.useEffect(()=>{const F=!k.current,Q=C.current!==l;if(C.current=l,F||Q){if(k.current=!0,K.current=!1,g.current=!0,!M.current){const ue=l?un.get(l):null;ue&&lo(ue,E)?requestAnimationFrame(()=>{const te=b.current;te&&(mo(te,ue),K.current=uo(ue),V.current=!0)}):J("auto")}y.current=t.length;return}t.length>y.current,Xd({hasSelection:M.current,userScrolledUp:K.current})&&J("auto"),y.current=t.length},[E,l,c,t.length,J]),o.useEffect(()=>{p&&(be(),M.current||J("auto"))},[be,J,p]),o.useEffect(()=>{const F=L.current;L.current=x,Yd(F,x)&&(be(),M.current||J("auto"))},[x,be,J]),o.useEffect(()=>()=>{W(),v.current!=null&&cancelAnimationFrame(v.current),D.current!=null&&window.clearTimeout(D.current)},[W]),o.useEffect(()=>{const F=N.current,Q=b.current;if(!F||!Q)return;const ue=()=>{D.current!=null&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>{g.current=!1,D.current=null},co)},te=new ResizeObserver(()=>{const fe=g.current;Jd({hasSelection:M.current,userScrolledUp:K.current,contextAutoScrollActive:fe})&&(J("auto"),fe&&ue())});return te.observe(F),Q!==F&&te.observe(Q),()=>{te.disconnect(),D.current!=null&&(window.clearTimeout(D.current),D.current=null)}},[J,l]),o.useImperativeHandle(j,()=>({scrollToBottom:(F="smooth")=>{G(F)}}),[G]),o.useEffect(()=>{const F=b.current;if(!F)return;let Q;const ue=()=>{clearTimeout(Q),Q=setTimeout(()=>{K.current=!R(),W()},50)};return F.addEventListener("scroll",ue,{passive:!0}),()=>{F.removeEventListener("scroll",ue),clearTimeout(Q)}},[W]),o.useEffect(()=>(document.addEventListener("selectionchange",B),()=>document.removeEventListener("selectionchange",B)),[B]);const he=o.useRef(0),de=o.useRef(!1);o.useEffect(()=>{const F=b.current;if(!F||!de.current||he.current===0)return;const Q=F.scrollHeight-he.current;Q>0&&(F.scrollTop=Q),W(),he.current=0,de.current=!1},[t.length,W]),o.useEffect(()=>{if(V.current||!l)return;const F=un.get(l),Q=b.current;if(!(!F||!Q)){if(!lo(F,E)){G("auto"),V.current=!0;return}mo(Q,F),K.current=uo(F),V.current=!0}},[l,E,t.length,G]);const ye=()=>{const F=b.current;F&&(he.current=F.scrollHeight),de.current=!0,d==null||d()},ge=o.useMemo(()=>{const F=t.map((fe,ne)=>({type:"message",data:fe,index:ne,ts:Qd(fe,ne,u)}));if(!r||r.length===0)return F;const Q=[...r].sort((fe,ne)=>fe.timestamp-ne.timestamp).map((fe,ne)=>({type:"action",data:fe,index:ne,ts:fe.timestamp})),ue=[];let te=0;for(const fe of F){for(;te<Q.length&&fe.ts>0&&Q[te].ts<fe.ts;)ue.push(Q[te++]);ue.push(fe)}for(;te<Q.length;)ue.push(Q[te++]);return ue},[t,r,u]),ve=w>0||!!m,z=w>0?`↑ Show ${Math.min(w,80)} earlier messages${w>80?` (${w} hidden)`:""}`:S?`↻ ${S}`:"↑ Load older messages";return s.jsx("div",{ref:b,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:N,className:"chat-container-content",children:[h&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),ve&&!h&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{onClick:ye,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${S&&w===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})}),ge.length===0&&!ve&&(f||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ge.map(F=>{if(F.type==="action"){const re=F.data;return s.jsx(eu,{log:re},`action-${F.index}`)}const Q=F.data,ue=F.index,te=Kr(Q,ue),fe=Q.receivedAt||u[te],ne=`${l}-${te}`,xe=I.has(ne);return s.jsx(tu,{message:Q,receivedAt:fe,agentName:n,userName:a,isCliMode:i,isTextExpanded:xe,onToggleTextExpanded:()=>P(re=>{const le=new Set(re);return xe?le.delete(ne):le.add(ne),le})},`msg-${te}`)}),c&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),s.jsx("div",{className:"min-h-10",ref:T})]})})}),ru=o.memo(su,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible),nu="modulepreload",au=function(e){return"/"+e},po={},ou=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=Promise.allSettled(r.map(u=>{if(u=au(u),u in po)return;po[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":nu,f||(h.as="script"),h.crossOrigin="",h.href=u,l&&h.setAttribute("nonce",l),document.head.appendChild(h),f)return new Promise((m,w)=>{h.addEventListener("load",m),h.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};let ho=!1;const _i=o.forwardRef(({onInput:e,onViewportMetrics:t,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),w=()=>{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&&w()},[l]),o.useEffect(()=>{let S=!1;return ou(()=>import("./terminal-Bv6gUGuY.js"),__vite__mapDeps([0,1,2])).then(p=>{ho||(ho=!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?s.jsx(l,{ref:c,onInput:e,onViewportMetrics:t,fontSize:r,readOnly:n,sizingMode:a,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});_i.displayName="CliTerminal";function mr({label:e,value:t,sub:r,icon:n}){return s.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:n}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),r&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function xo({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:i=!1}){const c=t>0?Math.min(Math.round(e/t*100),100):0,l=c>85?"#ef4444":c>60?"var(--status-warning)":n;return i?s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),s.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[c,"%"]})]}),s.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${c}%`,background:l}})})]}):s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-1.5",children:[s.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),s.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[c,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${c}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function iu({cursorPos:e,viewportRef:t,imgRef:r}){var b;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(b=t.current)==null?void 0:b.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,w;u>f?(d=a.width,h=a.width/u,m=0,w=(a.height-h)/2):(h=a.height,d=a.height*u,m=(a.width-d)/2,w=0);const S=a.left-i.left+m+d*e.nx,p=a.top-i.top+w+h*e.ny,x=Math.max(8,Math.min(i.width-8,S)),j=Math.max(8,Math.min(i.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:x-8,top:j-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function cu({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:f,zoom:d,isMobile:h,mobileFillZoom:m,onZoomOut:w,onZoomReset:S,onZoomIn:p,transportType:x,screenshotUsage:j,lastActionStatus:b}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:N=>N.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{n(N=>!N),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:N=>N.stopPropagation(),onChange:N=>l(N.target.value),onKeyDown:N=>{u(N)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{i(N=>!N),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:f?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:f?"#22c55e":"#eab308",boxShadow:f?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:f?"#22c55e":"#eab308"},children:f?"Connected":"WS"})]}),d>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),x==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),x==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),j&&j.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:j.budgetExhausted?"#ef4444":"#c4b5fd",background:j.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:j.budgetExhausted?"TURN blocked":`TURN ${j.dailyUsedMinutes}/${j.dailyBudgetMinutes}m`}),b&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:b})]})]}),a&&s.jsxs("div",{onTouchStart:N=>N.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",d<=(h?m:1)+.01?h?"FILL":"FIT":`${Math.round(d*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:N=>{N.stopPropagation(),w()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:N=>{N.stopPropagation(),S()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:h?"FILL":"FIT"}),s.jsx("button",{onClick:N=>{N.stopPropagation(),p()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function lu({waitingLabel:e,waitingHint:t,transportType:r}){return s.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[s.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),s.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),s.jsx("div",{className:"text-[11px] text-white/40",children:t}),r==="relay"&&s.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function du(){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 bo(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,t){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!du())return;n.current+=1;const a=r.current;if(!a){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([c,l])=>[c,bo(l)]))}),r.current=t;return}const i=Object.keys({...a,...t}).filter(c=>!Object.is(a[c],t[c]));i.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(c=>[c,bo(t[c])]))}),r.current=t})}function uu({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:f,setPanY:d,setZoom:h,lastWheelTimeRef:m,onAction:w,setLastActionStatus:S,spawnRippleFromNormalized:p,clampPan:x,isMobile:j,mobileFillZoom:b}){const[N,T]=o.useState(null),y=o.useRef(null),C=o.useRef(null),k=o.useRef(null),v=o.useRef(!1),g=o.useRef(null),D=o.useRef(0),M=o.useRef(null),I=o.useRef(1),P=o.useRef({x:0,y:0}),K=o.useRef(!1),V=o.useRef(n),L=o.useRef(w),R=30,G=550,B=18,E=60,W=400,J=12,be=()=>{if(y.current)return;const ye={nx:.5,ny:.5};y.current=ye,T(ye)};return o.useEffect(()=>{V.current=n,n==="mouse"&&be()},[n]),o.useEffect(()=>{L.current=w},[w]),o.useEffect(()=>{const ye=e.current;if(!ye)return;const ge=te=>{if(!r.current)return null;const fe=r.current.getBoundingClientRect();return!fe.width||!fe.height?null:{nx:Math.max(0,Math.min(1,(te.clientX-fe.left)/fe.width)),ny:Math.max(0,Math.min(1,(te.clientY-fe.top)/fe.height))}},ve=(te,fe)=>{if(!r.current)return{dnx:0,dny:0};const ne=r.current,xe=ne.getBoundingClientRect(),re=ne.naturalWidth||xe.width,le=ne.naturalHeight||xe.height,oe=re/le,Y=xe.width/xe.height;let X,ae;return oe>Y?(X=xe.width,ae=xe.width/oe):(ae=xe.height,X=xe.height*oe),{dnx:te/X,dny:fe/ae}},z=(te,fe,ne)=>{if(ne<=1.05)return;const xe=-(te-.5)*100,re=-(fe-.5)*100,le=x(xe,re,ne);(Math.abs(le.x-l.current)>.1||Math.abs(le.y-u.current)>.1)&&(f(le.x),d(le.y),l.current=le.x,u.current=le.y)},F=te=>{const fe=t.current;if(fe&&te.target instanceof Node&&fe.contains(te.target))te.preventDefault();else return;if(te.touches.length===1){const ne=te.touches[0];C.current={x:ne.clientX,y:ne.clientY,time:Date.now()},k.current={x:ne.clientX,y:ne.clientY},K.current||(v.current=!1),g.current=setTimeout(()=>{if(!v.current&&!K.current)if(v.current=!0,V.current==="mouse"){const xe=y.current||{nx:.5,ny:.5};S("Right Click"),p(xe.nx,xe.ny,"right"),L.current("input_click",{...xe,button:"right"}).catch(()=>{})}else{const xe=ge(ne);xe&&(S("Right Click"),p(xe.nx,xe.ny,"right"),L.current("input_click",{...xe,button:"right"}).catch(()=>{}))}},500);return}if(te.touches.length===2){g.current&&clearTimeout(g.current),v.current=!0,K.current=!0;const ne=te.touches[1].clientX-te.touches[0].clientX,xe=te.touches[1].clientY-te.touches[0].clientY;M.current=Math.sqrt(ne*ne+xe*xe),I.current=c.current,P.current={x:(te.touches[0].clientX+te.touches[1].clientX)/2,y:(te.touches[0].clientY+te.touches[1].clientY)/2}}},Q=te=>{const fe=t.current;if(fe&&te.target instanceof Node&&fe.contains(te.target)&&te.preventDefault(),te.touches.length===1&&k.current){const ne=te.touches[0],xe=ne.clientX-k.current.x,re=ne.clientY-k.current.y;if(!v.current&&C.current){const le=ne.clientX-C.current.x,oe=ne.clientY-C.current.y;Math.sqrt(le*le+oe*oe)>8&&(v.current=!0,g.current&&clearTimeout(g.current))}if(v.current)if(V.current==="mouse"){const le=ve(xe,re),oe=y.current||{nx:.5,ny:.5},Y=Math.max(0,Math.min(1,oe.nx+le.dnx)),X=Math.max(0,Math.min(1,oe.ny+le.dny));y.current={nx:Y,ny:X},T({nx:Y,ny:X}),S(`Cursor: ${Math.round(Y*100)}%, ${Math.round(X*100)}%`),z(Y,X,c.current);const ae=Date.now();ae-m.current>=30&&(m.current=ae,L.current("input_mouseMoved",{nx:Y,ny:X}).catch(()=>{}))}else if(c.current>1){const le=t.current;if(le){const oe=le.clientWidth,Y=le.clientHeight,X=l.current+xe/oe*100,ae=u.current+re/Y*100,A=x(X,ae,c.current);f(A.x),d(A.y),l.current=A.x,u.current=A.y}}else{const le=ge(ne);if(le){const oe=Date.now();oe-m.current>=40&&(m.current=oe,S("Scroll"),L.current("input_wheel",{nx:le.nx,ny:le.ny,deltaX:Math.round(-xe*2.5),deltaY:Math.round(-re*2.5)}).catch(()=>{}))}}k.current={x:ne.clientX,y:ne.clientY};return}if(te.touches.length===2&&M.current!==null){const ne=te.touches[1].clientX-te.touches[0].clientX,xe=te.touches[1].clientY-te.touches[0].clientY,le=Math.sqrt(ne*ne+xe*xe)/M.current,oe=(te.touches[0].clientX+te.touches[1].clientX)/2,Y=(te.touches[0].clientY+te.touches[1].clientY)/2,X=oe-P.current.x,ae=Y-P.current.y,A=Math.abs(le-1)>.03;if(V.current==="mouse"){if(A){const H=Math.max(i,Math.min(5,I.current*le));h(H),c.current=H}else if(Math.abs(X)>2||Math.abs(ae)>2){const H=y.current||{nx:.5,ny:.5},ce=Date.now();ce-m.current>=30&&(m.current=ce,S("Scroll"),L.current("input_wheel",{nx:H.nx,ny:H.ny,deltaX:Math.round(-X*3),deltaY:Math.round(-ae*3)}).catch(()=>{}))}}else{const H=Math.max(i,Math.min(5,I.current*le));h(H),c.current=H;const ce=t.current;if(ce&&H>1){const me=ce.clientWidth,we=ce.clientHeight,_e=l.current+X/me*100,Ae=u.current+ae/we*100,Ke=x(_e,Ae,H);f(Ke.x),d(Ke.y),l.current=Ke.x,u.current=Ke.y}}P.current={x:oe,y:Y}}},ue=te=>{var fe;if(g.current&&clearTimeout(g.current),M.current=null,te.touches.length===1&&K.current){const ne=te.touches[0];C.current={x:ne.clientX,y:ne.clientY,time:Date.now()},k.current={x:ne.clientX,y:ne.clientY},v.current=!0;return}if(te.touches.length===0){if(K.current){K.current=!1,v.current=!1;return}if(te.changedTouches.length===1){const ne=te.changedTouches[0],xe=Date.now(),re=xe-(((fe=C.current)==null?void 0:fe.time)||0),le=C.current?ne.clientX-C.current.x:0,oe=C.current?ne.clientY-C.current.y:0,Y=Math.sqrt(le*le+oe*oe);if(V.current==="mouse"){if(re<R||re>G||Y>B){v.current=!1;return}const X=y.current||ge(ne);X&&(S(`Click: ${Math.round(X.nx*100)}%, ${Math.round(X.ny*100)}%`),p(X.nx,X.ny,"left"),L.current("input_click",{...X}).catch(()=>{}))}else{if(v.current){v.current=!1;return}if(re<E||re>W||Y>J){v.current=!1;return}const X=ge(ne);if(!X)return;xe-D.current<300?(S("Double tap"),p(X.nx,X.ny,"double"),L.current("input_click",{...X,clickCount:2}).catch(()=>{}),D.current=0):(S(`Tap: ${Math.round(X.nx*100)}%, ${Math.round(X.ny*100)}%`),p(X.nx,X.ny,"left"),L.current("input_click",{...X}).catch(()=>{}),D.current=xe)}}v.current=!1}};return ye.addEventListener("touchstart",F,{passive:!1}),ye.addEventListener("touchmove",Q,{passive:!1}),ye.addEventListener("touchend",ue,{passive:!1}),()=>{ye.removeEventListener("touchstart",F),ye.removeEventListener("touchmove",Q),ye.removeEventListener("touchend",ue),g.current&&clearTimeout(g.current)}},[e,t,r,i,c,l,u,f,d,h,m,S,p,x]),{cursorPos:N,cursorPosRef:y,handleToggleInputMode:()=>{a(ye=>{const ge=ye==="touch"?"mouse":"touch";return ge==="mouse"&&be(),ge})},handleZoomReset:()=>{const ye=j?b:1;h(ye),c.current=ye,f(0),d(0),l.current=0,u.current=0}}}function Di({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),u=o.useRef(null),[f,d]=o.useState(null),[h,m]=o.useState(""),[,w]=o.useState(!1),[S,p]=o.useState([]),x=o.useRef(0),[j,b]=o.useState(!1),[N,T]=o.useState(!1),y=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[C,k]=o.useState(y?"mouse":"touch"),[v,g]=o.useState(1),D=o.useRef(!1),[M,I]=o.useState(1),[P,K]=o.useState(0),[V,L]=o.useState(0);tr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:C,zoom:M,panX:P,panY:V,isMenuOpen:j,isImeOpen:N});const R=o.useRef(0),G=o.useRef(M),B=o.useRef(P),E=o.useRef(V);o.useEffect(()=>{G.current=M},[M]),o.useEffect(()=>{B.current=P},[P]),o.useEffect(()=>{E.current=V},[V]),o.useEffect(()=>{var re;(re=c.current)==null||re.focus()},[]);const W=r==="connected",J=n,be=W?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",he=W?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!y||D.current||!J)return;const re=u.current,le=l.current;if(!re||!le)return;const oe=()=>{const Y=le.clientWidth,X=le.clientHeight,ae=re.naturalWidth,A=re.naturalHeight;if(!ae||!A||!Y||!X)return;const H=Math.min(Y/ae,X/A),me=Math.max(Y/ae,X/A)/H;me>1.01&&(g(me),I(me),G.current=me),D.current=!0};re.complete&&re.naturalWidth?oe():re.addEventListener("load",oe,{once:!0})},[J,y]);const de=.5;o.useEffect(()=>{M<=de&&(K(0),L(0))},[M,de]);const ye=(re,le,oe)=>{if(oe<=de)return{x:0,y:0};const Y=(oe-1)/(2*oe)*100,X=(oe-1)/(2*oe)*100;return{x:Math.max(-Y,Math.min(Y,re)),y:Math.max(-X,Math.min(X,le))}},ge=(re,le)=>{if(!u.current)return null;const oe=u.current.getBoundingClientRect();return!oe.width||!oe.height?null:{nx:Math.max(0,Math.min(1,(re-oe.left)/oe.width)),ny:Math.max(0,Math.min(1,(le-oe.top)/oe.height))}},ve=(re,le,oe)=>{const Y=l.current;if(!Y)return;const X=Y.getBoundingClientRect(),ae=++x.current;p(A=>[...A,{id:ae,x:re-X.left,y:le-X.top,type:oe}]),setTimeout(()=>p(A=>A.filter(H=>H.id!==ae)),600)},z=(re,le,oe)=>{const Y=u.current,X=l.current;if(!Y||!X)return;const ae=Y.getBoundingClientRect(),A=X.getBoundingClientRect(),H=Y.naturalWidth||ae.width,ce=Y.naturalHeight||ae.height,me=H/ce,we=ae.width/ae.height;let _e,Ae,Ke,Fe;me>we?(_e=ae.width,Ae=ae.width/me,Ke=0,Fe=(ae.height-Ae)/2):(Ae=ae.height,_e=ae.height*me,Ke=(ae.width-_e)/2,Fe=0);const ze=ae.left-A.left+Ke+_e*re,ot=ae.top-A.top+Fe+Ae*le,it=++x.current;p(dt=>[...dt,{id:it,x:ze,y:ot,type:oe}]),setTimeout(()=>p(dt=>dt.filter(ut=>ut.id!==it)),600)},F=async re=>{var oe;const le=ge(re.clientX,re.clientY);if(le){d(`Click: ${Math.round(le.nx*100)}%, ${Math.round(le.ny*100)}%`),ve(re.clientX,re.clientY,"left"),(oe=c.current)==null||oe.focus();try{const Y=await e("input_click",{nx:le.nx,ny:le.ny});Y!=null&&Y.success||t(`❌ Click failed: ${Y==null?void 0:Y.error}`)}catch(Y){t(`❌ Click error: ${Y.message||Y}`)}}},Q=async(re,le,oe,Y=0)=>{try{await e("input_key",{type:oe?"char":"keyDown",key:re,code:le,text:oe?re:void 0,unmodifiedText:oe?re:void 0,modifiers:Y})}catch(X){t(`❌ Key error: ${X.message||X}`)}},ue=async re=>{if(re.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(re.key)&&re.preventDefault();let oe=0;re.altKey&&(oe|=1),re.ctrlKey&&(oe|=2),re.metaKey&&(oe|=4),re.shiftKey&&(oe|=8),d(`Key: ${re.key}`),await Q(re.key,re.code,re.key.length===1,oe)},te=async re=>{if(re.key==="Enter"){if(re.nativeEvent.isComposing)return;if(h){const le=h;m(""),d(`IME Sent: ${le}`);try{const oe=await e("input_type",{text:le});oe!=null&&oe.success||t(`❌ IME error: ${oe==null?void 0:oe.error}`)}catch(oe){t(`❌ IME error: ${oe.message}`)}}else d("Key: Enter"),await Q("Enter","Enter",!1)}};o.useEffect(()=>{const re=c.current;if(!re)return;const le=oe=>{var Y;if((Y=u.current)!=null&&Y.contains(oe.target)){oe.preventDefault();const X=Date.now();if(X-R.current<40)return;R.current=X;const ae=ge(oe.clientX,oe.clientY);if(!ae)return;d(`Scroll: ${Math.round(oe.deltaY)}`),e("input_wheel",{nx:ae.nx,ny:ae.ny,deltaX:Math.round(oe.deltaX),deltaY:Math.round(oe.deltaY)}).catch(()=>{})}};return re.addEventListener("wheel",le,{passive:!1}),()=>re.removeEventListener("wheel",le)},[e]);const{cursorPos:fe,handleToggleInputMode:ne,handleZoomReset:xe}=uu({containerRef:c,viewportRef:l,imgRef:u,inputMode:C,setInputMode:k,minZoom:de,zoomRef:G,panXRef:B,panYRef:E,setPanX:K,setPanY:L,setZoom:I,lastWheelTimeRef:R,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:z,clampPan:ye,isMobile:y,mobileFillZoom:v});return s.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ue,onContextMenu:re=>re.preventDefault(),onFocus:()=>w(!0),onBlur:()=>w(!1),tabIndex:0,children:[s.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[J?s.jsx("img",{ref:u,src:J,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${M}) translate(${P}%, ${V}%)`,transformOrigin:"center center",cursor:C==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:F,onContextMenu:re=>re.preventDefault(),onDragStart:re=>re.preventDefault()}):s.jsx(lu,{waitingLabel:be,waitingHint:he,transportType:i}),C==="mouse"&&J&&s.jsx(iu,{cursorPos:fe,viewportRef:l,imgRef:u}),S.map(re=>{const oe={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[re.type];return s.jsxs("div",{style:{position:"absolute",left:re.x,top:re.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${oe}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),s.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${oe}, 0.9)`,boxShadow:`0 0 12px rgba(${oe}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},re.id)})]}),s.jsx(cu,{inputMode:C,onToggleInputMode:ne,isImeOpen:N,setIsImeOpen:T,isMenuOpen:j,setIsMenuOpen:b,imeText:h,setImeText:m,handleImeSubmit:te,isConnActive:W,zoom:M,isMobile:y,mobileFillZoom:v,onZoomOut:()=>I(re=>Math.max(.5,re-.25)),onZoomReset:xe,onZoomIn:()=>I(re=>Math.min(5,re+.25)),transportType:i,screenshotUsage:a,lastActionStatus:f}),s.jsx("style",{children:`
|
|
2
|
+
var ed=Object.defineProperty;var td=(e,t,r)=>t in e?ed(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ge=(e,t,r)=>td(e,typeof t!="symbol"?t+"":t,r);import{r as o,j as s,M as ma,a as fa,b as bi,c as gi,u as As,R as kt,d as qs,t as sd,e as rd,D as nd,f as Un,g as zn,h as pa,i as ad,k as od,B as id,l as cd,m as Yt,N as Vn,n as ld}from"./vendor-BRZ4K-AC.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const 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 dd(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(a),r.length>t&&r.splice(0,r.length-t),a},list(n={}){const a=Math.max(1,Math.floor(n.limit||100));return r.filter(i=>!n.interactionId||i.interactionId===n.interactionId).filter(i=>!n.topic||i.topic===n.topic).filter(i=>!n.kind||i.kind===n.kind).slice(-a).map(i=>({...i,payload:i.payload?{...i.payload}:{}}))},clear(){r.splice(0,r.length)}}}const ks=dd();function oo(e){const t={};for(const r of e)r.transport&&(t[r.transport]=(t[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:t}}function ud(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function md(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function yi(e,t){var f;if(!e)return t??null;if(!t)return e??null;const r=md(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:void 0,a=e.status==="waiting_approval"||Array.isArray((f=e.activeModal)==null?void 0:f.buttons)&&e.activeModal.buttons.length>0,i=r&&a&&(n==null?void 0:n.length)===0&&Array.isArray(t.messages)&&t.messages.length>0,c=r?i?t.messages:n??[]:t.messages,l=e.activeModal||(e.status==="waiting_approval"?t.activeModal:null),d={...t,...e,activeModal:l,inputContent:e.inputContent??t.inputContent};return r?{...d,messages:c}:d}function Ws(e,t){const r=ud(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(t==null?void 0:t.parentSessionId)??null,providerSessionId:e.providerSessionId??(t==null?void 0:t.providerSessionId),providerName:r??(t==null?void 0:t.providerName)??(t==null?void 0:t.cliName)??(t==null?void 0:t.type)??e.providerName??e.providerType,title:e.title??(t==null?void 0:t.title)??r??(t==null?void 0:t.providerName)??e.providerName??e.providerType,workspace:e.workspace??(t==null?void 0:t.workspace)??null,mode:e.mode??(t==null?void 0:t.mode),capabilities:e.capabilities??(t==null?void 0:t.sessionCapabilities)??(t==null?void 0:t.capabilities)??[],cdpConnected:e.cdpConnected??(t==null?void 0:t.cdpConnected),activeChat:yi(e.activeChat,t==null?void 0:t.activeChat),controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel)}}function vi(e,t,r){if(!(t!=null&&t.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const n=t.map(a=>{const i=e.find(c=>c.id===a.id);return i?Ws(a,i):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(t.map(i=>i.id));for(const i of e)a.has(i.id)||n.push(i)}return n}function io(e){return!!e&&typeof e=="object"&&"text"in e}function ha(e,t){const r=(t==null?void 0:t.joiner)??" ",n=(t==null?void 0:t.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(i=>typeof i=="string"?i:io(i)?String(i.text||""):"").join(r):io(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Ss(e){return ha(e,{normalizeWhitespace:!0})}const wi=o.createContext({ides:[],updateRouteChats:()=>{},initialLoaded:!1,toasts:[],setToasts:()=>{},wsStatus:"connected",isConnected:!0,connectionStates:{},connectionTransports:{},showReconnected:!1,userName:void 0,setUserName:()=>{},isP2PActive:!1,p2pStates:{},userRole:void 0}),ji=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function co(e){var r,n;let t=0;return e.activeChat!==void 0&&(t+=4),(r=e.childSessions)!=null&&r.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(n=e.agents)!=null&&n.length&&(t+=1),t}function ki(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,i=t.serverVersion??e.serverVersion??r.serverVersion,c=t.versionMismatch===!0||e.versionMismatch===!0,l=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),i&&(n.serverVersion=i),d&&(n.versionUpdateReason=d),a&&i&&a===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||c&&a&&i&&a!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function fd(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function dn(e){if(!e||typeof e!="object")return"";const t=e,r=fd(Ss(t.content).slice(0,512));return[String(t.id||""),String(t._localId||""),String(t._turnKey||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),r].join(":")}function pd(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=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 Gn(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function qn(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(Gn(e)&&Gn(t)){const c=e.messages;Array.isArray(c)&&c===t.messages&&r.add(c)}if(Array.isArray(e)&&Array.isArray(t)){const c=Math.min(e.length,t.length);for(let l=0;l<c;l+=1)qn(e[l],t[l],r);return}const n=e,a=t,i=new Set([...Object.keys(n),...Object.keys(a)]);for(const c of i)c!=="messages"&&qn(n[c],a[c],r)}function Hs(e,t){return Array.isArray(e)?e.map(r=>Hs(r,t)):!e||typeof e!="object"?e:Gn(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?pd(a,t):Hs(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Hs(n,t)]))}function hd(e,t){try{const r=new WeakSet;return qn(e,t,r),JSON.stringify(Hs(e,r))===JSON.stringify(Hs(t,r))}catch{return!1}}function Yn(e,t,r){return hd(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Si(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function xd(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function lo(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,i=vi(e.childSessions,t.childSessions,{preserveMissing:n}),c=yi(t.activeChat,e.activeChat);return ki(e,t,{...e,...t,chats:a,childSessions:i,activeChat:c,_lastUpdate:r})}function bd(e,t,r){var a,i;const n={};t.status&&t.status!==e.status&&(n.status=t.status),t.cdpConnected!==void 0&&(n.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(n.childSessions=vi(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((i=e.chats)!=null&&i.length)&&(n.chats=t.chats);for(const c of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion"])xd(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function gd(e,t,r,n){const a=bd(e,t,n),i=Object.keys(a).length>0?ki(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return Yn(e,i,r)}function yd(e){const t=new Set(e.map(a=>a.id)),r=new Set,n=new Set;for(const a of e){const i=Si(a);i&&r.add(i),i&&a.type!=="adhdev-daemon"&&n.add(i)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n}}function vd(e,t,r,n,a,i){return!a.has(t)||!i.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function wd(e,t,r,n){return!!(r.has(t)&&e.transport&&!n.has(t))}function jd(e,t,r){var f,u;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(x=>({...x,_lastUpdate:n}));const i=new Map;for(const x of t)i.set(x.id,x);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:d}=yd(e);for(const x of e){const m=i.get(x.id);if(!m){i.set(x.id,{...x,_lastUpdate:n});continue}const v=co(x),S=co(m),p=Si(x),h=!a.has(p);if(v>S){const N=lo(m,x,n,h);i.set(x.id,Yn(m,N,n));continue}if(v<S){i.set(x.id,gd(m,x,n,h));continue}const j=x.timestamp||n,b=m._lastUpdate||m.timestamp||0;if(j>=b){const N=lo(m,x,n,h);i.set(x.id,Yn(m,N,n));continue}(f=x.chats)!=null&&f.length&&!((u=m.chats)!=null&&u.length)&&i.set(x.id,{...m,chats:x.chats})}for(const[x,m]of i){const v=m.daemonId||x.split(":")[0];if(!l.has(v))continue;if(a.has(v)&&!c.has(x)){i.delete(x);continue}const S=n-(m._lastUpdate||m.timestamp||0);vd(m,v,S,c,a,d)&&i.delete(x)}for(const[x,m]of i){const v=m.daemonId||x.split(":")[0];if(wd(m,v,l,d))continue;n-(m._lastUpdate||m.timestamp||0)>3e5&&m.status!=="online"&&i.delete(x)}return Array.from(i.values())}function kd(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Sd({children:e,connectionOverrides:t}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[d,f]=o.useState(void 0),u=o.useRef(r);o.useEffect(()=>{u.current=r},[r]);const x=o.useCallback((j,b)=>{n(N=>{let T=!1;const y=N.map(C=>C.id!==j||C.chats===b?C:(T=!0,{...C,chats:b}));return T?y:N})},[]),m=o.useCallback((j,b)=>{n(N=>{const T=N.length===0?j:jd(j,N,b),y=!kd(N,T);return y&&ks.record({kind:"dashboard.entries_applied",payload:{incoming:oo(j),next:oo(T)}}),y?T:N})},[]),v=o.useCallback(()=>i(!0),[]),S=o.useMemo(()=>({injectEntries:m,markLoaded:v,getIdes:()=>u.current}),[m,v]),p=t,h=o.useMemo(()=>({ides:r,updateRouteChats:x,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(p==null?void 0:p.wsStatus)??"connected",isConnected:(p==null?void 0:p.isConnected)??!0,connectionStates:(p==null?void 0:p.connectionStates)??{},connectionTransports:(p==null?void 0:p.connectionTransports)??{},showReconnected:(p==null?void 0:p.showReconnected)??!1,retryConnection:p==null?void 0:p.retryConnection,retryServerConnection:p==null?void 0:p.retryServerConnection,connectionLoginUrl:p==null?void 0:p.connectionLoginUrl,isP2PActive:(p==null?void 0:p.isP2PActive)??!1,p2pStates:(p==null?void 0:p.p2pStates)??{},userRole:p==null?void 0:p.userRole,userName:d,setUserName:f}),[r,x,a,c,p==null?void 0:p.wsStatus,p==null?void 0:p.isConnected,p==null?void 0:p.connectionStates,p==null?void 0:p.connectionTransports,p==null?void 0:p.showReconnected,p==null?void 0:p.retryConnection,p==null?void 0:p.retryServerConnection,p==null?void 0:p.connectionLoginUrl,p==null?void 0:p.isP2PActive,p==null?void 0:p.p2pStates,p==null?void 0:p.userRole,d]);return s.jsx(ji.Provider,{value:S,children:s.jsx(wi.Provider,{value:h,children:e})})}function cs(){return o.useContext(wi)}function Ys(){return o.useContext(ji)}function Ni(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function i(l){const d=r==null?void 0:r(),f=a(l),u=l.startsWith("http")?new URL(f):new URL(f,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!l.startsWith("http")&&!t?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function c(l,d={}){const f={"Content-Type":"application/json",...d.headers||{}},u=r==null?void 0:r();u&&(f.Authorization=`Bearer ${u}`);const x=a(l),m=new AbortController,v=setTimeout(()=>m.abort(),15e3);try{const S=await fetch(x,{...d,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(v)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,d,f={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:d,payload:f})}),execTerminal:(l,d,f)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:f})}),sendAgentMessage:(l,d,f)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:f})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,d,f)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:f?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,d,f={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:f})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Nd=Ni({baseUrl:"http://localhost:3847"}),Cd=o.createContext(Nd);function Id({client:e,children:t}){return s.jsx(Cd.Provider,{value:e,children:t})}const Md={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Ci=o.createContext(Md);function Ad({value:e,children:t}){return s.jsx(Ci.Provider,{value:e,children:t})}function wt(){return o.useContext(Ci)}function Td(e){let t=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)t^=n.charCodeAt(a),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function Ld(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Ii(e){return e?Td([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Ld(e.content)]):""}const Ee={size:18};function Mi({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function xa({size:e=Ee.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function ls({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function Ai({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Rd({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Pd({size:e=Ee.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function Ti({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function _d({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Yr({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Li({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Dd({size:e=Ee.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Ut({size:e=Ee.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Nt({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function ba({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("polyline",{points:"14 2 14 8 20 8"}),s.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),s.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Ed({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Ns({size:e=Ee.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function sr({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function Xs({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Js({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function Ri({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Pi({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),s.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function _i({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function $d({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function ga({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Bd({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function ya({size:e=Ee.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Di({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function vt({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Kd({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),s.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),s.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),s.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Od({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Wd({size:e=Ee.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function Hd({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function Xr({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Fd({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"5"}),s.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),s.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),s.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),s.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),s.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),s.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),s.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),s.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function Ud({size:e=Ee.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function zd({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Vd({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Gd({size:e=Ee.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function qd({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function Yd({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function Xd({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function Jd({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Qd({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function Zd({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function eu({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const Ei=200,uo=650,un=new Map;function mo(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function tu(e){if(!Array.isArray(e)||e.length===0)return"0:empty";const t=e[e.length-1];return`${e.length}:${Ii(t)}`}function su(e,t){return!e&&t}function fo(e,t=Ei){return!!e&&e.fromBottom>=t}function ru({hasSelection:e,userScrolledUp:t}){return!(e||t)}function nu({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function po(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function $i(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function au(e,t,r){return Number(e.receivedAt||r[Kr(e,t)]||0)||0}function Bi(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function ou(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function ur(e,t){if(!e)return t;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||t}catch{return e.split(/[\\/]/).filter(Boolean).pop()||t}}function 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 ho(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Bi(e)?s.jsx(ma,{remarkPlugins:[fa,bi,gi],children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function mr({parts:e,renderAsPreformatted:t}){return s.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return s.jsx("div",{children:ho(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=mn(r);return a?s.jsx("img",{src:a,alt:ur(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=mn(r);return a?s.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=mn(r);return a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:ur(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||ur(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=ur(r.resource.uri,"resource");if(r.resource.text)return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[s.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),ho(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return s.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function Kr(e,t){const r=e,n=ha(e.content,{joiner:`
|
|
3
|
+
`});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${t}`].filter(Boolean).join("|")}const iu=o.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(ma,{remarkPlugins:[fa],children:t.text}),s.jsx("span",{className:"action-time",children:$i(t.timestamp)})]})},(e,t)=>e.log===t.log),cu=o.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var C,k,w;const d=(t.role||"").toLowerCase(),f=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),x=ou(t.content)?t.content:null,m=!!(x!=null&&x.some(g=>g.type!=="text")),v=ha(t.content,{joiner:`
|
|
4
|
+
`});if(u==="thought"){const g=typeof((C=t.meta)==null?void 0:C.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(Wd,{size:13}),s.jsx("span",{children:g})]}),s.jsx("div",{className:"chat-msg-body",children:v})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),m&&x?s.jsx("div",{className:"tool-text w-full",children:s.jsx(mr,{parts:x,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:v})]});if(u==="terminal"){const g=(k=t.meta)!=null&&k.isRunning?"⏳":"✅",D=typeof((w=t.meta)==null?void 0:w.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:g}),s.jsx("span",{children:D})]}),m&&x?s.jsx("div",{className:"chat-msg-body",children:s.jsx(mr,{parts:x,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:v})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:m&&x?s.jsx(mr,{parts:x,renderAsPreformatted:!1}):v.slice(0,100)});const S=t.meta,h=(typeof(S==null?void 0:S.renderMode)=="string"?S.renderMode.trim():"")==="preformatted",j=v,b=!1,N=j,T=h,y=!T&&Bi(N);return s.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${f?"self-end":"self-start"}`,children:(j||m||f)&&s.jsxs("div",{className:`chat-bubble ${f?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${j||m?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:f?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:$i(r)})]}),(j||m)&&s.jsx("div",{className:"chat-markdown",children:m&&x?s.jsx(mr,{parts:x,renderAsPreformatted:T}):T?s.jsx("pre",{className:"chat-preformatted",children:N}):y?s.jsx(ma,{remarkPlugins:[fa,bi,gi],children:N}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:N})}),b]})})},(e,t)=>e.message===t.message&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),lu=o.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:d={},emptyState:f,onLoadMore:u,isLoadingMore:x,hasMoreHistory:m,hiddenLiveCount:v=0,loadError:S,scrollToBottomRequestNonce:p,isVisible:h=!0},j){const b=o.useRef(null),N=o.useRef(null),T=o.useRef(null),y=o.useRef(0),C=o.useRef(""),k=o.useRef(!1),w=o.useRef(null),g=o.useRef(!1),D=o.useRef(null),A=o.useRef(!1),[I,P]=o.useState(new Set),O=o.useRef(!1),V=o.useRef(!1),L=o.useRef(h),R=()=>{const F=b.current;return F?F.scrollHeight-F.scrollTop-F.clientHeight<Ei:!0},G=o.useCallback((F="auto")=>{const Q=b.current;Q&&Q.scrollTo({top:Q.scrollHeight,behavior:F})},[]),K=o.useCallback(()=>{var fe;const F=b.current,Q=(fe=window.getSelection)==null?void 0:fe.call(window);if(!F||!Q||Q.rangeCount===0||Q.isCollapsed){A.current=!1;return}const ue=Q.anchorNode,te=Q.focusNode;A.current=!!(ue&&te&&F.contains(ue)&&F.contains(te))},[]),E=tu(t),W=o.useCallback(()=>{const F=b.current;!F||!l||un.set(l,{top:F.scrollTop,fromBottom:Math.max(0,F.scrollHeight-F.scrollTop-F.clientHeight),messageFingerprint:E})},[l,E]),J=o.useCallback((F="auto")=>{w.current!=null&&cancelAnimationFrame(w.current),w.current=requestAnimationFrame(()=>{w.current=null,G(F)})},[G]),be=o.useCallback(()=>{O.current=!1,g.current=!0,V.current=!0,D.current!=null&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>{g.current=!1,D.current=null},uo)},[]);o.useEffect(()=>{const F=!k.current,Q=C.current!==l;if(C.current=l,F||Q){if(k.current=!0,O.current=!1,g.current=!0,!A.current){const ue=l?un.get(l):null;ue&&mo(ue,E)?requestAnimationFrame(()=>{const te=b.current;te&&(po(te,ue),O.current=fo(ue),V.current=!0)}):J("auto")}y.current=t.length;return}t.length>y.current,ru({hasSelection:A.current,userScrolledUp:O.current})&&J("auto"),y.current=t.length},[E,l,c,t.length,J]),o.useEffect(()=>{p&&(be(),A.current||J("auto"))},[be,J,p]),o.useEffect(()=>{const F=L.current;L.current=h,su(F,h)&&(be(),A.current||J("auto"))},[h,be,J]),o.useEffect(()=>()=>{W(),w.current!=null&&cancelAnimationFrame(w.current),D.current!=null&&window.clearTimeout(D.current)},[W]),o.useEffect(()=>{const F=N.current,Q=b.current;if(!F||!Q)return;const ue=()=>{D.current!=null&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>{g.current=!1,D.current=null},uo)},te=new ResizeObserver(()=>{const fe=g.current;nu({hasSelection:A.current,userScrolledUp:O.current,contextAutoScrollActive:fe})&&(J("auto"),fe&&ue())});return te.observe(F),Q!==F&&te.observe(Q),()=>{te.disconnect(),D.current!=null&&(window.clearTimeout(D.current),D.current=null)}},[J,l]),o.useImperativeHandle(j,()=>({scrollToBottom:(F="smooth")=>{G(F)}}),[G]),o.useEffect(()=>{const F=b.current;if(!F)return;let Q;const ue=()=>{clearTimeout(Q),Q=setTimeout(()=>{O.current=!R(),W()},50)};return F.addEventListener("scroll",ue,{passive:!0}),()=>{F.removeEventListener("scroll",ue),clearTimeout(Q)}},[W]),o.useEffect(()=>(document.addEventListener("selectionchange",K),()=>document.removeEventListener("selectionchange",K)),[K]);const xe=o.useRef(0),de=o.useRef(!1);o.useEffect(()=>{const F=b.current;if(!F||!de.current||xe.current===0)return;const Q=F.scrollHeight-xe.current;Q>0&&(F.scrollTop=Q),W(),xe.current=0,de.current=!1},[t.length,W]),o.useEffect(()=>{if(V.current||!l)return;const F=un.get(l),Q=b.current;if(!(!F||!Q)){if(!mo(F,E)){G("auto"),V.current=!0;return}po(Q,F),O.current=fo(F),V.current=!0}},[l,E,t.length,G]);const ye=()=>{const F=b.current;F&&(xe.current=F.scrollHeight),de.current=!0,u==null||u()},ge=o.useMemo(()=>{const F=t.map((fe,re)=>({type:"message",data:fe,index:re,ts:au(fe,re,d)}));if(!r||r.length===0)return F;const Q=[...r].sort((fe,re)=>fe.timestamp-re.timestamp).map((fe,re)=>({type:"action",data:fe,index:re,ts:fe.timestamp})),ue=[];let te=0;for(const fe of F){for(;te<Q.length&&fe.ts>0&&Q[te].ts<fe.ts;)ue.push(Q[te++]);ue.push(fe)}for(;te<Q.length;)ue.push(Q[te++]);return ue},[t,r,d]),ve=v>0||!!m,z=v>0?`↑ Show ${Math.min(v,80)} earlier messages${v>80?` (${v} hidden)`:""}`:S?`↻ ${S}`:"↑ Load older messages";return s.jsx("div",{ref:b,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:N,className:"chat-container-content",children:[x&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),ve&&!x&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{onClick:ye,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${S&&v===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})}),ge.length===0&&!ve&&(f||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ge.map(F=>{if(F.type==="action"){const oe=F.data;return s.jsx(iu,{log:oe},`action-${F.index}`)}const Q=F.data,ue=F.index,te=Kr(Q,ue),fe=Q.receivedAt||d[te],re=`${l}-${te}`,pe=I.has(re);return s.jsx(cu,{message:Q,receivedAt:fe,agentName:n,userName:a,isCliMode:i,isTextExpanded:pe,onToggleTextExpanded:()=>P(oe=>{const le=new Set(oe);return pe?le.delete(re):le.add(re),le})},`msg-${te}`)}),c&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),s.jsx("div",{className:"min-h-10",ref:T})]})})}),du=o.memo(lu,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible),uu="modulepreload",mu=function(e){return"/"+e},xo={},fu=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=mu(d),d in xo)return;xo[d]=!0;const f=d.endsWith(".css"),u=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const x=document.createElement("link");if(x.rel=f?"stylesheet":uu,f||(x.as="script"),x.crossOrigin="",x.href=d,l&&x.setAttribute("nonce",l),document.head.appendChild(x),f)return new Promise((m,v)=>{x.addEventListener("load",m),x.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};let bo=!1;const Ki=o.forwardRef(({onInput:e,onViewportMetrics:t,fontSize:r=13,readOnly:n=!1,sizingMode:a="measured"},i)=>{const c=o.useRef(null),[l,d]=o.useState(null),f=o.useRef([]),u=o.useRef(!1),x=o.useRef(!1),m=o.useRef(!1),v=()=>{const S=c.current;if(S){u.current&&(S.clear(),u.current=!1);for(const p of f.current)S.write(p);f.current=[],x.current&&(S.fit(),x.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=[],u.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(f.current=[],u.current=!0)},resize:(S,p)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(S,p)},fit:()=>{c.current?c.current.fit():x.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():m.current=!0}}),[]),o.useEffect(()=>{l&&v()},[l]),o.useEffect(()=>{let S=!1;return fu(()=>import("./terminal-Bv6gUGuY.js"),__vite__mapDeps([0,1,2])).then(p=>{bo||(bo=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),S||d(()=>p.GhosttyTerminalView)}).catch(p=>{console.error("[CliTerminal] failed to load terminal renderer",p)}),()=>{S=!0}},[]),l?s.jsx(l,{ref:c,onInput:e,onViewportMetrics:t,fontSize:r,readOnly:n,sizingMode:a,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Ki.displayName="CliTerminal";function fr({label:e,value:t,sub:r,icon:n}){return s.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:n}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),r&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function go({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:i=!1}){const c=t>0?Math.min(Math.round(e/t*100),100):0,l=c>85?"#ef4444":c>60?"var(--status-warning)":n;return i?s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),s.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[c,"%"]})]}),s.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${c}%`,background:l}})})]}):s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-1.5",children:[s.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),s.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[c,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${c}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function pu({cursorPos:e,viewportRef:t,imgRef:r}){var b;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(b=t.current)==null?void 0:b.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,d=c/l,f=a.width/a.height;let u,x,m,v;d>f?(u=a.width,x=a.width/d,m=0,v=(a.height-x)/2):(x=a.height,u=a.height*d,m=(a.width-u)/2,v=0);const S=a.left-i.left+m+u*e.nx,p=a.top-i.top+v+x*e.ny,h=Math.max(8,Math.min(i.width-8,S)),j=Math.max(8,Math.min(i.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:h-8,top:j-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function hu({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:d,isConnActive:f,zoom:u,isMobile:x,mobileFillZoom:m,onZoomOut:v,onZoomReset:S,onZoomIn:p,transportType:h,screenshotUsage:j,lastActionStatus:b}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:N=>N.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{n(N=>!N),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:N=>N.stopPropagation(),onChange:N=>l(N.target.value),onKeyDown:N=>{d(N)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{i(N=>!N),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:f?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:f?"#22c55e":"#eab308",boxShadow:f?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:f?"#22c55e":"#eab308"},children:f?"Connected":"WS"})]}),u>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),h==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),h==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),j&&j.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:j.budgetExhausted?"#ef4444":"#c4b5fd",background:j.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:j.budgetExhausted?"TURN blocked":`TURN ${j.dailyUsedMinutes}/${j.dailyBudgetMinutes}m`}),b&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:b})]})]}),a&&s.jsxs("div",{onTouchStart:N=>N.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(x?m:1)+.01?x?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:N=>{N.stopPropagation(),v()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:N=>{N.stopPropagation(),S()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:x?"FILL":"FIT"}),s.jsx("button",{onClick:N=>{N.stopPropagation(),p()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function xu({waitingLabel:e,waitingHint:t,transportType:r}){return s.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[s.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),s.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),s.jsx("div",{className:"text-[11px] text-white/40",children:t}),r==="relay"&&s.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function bu(){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 yo(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 rr(e,t){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!bu())return;n.current+=1;const a=r.current;if(!a){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([c,l])=>[c,yo(l)]))}),r.current=t;return}const i=Object.keys({...a,...t}).filter(c=>!Object.is(a[c],t[c]));i.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(c=>[c,yo(t[c])]))}),r.current=t})}function gu({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:d,setPanX:f,setPanY:u,setZoom:x,lastWheelTimeRef:m,onAction:v,setLastActionStatus:S,spawnRippleFromNormalized:p,clampPan:h,isMobile:j,mobileFillZoom:b}){const[N,T]=o.useState(null),y=o.useRef(null),C=o.useRef(null),k=o.useRef(null),w=o.useRef(!1),g=o.useRef(null),D=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(v),R=30,G=550,K=18,E=60,W=400,J=12,be=()=>{if(y.current)return;const ye={nx:.5,ny:.5};y.current=ye,T(ye)};return o.useEffect(()=>{V.current=n,n==="mouse"&&be()},[n]),o.useEffect(()=>{L.current=v},[v]),o.useEffect(()=>{const ye=e.current;if(!ye)return;const ge=te=>{if(!r.current)return null;const fe=r.current.getBoundingClientRect();return!fe.width||!fe.height?null:{nx:Math.max(0,Math.min(1,(te.clientX-fe.left)/fe.width)),ny:Math.max(0,Math.min(1,(te.clientY-fe.top)/fe.height))}},ve=(te,fe)=>{if(!r.current)return{dnx:0,dny:0};const re=r.current,pe=re.getBoundingClientRect(),oe=re.naturalWidth||pe.width,le=re.naturalHeight||pe.height,ae=oe/le,Y=pe.width/pe.height;let X,ne;return ae>Y?(X=pe.width,ne=pe.width/ae):(ne=pe.height,X=pe.height*ae),{dnx:te/X,dny:fe/ne}},z=(te,fe,re)=>{if(re<=1.05)return;const pe=-(te-.5)*100,oe=-(fe-.5)*100,le=h(pe,oe,re);(Math.abs(le.x-l.current)>.1||Math.abs(le.y-d.current)>.1)&&(f(le.x),u(le.y),l.current=le.x,d.current=le.y)},F=te=>{const fe=t.current;if(fe&&te.target instanceof Node&&fe.contains(te.target))te.preventDefault();else return;if(te.touches.length===1){const re=te.touches[0];C.current={x:re.clientX,y:re.clientY,time:Date.now()},k.current={x:re.clientX,y:re.clientY},O.current||(w.current=!1),g.current=setTimeout(()=>{if(!w.current&&!O.current)if(w.current=!0,V.current==="mouse"){const pe=y.current||{nx:.5,ny:.5};S("Right Click"),p(pe.nx,pe.ny,"right"),L.current("input_click",{...pe,button:"right"}).catch(()=>{})}else{const pe=ge(re);pe&&(S("Right Click"),p(pe.nx,pe.ny,"right"),L.current("input_click",{...pe,button:"right"}).catch(()=>{}))}},500);return}if(te.touches.length===2){g.current&&clearTimeout(g.current),w.current=!0,O.current=!0;const re=te.touches[1].clientX-te.touches[0].clientX,pe=te.touches[1].clientY-te.touches[0].clientY;A.current=Math.sqrt(re*re+pe*pe),I.current=c.current,P.current={x:(te.touches[0].clientX+te.touches[1].clientX)/2,y:(te.touches[0].clientY+te.touches[1].clientY)/2}}},Q=te=>{const fe=t.current;if(fe&&te.target instanceof Node&&fe.contains(te.target)&&te.preventDefault(),te.touches.length===1&&k.current){const re=te.touches[0],pe=re.clientX-k.current.x,oe=re.clientY-k.current.y;if(!w.current&&C.current){const le=re.clientX-C.current.x,ae=re.clientY-C.current.y;Math.sqrt(le*le+ae*ae)>8&&(w.current=!0,g.current&&clearTimeout(g.current))}if(w.current)if(V.current==="mouse"){const le=ve(pe,oe),ae=y.current||{nx:.5,ny:.5},Y=Math.max(0,Math.min(1,ae.nx+le.dnx)),X=Math.max(0,Math.min(1,ae.ny+le.dny));y.current={nx:Y,ny:X},T({nx:Y,ny:X}),S(`Cursor: ${Math.round(Y*100)}%, ${Math.round(X*100)}%`),z(Y,X,c.current);const ne=Date.now();ne-m.current>=30&&(m.current=ne,L.current("input_mouseMoved",{nx:Y,ny:X}).catch(()=>{}))}else if(c.current>1){const le=t.current;if(le){const ae=le.clientWidth,Y=le.clientHeight,X=l.current+pe/ae*100,ne=d.current+oe/Y*100,M=h(X,ne,c.current);f(M.x),u(M.y),l.current=M.x,d.current=M.y}}else{const le=ge(re);if(le){const ae=Date.now();ae-m.current>=40&&(m.current=ae,S("Scroll"),L.current("input_wheel",{nx:le.nx,ny:le.ny,deltaX:Math.round(-pe*2.5),deltaY:Math.round(-oe*2.5)}).catch(()=>{}))}}k.current={x:re.clientX,y:re.clientY};return}if(te.touches.length===2&&A.current!==null){const re=te.touches[1].clientX-te.touches[0].clientX,pe=te.touches[1].clientY-te.touches[0].clientY,le=Math.sqrt(re*re+pe*pe)/A.current,ae=(te.touches[0].clientX+te.touches[1].clientX)/2,Y=(te.touches[0].clientY+te.touches[1].clientY)/2,X=ae-P.current.x,ne=Y-P.current.y,M=Math.abs(le-1)>.03;if(V.current==="mouse"){if(M){const H=Math.max(i,Math.min(5,I.current*le));x(H),c.current=H}else if(Math.abs(X)>2||Math.abs(ne)>2){const H=y.current||{nx:.5,ny:.5},ce=Date.now();ce-m.current>=30&&(m.current=ce,S("Scroll"),L.current("input_wheel",{nx:H.nx,ny:H.ny,deltaX:Math.round(-X*3),deltaY:Math.round(-ne*3)}).catch(()=>{}))}}else{const H=Math.max(i,Math.min(5,I.current*le));x(H),c.current=H;const ce=t.current;if(ce&&H>1){const me=ce.clientWidth,je=ce.clientHeight,_e=l.current+X/me*100,Me=d.current+ne/je*100,Be=h(_e,Me,H);f(Be.x),u(Be.y),l.current=Be.x,d.current=Be.y}}P.current={x:ae,y:Y}}},ue=te=>{var fe;if(g.current&&clearTimeout(g.current),A.current=null,te.touches.length===1&&O.current){const re=te.touches[0];C.current={x:re.clientX,y:re.clientY,time:Date.now()},k.current={x:re.clientX,y:re.clientY},w.current=!0;return}if(te.touches.length===0){if(O.current){O.current=!1,w.current=!1;return}if(te.changedTouches.length===1){const re=te.changedTouches[0],pe=Date.now(),oe=pe-(((fe=C.current)==null?void 0:fe.time)||0),le=C.current?re.clientX-C.current.x:0,ae=C.current?re.clientY-C.current.y:0,Y=Math.sqrt(le*le+ae*ae);if(V.current==="mouse"){if(oe<R||oe>G||Y>K){w.current=!1;return}const X=y.current||ge(re);X&&(S(`Click: ${Math.round(X.nx*100)}%, ${Math.round(X.ny*100)}%`),p(X.nx,X.ny,"left"),L.current("input_click",{...X}).catch(()=>{}))}else{if(w.current){w.current=!1;return}if(oe<E||oe>W||Y>J){w.current=!1;return}const X=ge(re);if(!X)return;pe-D.current<300?(S("Double tap"),p(X.nx,X.ny,"double"),L.current("input_click",{...X,clickCount:2}).catch(()=>{}),D.current=0):(S(`Tap: ${Math.round(X.nx*100)}%, ${Math.round(X.ny*100)}%`),p(X.nx,X.ny,"left"),L.current("input_click",{...X}).catch(()=>{}),D.current=pe)}}w.current=!1}};return ye.addEventListener("touchstart",F,{passive:!1}),ye.addEventListener("touchmove",Q,{passive:!1}),ye.addEventListener("touchend",ue,{passive:!1}),()=>{ye.removeEventListener("touchstart",F),ye.removeEventListener("touchmove",Q),ye.removeEventListener("touchend",ue),g.current&&clearTimeout(g.current)}},[e,t,r,i,c,l,d,f,u,x,m,S,p,h]),{cursorPos:N,cursorPosRef:y,handleToggleInputMode:()=>{a(ye=>{const ge=ye==="touch"?"mouse":"touch";return ge==="mouse"&&be(),ge})},handleZoomReset:()=>{const ye=j?b:1;x(ye),c.current=ye,f(0),u(0),l.current=0,d.current=0}}}function Oi({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),d=o.useRef(null),[f,u]=o.useState(null),[x,m]=o.useState(""),[,v]=o.useState(!1),[S,p]=o.useState([]),h=o.useRef(0),[j,b]=o.useState(!1),[N,T]=o.useState(!1),y=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[C,k]=o.useState(y?"mouse":"touch"),[w,g]=o.useState(1),D=o.useRef(!1),[A,I]=o.useState(1),[P,O]=o.useState(0),[V,L]=o.useState(0);rr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:C,zoom:A,panX:P,panY:V,isMenuOpen:j,isImeOpen:N});const R=o.useRef(0),G=o.useRef(A),K=o.useRef(P),E=o.useRef(V);o.useEffect(()=>{G.current=A},[A]),o.useEffect(()=>{K.current=P},[P]),o.useEffect(()=>{E.current=V},[V]),o.useEffect(()=>{var oe;(oe=c.current)==null||oe.focus()},[]);const W=r==="connected",J=n,be=W?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",xe=W?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!y||D.current||!J)return;const oe=d.current,le=l.current;if(!oe||!le)return;const ae=()=>{const Y=le.clientWidth,X=le.clientHeight,ne=oe.naturalWidth,M=oe.naturalHeight;if(!ne||!M||!Y||!X)return;const H=Math.min(Y/ne,X/M),me=Math.max(Y/ne,X/M)/H;me>1.01&&(g(me),I(me),G.current=me),D.current=!0};oe.complete&&oe.naturalWidth?ae():oe.addEventListener("load",ae,{once:!0})},[J,y]);const de=.5;o.useEffect(()=>{A<=de&&(O(0),L(0))},[A,de]);const ye=(oe,le,ae)=>{if(ae<=de)return{x:0,y:0};const Y=(ae-1)/(2*ae)*100,X=(ae-1)/(2*ae)*100;return{x:Math.max(-Y,Math.min(Y,oe)),y:Math.max(-X,Math.min(X,le))}},ge=(oe,le)=>{if(!d.current)return null;const ae=d.current.getBoundingClientRect();return!ae.width||!ae.height?null:{nx:Math.max(0,Math.min(1,(oe-ae.left)/ae.width)),ny:Math.max(0,Math.min(1,(le-ae.top)/ae.height))}},ve=(oe,le,ae)=>{const Y=l.current;if(!Y)return;const X=Y.getBoundingClientRect(),ne=++h.current;p(M=>[...M,{id:ne,x:oe-X.left,y:le-X.top,type:ae}]),setTimeout(()=>p(M=>M.filter(H=>H.id!==ne)),600)},z=(oe,le,ae)=>{const Y=d.current,X=l.current;if(!Y||!X)return;const ne=Y.getBoundingClientRect(),M=X.getBoundingClientRect(),H=Y.naturalWidth||ne.width,ce=Y.naturalHeight||ne.height,me=H/ce,je=ne.width/ne.height;let _e,Me,Be,We;me>je?(_e=ne.width,Me=ne.width/me,Be=0,We=(ne.height-Me)/2):(Me=ne.height,_e=ne.height*me,Be=(ne.width-_e)/2,We=0);const Fe=ne.left-M.left+Be+_e*oe,nt=ne.top-M.top+We+Me*le,Ze=++h.current;p(it=>[...it,{id:Ze,x:Fe,y:nt,type:ae}]),setTimeout(()=>p(it=>it.filter(dt=>dt.id!==Ze)),600)},F=async oe=>{var ae;const le=ge(oe.clientX,oe.clientY);if(le){u(`Click: ${Math.round(le.nx*100)}%, ${Math.round(le.ny*100)}%`),ve(oe.clientX,oe.clientY,"left"),(ae=c.current)==null||ae.focus();try{const Y=await e("input_click",{nx:le.nx,ny:le.ny});Y!=null&&Y.success||t(`❌ Click failed: ${Y==null?void 0:Y.error}`)}catch(Y){t(`❌ Click error: ${Y.message||Y}`)}}},Q=async(oe,le,ae,Y=0)=>{try{await e("input_key",{type:ae?"char":"keyDown",key:oe,code:le,text:ae?oe:void 0,unmodifiedText:ae?oe:void 0,modifiers:Y})}catch(X){t(`❌ Key error: ${X.message||X}`)}},ue=async oe=>{if(oe.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(oe.key)&&oe.preventDefault();let ae=0;oe.altKey&&(ae|=1),oe.ctrlKey&&(ae|=2),oe.metaKey&&(ae|=4),oe.shiftKey&&(ae|=8),u(`Key: ${oe.key}`),await Q(oe.key,oe.code,oe.key.length===1,ae)},te=async oe=>{if(oe.key==="Enter"){if(oe.nativeEvent.isComposing)return;if(x){const le=x;m(""),u(`IME Sent: ${le}`);try{const ae=await e("input_type",{text:le});ae!=null&&ae.success||t(`❌ IME error: ${ae==null?void 0:ae.error}`)}catch(ae){t(`❌ IME error: ${ae.message}`)}}else u("Key: Enter"),await Q("Enter","Enter",!1)}};o.useEffect(()=>{const oe=c.current;if(!oe)return;const le=ae=>{var Y;if((Y=d.current)!=null&&Y.contains(ae.target)){ae.preventDefault();const X=Date.now();if(X-R.current<40)return;R.current=X;const ne=ge(ae.clientX,ae.clientY);if(!ne)return;u(`Scroll: ${Math.round(ae.deltaY)}`),e("input_wheel",{nx:ne.nx,ny:ne.ny,deltaX:Math.round(ae.deltaX),deltaY:Math.round(ae.deltaY)}).catch(()=>{})}};return oe.addEventListener("wheel",le,{passive:!1}),()=>oe.removeEventListener("wheel",le)},[e]);const{cursorPos:fe,handleToggleInputMode:re,handleZoomReset:pe}=gu({containerRef:c,viewportRef:l,imgRef:d,inputMode:C,setInputMode:k,minZoom:de,zoomRef:G,panXRef:K,panYRef:E,setPanX:O,setPanY:L,setZoom:I,lastWheelTimeRef:R,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:z,clampPan:ye,isMobile:y,mobileFillZoom:w});return s.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ue,onContextMenu:oe=>oe.preventDefault(),onFocus:()=>v(!0),onBlur:()=>v(!1),tabIndex:0,children:[s.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[J?s.jsx("img",{ref:d,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:F,onContextMenu:oe=>oe.preventDefault(),onDragStart:oe=>oe.preventDefault()}):s.jsx(xu,{waitingLabel:be,waitingHint:xe,transportType:i}),C==="mouse"&&J&&s.jsx(pu,{cursorPos:fe,viewportRef:l,imgRef:d}),S.map(oe=>{const ae={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[oe.type];return s.jsxs("div",{style:{position:"absolute",left:oe.x,top:oe.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.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}}),s.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}})]},oe.id)})]}),s.jsx(hu,{inputMode:C,onToggleInputMode:re,isImeOpen:N,setIsImeOpen:T,isMenuOpen:j,setIsMenuOpen:b,imeText:x,setImeText:m,handleImeSubmit:te,isConnActive:W,zoom:A,isMobile:y,mobileFillZoom:w,onZoomOut:()=>I(oe=>Math.max(.5,oe-.25)),onZoomReset:pe,onZoomIn:()=>I(oe=>Math.min(5,oe+.25)),transportType:i,screenshotUsage:a,lastActionStatus:f}),s.jsx("style",{children:`
|
|
5
5
|
@keyframes slideUp {
|
|
6
6
|
from { opacity: 0; transform: translateY(6px); }
|
|
7
7
|
to { opacity: 1; transform: translateY(0); }
|
|
@@ -24,53 +24,53 @@ var Gl=Object.defineProperty;var ql=(e,t,r)=>t in e?Gl(e,t,{enumerable:!0,config
|
|
|
24
24
|
50% { transform: translateY(-7px); }
|
|
25
25
|
100% { transform: translateY(0px); }
|
|
26
26
|
}
|
|
27
|
-
`})]})}function Jr(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,i=Date.now()-e,c=Math.floor(i/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const u=Math.floor(l/60);if(u<24)return`${u}h${r}`;const f=Math.floor(u/24);return f<7?`${f}d${r}`:new Date(e).toLocaleDateString()}const Ei=e=>Jr(e);function mu(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 Ms(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function fu(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...mu(a)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const a of n.childSessions||[])r(a.id,a)}return t}function Or(e,t){if(e.sessionId){const r=t.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function Qr(e,t,r){const n=Or(e,t),a=Ms(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 pu(e,t,r){return Qr(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function $i({activeConv:e,onModalButton:t}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Ms(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),t(l))},c=l=>l.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&s.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(qs,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.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,w=r!==null;return s.jsx("button",{onClick:()=>i(l),disabled:w,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${d?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${w&&!m?"opacity-40":"opacity-100"} ${w?"cursor-not-allowed":"cursor-pointer"}`,style:d?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:h?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:m?"⏳ ...":c(l)},u)})})]})]})}const va="adhdev_controls_bar_visible",Xn="adhdev:controlsbarvisibilitychange";function fn(e){if(!e)return!1;try{return e.getItem(va)==="1"}catch{return!1}}function go(e,t){if(t)try{t.setItem(va,e?"1":"0")}catch{}}function yo(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Xn,{detail:{visible:e}}))}function Bi(){const[e,t]=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"){t(l.visible);return}t(fn(window.localStorage))},i=c=>{c.key===va&&t(fn(window.localStorage))};return window.addEventListener(Xn,a),window.addEventListener("storage",i),()=>{window.removeEventListener(Xn,a),window.removeEventListener("storage",i)}},[]);const r=o.useCallback(a=>{t(a),typeof window<"u"&&go(a,window.localStorage),yo(a)},[]),n=o.useCallback(()=>{t(a=>{const i=!a;return typeof window<"u"&&go(i,window.localStorage),yo(i),i})},[]);return{isVisible:e,setVisibility:r,toggleVisibility:n}}var hu=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function xu(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function bt(e,t){if(xu(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":hu.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 Ki(e){return bt(e)==="generating"}function Ze(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function bu(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const r=Math.floor(t/60),n=t%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),i=r%24;return`${a}d ${i}h`}function pn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Zr(e,t){const r=typeof t=="string"?t.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),i=a.split(/[\\/]/).filter(Boolean);return i[i.length-1]||a}function gu(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),r=t[t.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function yu(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function vu(e){return gu(e.trim().replace(/\.local$/i,""))}function wu(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function Oi(e,t={}){var a,i;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(i=e.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!yu(c));if(r&&r!=="Unknown")return vu(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Mt(e,t={}){return wu(e)||Oi(e,t)}function Wi(e){return!e||!Array.isArray(e.items)?[]:e.items.map(t=>String((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim()).filter(Boolean)}function Hi(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function ds(e,t){return Wi(e).join(" · ")}function Xs(e){return e.transport==="pty"}function ys(e){return e.transport==="acp"}function ju(e,t){var r,n;return(r=t==null?void 0:t.providerLabels)!=null&&r[e]?t.providerLabels[e]:(n=t==null?void 0:t.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:Ze(e)}function vo(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=Ze(r||"").trim().toLowerCase();return n===a||n===i||n===c}function ku(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Su(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=t.get(a),c=bt(n.status);if(!i){t.set(a,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),u=r.indexOf(c||"idle");u>=0&&(l<0||u<l)&&t.set(a,{...n,status:c})}return Array.from(t.values())}function Nu(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Cu(e){var r,n;const t=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return t&&Nu(t.receivedAt)||0}function Iu(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Jn(e){return Math.max(Iu(e),Cu(e.activeChat))}function Au(e,t,r,n,a,i){const c=t-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(i)}function wa(e,t){return Au(Jn(e),Jn(t),Mt(e,{fallbackId:e.id}),Mt(t,{fallbackId:t.id}),e.id,t.id)}const Fi="adhdev_notification_prefs",wo={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Mu(){try{const e=localStorage.getItem(Fi);if(e){const t=JSON.parse(e);return{...wo,...t}}}catch{}return{...wo}}function Tu(e){try{localStorage.setItem(Fi,JSON.stringify(e))}catch{}}let Wt=Mu(),Mr=[];function Lu(){Mr.forEach(e=>e())}function Ru(e){Wt={...Wt,...e},Tu(Wt),Lu()}function Pu(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Mr.push(r),()=>{Mr=Mr.filter(n=>n!==r)}},[]);const t=o.useCallback(r=>{Ru(r)},[]);return[{...Wt},t]}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 _u={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Ui(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function zi(){return"Notification"in window&&Notification.permission==="granted"}let Xt=null;async function Du(){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 Qn(e,t,r){if(zi())try{const n=new Notification(e,{body:t,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function Eu(e,t={}){const r={..._u,...t},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{Du().then(l=>{i.current=l})},[]);const c=o.useCallback((l,u,f)=>{const d=Date.now();d-a.current<r.throttleMs||(a.current=d,Qn(l,u,f))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!zi())&&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")&&Ki(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 $u=/^(run|approve|accept|yes|allow|always)/,Bu=/^(run|approve|accept|yes|allow|always|proceed|save)/,Ku=/^(reject|deny|delete|remove|abort|cancel|no)/;function ja(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Ou(e){const t=ja(e).toLowerCase();return $u.test(t)?"primary":Ku.test(t)?"danger":"default"}function Wu(e){return Bu.test(ja(e).toLowerCase())?"approve":"reject"}function Hu(e){return e.map((t,r)=>({label:ja(t),variant:Ou(t),action:Wu(t),button:t,buttonIndex:r}))}function Fu(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Uu(e,t,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,t,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,t,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class zu{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(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(i=>i.id===t.daemonId&&i.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const i=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var S;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),i=n||t.daemonId||"",c=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),l=`${i}:${t.event}:${c}`;if(this.isDuplicate(l))return;const u=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,f=(u==null?void 0:u.type)||"";let d=Ze(f);const h=this.resolveOwningDaemon(t);if(h){const p=Mt(h,{fallbackId:h.id});p&&(d=!f||f==="adhdev-daemon"?p:`${p}/${d}`)}let m="",w="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";m=`✅ ${d} agent task completed${p}`,w="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(m=`⚡ ${d} approval needed`,w="warning",(S=t.modalButtons)!=null&&S.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const x=this.resolveActionFn,j=Hu(t.modalButtons).map(T=>({label:T.label,variant:T.variant,onClick:()=>{x(p,"resolve_action",{action:T.action,button:T.button,buttonIndex:T.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),b=Fu(d,t.modalMessage,m),N=Date.now();this.emitToast({id:N,message:b,type:w,timestamp:N,targetKey:n||p,actions:j,duration:15e3}),m=""}}else if(t.event==="monitor:long_generating"){const p=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";m=`⚠️ ${d} agent is taking a long time${p}`,w="warning",Os("browser")&&!document.hasFocus()&&Qn(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const p=t.requesterName||"A team member",x=t.requestId,j=t.orgId;if(m=`👁️ ${p} wants to view your session`,w="warning",x&&j&&this.viewRequestRespondFn){const b=Date.now(),N=Uu(j,x,this.viewRequestRespondFn,(T,y)=>console.error(`[EventManager] ${T} view request failed:`,y));this.emitToast({id:b,message:m,type:w,timestamp:b,actions:N,duration:3e4}),m=""}Os("browser")&&!document.hasFocus()&&Qn("👁️ View Request",`${p} wants to view your session`,`view-request-${x}`)}else t.event==="team:view_request_approved"?(m="✅ View request approved",w="success"):t.event==="team:view_request_rejected"&&(m=`❌ ${t.targetName||"Team member"} declined your view request`,w="warning");if(m){const p=Date.now();this.emitToast({id:p,message:m,type:w,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const lt=new zu,jo=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 Vu(e){const t=en(e);return!t||!Wr(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function fr(e){const t=en(e);return!t||!Wr(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Ls(e){const t=en(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function pr(e){const t=en(e);return!!t&&t.success===!1}function Gu(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";lt.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";lt.showToast(n.notification.body,a)}}}function qu(e,t){return e&&vs(e.currentValue)?e.currentValue:t}function Yu(e,t){return vs(t)?vs(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Xu(e,t){var i,c;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(vs(l))return l}const n=(i=t.controlValues)==null?void 0:i[e];if(vs(n))return n;const a=(c=t.defaultValues)==null?void 0:c[e];return vs(a)?a:void 0}function Tr(e,t){return e.options||t[e.id]||[]}const Ju={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 Qu(e,t,r){var n;return((n=Ju[t])==null?void 0:n.has(r.id))===!0}function ka(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Qu(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function hn(e,t){return{value:t}}function Zu(e,t,r){var a;return r?((a=Tr(e,t).find(i=>i.value===r))==null?void 0:a.label)||r:""}const em={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function tm({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=jt(),u=`${e}:${t||n}`,f=em[n]||"#94a3b8",[d,h]=o.useState({}),m=o.useRef({}),w=o.useRef(c);m.current=d,w.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[j,b]=o.useState(jo.get(u)||{}),[N,T]=o.useState(null),[y,C]=o.useState(null),k=o.useCallback(async(R,G={})=>{const B={...G,...t&&{targetSessionId:t}};return await l(e,R,B)},[e,t,l]),v=o.useCallback(async(R,G={})=>{const B=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await k("invoke_provider_script",{...B,scriptName:R,...G})},[k,n,r,t]),g=o.useCallback((R,G,B)=>{const E=qu(B,G);h(W=>({...W,[R.id]:E})),Gu(B==null?void 0:B.effects)},[]),D=o.useCallback((R,G)=>{h(B=>{const E={...B};return G===void 0?delete E[R.id]:E[R.id]=G,E}),S.current=0},[]);if(!i||i.length===0)return null;const M=ka(i,{hostIdeType:r,providerType:n});if(M.length===0)return null;const I=async R=>{if(N===R.id){T(null);return}if(Tr(R,j).length>0){T(R.id);return}if(R.dynamic&&R.listScript){C(R.id);try{const B=await v(R.listScript,{}),E=Vu(B);if(!E){const be=Ls(B);be&<.showToast(be,"warning");return}const W=E.options;b(be=>{const he={...be,[R.id]:W};return jo.set(u,he),he});const J=Xu(R.id,{localOverrideUntil:S.current,localValues:m.current,controlValues:w.current,defaultValues:p});if(Yu(J,E.currentValue)){const be=E.currentValue;h(he=>({...he,[R.id]:be}))}T(R.id)}catch(B){const E=B instanceof Error?B.message:`Could not load ${R.label}`;lt.showToast(E,"warning")}finally{C(null)}}},P=async(R,G)=>{T(null);const B=(c==null?void 0:c[R.id])??p[R.id];h(E=>({...E,[R.id]:G})),S.current=Date.now()+5e3;try{if(!R.setScript)return;const E=await v(R.setScript,hn(R,G)),W=fr(E);if(W&&!W.ok||pr(E))throw new Error((W==null?void 0:W.error)||Ls(E)||`Could not update ${R.label}`);g(R,G,W)}catch(E){D(R,B);const W=E instanceof Error?E.message:`Could not update ${R.label}`;lt.showToast(W,"warning")}},K=async R=>{const G=Tr(R,j).map(he=>he.value);if(G.length===0)return;const B=String(x[R.id]||""),W=(G.indexOf(B)+1)%G.length,J=G[W];if(typeof J!="string")return;const be=(c==null?void 0:c[R.id])??p[R.id];h(he=>({...he,[R.id]:J})),S.current=Date.now()+5e3;try{if(!R.setScript)return;const he=await v(R.setScript,hn(R,J)),de=fr(he);if(de&&!de.ok||pr(he))throw new Error((de==null?void 0:de.error)||Ls(he)||`Could not update ${R.label}`);g(R,J,de)}catch(he){D(R,be);const de=he instanceof Error?he.message:`Could not update ${R.label}`;lt.showToast(de,"warning")}},V=async R=>{const B=!x[R.id],E=(c==null?void 0:c[R.id])??p[R.id];h(W=>({...W,[R.id]:B})),S.current=Date.now()+5e3;try{if(!R.setScript)return;const W=await v(R.setScript,hn(R,B)),J=fr(W);if(J&&!J.ok||pr(W))throw new Error((J==null?void 0:J.error)||Ls(W)||`Could not update ${R.label}`);g(R,B,J)}catch(W){D(R,E);const J=W instanceof Error?W.message:`Could not update ${R.label}`;lt.showToast(J,"warning")}},L=async R=>{if(!R.invokeScript)return;if(R.confirmMessage){const B=[R.confirmTitle,R.confirmMessage,R.confirmLabel].filter(W=>typeof W=="string"&&W.trim().length>0);if(!window.confirm(B.join(`
|
|
27
|
+
`})]})}function Jr(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,i=Date.now()-e,c=Math.floor(i/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const d=Math.floor(l/60);if(d<24)return`${d}h${r}`;const f=Math.floor(d/24);return f<7?`${f}d${r}`:new Date(e).toLocaleDateString()}const Wi=e=>Jr(e);function yu(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 Ts(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function vu(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...yu(a)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const a of n.childSessions||[])r(a.id,a)}return t}function Or(e,t){if(e.sessionId){const r=t.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function Qr(e,t,r){const n=Or(e,t),a=Ts(e),i=a.isReconnecting,c=a.isConnecting,l=a.isGenerating,d=a.isWaiting,f=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,u=n.inboxBucket==="working"||l,m=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:m,requiresAction:f,isWorking:u,isReconnecting:i,isConnecting:c,isGenerating:l,isWaiting:d,inboxBucket:f?"needs_attention":u?"working":m?"task_complete":"idle"}}function wu(e,t,r){return Qr(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Hi({activeConv:e,onModalButton:t}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Ts(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),t(l))},c=l=>l.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&s.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(Xs,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,d)=>{const f=c(l).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(f),x=/^(reject|deny|delete|remove|abort)/.test(f),m=r===l,v=r!==null;return s.jsx("button",{onClick:()=>i(l),disabled:v,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":x?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${v&&!m?"opacity-40":"opacity-100"} ${v?"cursor-not-allowed":"cursor-pointer"}`,style:u?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:x?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:m?"⏳ ...":c(l)},d)})})]})]})}const va="adhdev_controls_bar_visible",Xn="adhdev:controlsbarvisibilitychange";function fn(e){if(!e)return!1;try{return e.getItem(va)==="1"}catch{return!1}}function vo(e,t){if(t)try{t.setItem(va,e?"1":"0")}catch{}}function wo(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Xn,{detail:{visible:e}}))}function Fi(){const[e,t]=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"){t(l.visible);return}t(fn(window.localStorage))},i=c=>{c.key===va&&t(fn(window.localStorage))};return window.addEventListener(Xn,a),window.addEventListener("storage",i),()=>{window.removeEventListener(Xn,a),window.removeEventListener("storage",i)}},[]);const r=o.useCallback(a=>{t(a),typeof window<"u"&&vo(a,window.localStorage),wo(a)},[]),n=o.useCallback(()=>{t(a=>{const i=!a;return typeof window<"u"&&vo(i,window.localStorage),wo(i),i})},[]);return{isVisible:e,setVisibility:r,toggleVisibility:n}}var ju=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function ku(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function bt(e,t){if(ku(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":ju.has(r)?"generating":r==="error"?"error":r==="stopped"?"stopped":r==="starting"?"starting":r==="panel_hidden"?"panel_hidden":r==="not_monitored"?"not_monitored":r==="disconnected"?"disconnected":"idle"}function Ui(e){return bt(e)==="generating"}function tt(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Su(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const r=Math.floor(t/60),n=t%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),i=r%24;return`${a}d ${i}h`}function pn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Zr(e,t){const r=typeof t=="string"?t.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),i=a.split(/[\\/]/).filter(Boolean);return i[i.length-1]||a}function Nu(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),r=t[t.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function Cu(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Iu(e){return Nu(e.trim().replace(/\.local$/i,""))}function Mu(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function zi(e,t={}){var a,i;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(i=e.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!Cu(c));if(r&&r!=="Unknown")return Iu(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function At(e,t={}){return Mu(e)||zi(e,t)}function Vi(e){return!e||!Array.isArray(e.items)?[]:e.items.map(t=>String((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim()).filter(Boolean)}function Gi(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function ds(e,t){return Vi(e).join(" · ")}function Qs(e){return e.transport==="pty"}function ys(e){return e.transport==="acp"}function Au(e,t){var r,n;return(r=t==null?void 0:t.providerLabels)!=null&&r[e]?t.providerLabels[e]:(n=t==null?void 0:t.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:tt(e)}function jo(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=tt(r||"").trim().toLowerCase();return n===a||n===i||n===c}function Tu(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Lu(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=t.get(a),c=bt(n.status);if(!i){t.set(a,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),d=r.indexOf(c||"idle");d>=0&&(l<0||d<l)&&t.set(a,{...n,status:c})}return Array.from(t.values())}function Ru(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Pu(e){var r,n;const t=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return t&&Ru(t.receivedAt)||0}function _u(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Jn(e){return Math.max(_u(e),Pu(e.activeChat))}function Du(e,t,r,n,a,i){const c=t-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(i)}function wa(e,t){return Du(Jn(e),Jn(t),At(e,{fallbackId:e.id}),At(t,{fallbackId:t.id}),e.id,t.id)}const qi="adhdev_notification_prefs",ko={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Eu(){try{const e=localStorage.getItem(qi);if(e){const t=JSON.parse(e);return{...ko,...t}}}catch{}return{...ko}}function $u(e){try{localStorage.setItem(qi,JSON.stringify(e))}catch{}}let Ht=Eu(),Ar=[];function Bu(){Ar.forEach(e=>e())}function Ku(e){Ht={...Ht,...e},$u(Ht),Bu()}function Ou(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Ar.push(r),()=>{Ar=Ar.filter(n=>n!==r)}},[]);const t=o.useCallback(r=>{Ku(r)},[]);return[{...Ht},t]}function Fs(e){if(!Ht.globalEnabled)return!1;switch(e){case"disconnect":return Ht.disconnectAlert;case"completion":return Ht.completionAlert;case"approval":return Ht.approvalAlert;case"browser":return Ht.browserNotifications;default:return!0}}const Wu={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Yi(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Xi(){return"Notification"in window&&Notification.permission==="granted"}let Xt=null;async function Hu(){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 Qn(e,t,r){if(Xi())try{const n=new Notification(e,{body:t,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function Fu(e,t={}){const r={...Wu,...t},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{Hu().then(l=>{i.current=l})},[]);const c=o.useCallback((l,d,f)=>{const u=Date.now();u-a.current<r.throttleMs||(a.current=u,Qn(l,d,f))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!Xi())&&Fs("browser")&&i.current!==!0){if(document.hasFocus()){for(const d of e)n.current.set(d.id,bt(d.status,{activeModal:d.activeModal}));return}for(const d of e){const f=n.current.get(d.id),u=bt(d.status,{activeModal:d.activeModal}),x=d.name||d.id;if(r.onApproval&&Fs("approval")&&u==="waiting_approval"&&f!=="waiting_approval"){const m=((l=d.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${x} — Approval needed`,m.slice(0,120),`approval-${d.id}`)}r.onComplete&&Fs("completion")&&Ui(f)&&u==="idle"&&c(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${d.id}`),r.onError&&u==="error"&&f!=="error"&&c(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${d.id}`),n.current.set(d.id,u)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const Uu=/^(run|approve|accept|yes|allow|always)/,zu=/^(run|approve|accept|yes|allow|always|proceed|save)/,Vu=/^(reject|deny|delete|remove|abort|cancel|no)/;function ja(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Gu(e){const t=ja(e).toLowerCase();return Uu.test(t)?"primary":Vu.test(t)?"danger":"default"}function qu(e){return zu.test(ja(e).toLowerCase())?"approve":"reject"}function Yu(e){return e.map((t,r)=>({label:ja(t),variant:Gu(t),action:qu(t),button:t,buttonIndex:r}))}function Xu(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Ju(e,t,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,t,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,t,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class Qu{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(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(i=>i.id===t.daemonId&&i.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const i=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var S;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),i=n||t.daemonId||"",c=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),l=`${i}:${t.event}:${c}`;if(this.isDuplicate(l))return;const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,f=(d==null?void 0:d.type)||"";let u=tt(f);const x=this.resolveOwningDaemon(t);if(x){const p=At(x,{fallbackId:x.id});p&&(u=!f||f==="adhdev-daemon"?p:`${p}/${u}`)}let m="",v="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";m=`✅ ${u} agent task completed${p}`,v="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(m=`⚡ ${u} approval needed`,v="warning",(S=t.modalButtons)!=null&&S.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const h=this.resolveActionFn,j=Yu(t.modalButtons).map(T=>({label:T.label,variant:T.variant,onClick:()=>{h(p,"resolve_action",{action:T.action,button:T.button,buttonIndex:T.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),b=Xu(u,t.modalMessage,m),N=Date.now();this.emitToast({id:N,message:b,type:v,timestamp:N,targetKey:n||p,actions:j,duration:15e3}),m=""}}else if(t.event==="monitor:long_generating"){const p=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";m=`⚠️ ${u} agent is taking a long time${p}`,v="warning",Fs("browser")&&!document.hasFocus()&&Qn(`⚠️ ${u} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const p=t.requesterName||"A team member",h=t.requestId,j=t.orgId;if(m=`👁️ ${p} wants to view your session`,v="warning",h&&j&&this.viewRequestRespondFn){const b=Date.now(),N=Ju(j,h,this.viewRequestRespondFn,(T,y)=>console.error(`[EventManager] ${T} view request failed:`,y));this.emitToast({id:b,message:m,type:v,timestamp:b,actions:N,duration:3e4}),m=""}Fs("browser")&&!document.hasFocus()&&Qn("👁️ View Request",`${p} wants to view your session`,`view-request-${h}`)}else t.event==="team:view_request_approved"?(m="✅ View request approved",v="success"):t.event==="team:view_request_rejected"&&(m=`❌ ${t.targetName||"Team member"} declined your view request`,v="warning");if(m){const p=Date.now();this.emitToast({id:p,message:m,type:v,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const lt=new Qu,So=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 Zu(e){const t=en(e);return!t||!Wr(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function pr(e){const t=en(e);return!t||!Wr(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Ps(e){const t=en(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function hr(e){const t=en(e);return!!t&&t.success===!1}function em(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";lt.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";lt.showToast(n.notification.body,a)}}}function tm(e,t){return e&&vs(e.currentValue)?e.currentValue:t}function sm(e,t){return vs(t)?vs(e)?typeof e=="string"&&e.trim()==="":!0:!1}function rm(e,t){var i,c;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(vs(l))return l}const n=(i=t.controlValues)==null?void 0:i[e];if(vs(n))return n;const a=(c=t.defaultValues)==null?void 0:c[e];return vs(a)?a:void 0}function Tr(e,t){return e.options||t[e.id]||[]}const nm={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 am(e,t,r){var n;return((n=nm[t])==null?void 0:n.has(r.id))===!0}function ka(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!am(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function hn(e,t){return{value:t}}function om(e,t,r){var a;return r?((a=Tr(e,t).find(i=>i.value===r))==null?void 0:a.label)||r:""}const im={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function cm({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=wt(),d=`${e}:${t||n}`,f=im[n]||"#94a3b8",[u,x]=o.useState({}),m=o.useRef({}),v=o.useRef(c);m.current=u,v.current=c;const S=o.useRef(0),p={};for(const R of i||[])R.defaultValue!==void 0&&(p[R.id]=R.defaultValue);const h={...p,...c||{},...Date.now()<S.current?u:{}};o.useEffect(()=>{c&&Date.now()>S.current&&x({})},[c]);const[j,b]=o.useState(So.get(d)||{}),[N,T]=o.useState(null),[y,C]=o.useState(null),k=o.useCallback(async(R,G={})=>{const K={...G,...t&&{targetSessionId:t}};return await l(e,R,K)},[e,t,l]),w=o.useCallback(async(R,G={})=>{const K=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await k("invoke_provider_script",{...K,scriptName:R,...G})},[k,n,r,t]),g=o.useCallback((R,G,K)=>{const E=tm(K,G);x(W=>({...W,[R.id]:E})),em(K==null?void 0:K.effects)},[]),D=o.useCallback((R,G)=>{x(K=>{const E={...K};return G===void 0?delete E[R.id]:E[R.id]=G,E}),S.current=0},[]);if(!i||i.length===0)return null;const A=ka(i,{hostIdeType:r,providerType:n});if(A.length===0)return null;const I=async R=>{if(N===R.id){T(null);return}if(Tr(R,j).length>0){T(R.id);return}if(R.dynamic&&R.listScript){C(R.id);try{const K=await w(R.listScript,{}),E=Zu(K);if(!E){const be=Ps(K);be&<.showToast(be,"warning");return}const W=E.options;b(be=>{const xe={...be,[R.id]:W};return So.set(d,xe),xe});const J=rm(R.id,{localOverrideUntil:S.current,localValues:m.current,controlValues:v.current,defaultValues:p});if(sm(J,E.currentValue)){const be=E.currentValue;x(xe=>({...xe,[R.id]:be}))}T(R.id)}catch(K){const E=K instanceof Error?K.message:`Could not load ${R.label}`;lt.showToast(E,"warning")}finally{C(null)}}},P=async(R,G)=>{T(null);const K=(c==null?void 0:c[R.id])??p[R.id];x(E=>({...E,[R.id]:G})),S.current=Date.now()+5e3;try{if(!R.setScript)return;const E=await w(R.setScript,hn(R,G)),W=pr(E);if(W&&!W.ok||hr(E))throw new Error((W==null?void 0:W.error)||Ps(E)||`Could not update ${R.label}`);g(R,G,W)}catch(E){D(R,K);const W=E instanceof Error?E.message:`Could not update ${R.label}`;lt.showToast(W,"warning")}},O=async R=>{const G=Tr(R,j).map(xe=>xe.value);if(G.length===0)return;const K=String(h[R.id]||""),W=(G.indexOf(K)+1)%G.length,J=G[W];if(typeof J!="string")return;const be=(c==null?void 0:c[R.id])??p[R.id];x(xe=>({...xe,[R.id]:J})),S.current=Date.now()+5e3;try{if(!R.setScript)return;const xe=await w(R.setScript,hn(R,J)),de=pr(xe);if(de&&!de.ok||hr(xe))throw new Error((de==null?void 0:de.error)||Ps(xe)||`Could not update ${R.label}`);g(R,J,de)}catch(xe){D(R,be);const de=xe instanceof Error?xe.message:`Could not update ${R.label}`;lt.showToast(de,"warning")}},V=async R=>{const K=!h[R.id],E=(c==null?void 0:c[R.id])??p[R.id];x(W=>({...W,[R.id]:K})),S.current=Date.now()+5e3;try{if(!R.setScript)return;const W=await w(R.setScript,hn(R,K)),J=pr(W);if(J&&!J.ok||hr(W))throw new Error((J==null?void 0:J.error)||Ps(W)||`Could not update ${R.label}`);g(R,K,J)}catch(W){D(R,E);const J=W instanceof Error?W.message:`Could not update ${R.label}`;lt.showToast(J,"warning")}},L=async R=>{if(!R.invokeScript)return;if(R.confirmMessage){const K=[R.confirmTitle,R.confirmMessage,R.confirmLabel].filter(W=>typeof W=="string"&&W.trim().length>0);if(!window.confirm(K.join(`
|
|
28
28
|
|
|
29
|
-
`)))return}const G=(c==null?void 0:c[R.id])??p[R.id];try{const B=await v(R.invokeScript),E=fr(B);if(E&&!E.ok||pr(B))throw new Error((E==null?void 0:E.error)||Ls(B)||`Could not run ${R.label}`);E&&g(R,G??!0,E)}catch(B){D(R,G);const E=B instanceof Error?B.message:`Could not run ${R.label}`;lt.showToast(E,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${f}33`,background:`${f}12`,color:f},children:a}),M.map(R=>{const G=String(x[R.id]||""),B=Zu(R,j,G),E=N===R.id,W=y===R.id,J=Tr(R,j),be="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 s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${f}55`:"var(--border-default)",background:E?`${f}10`:"var(--surface-tertiary)",color:G?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void I(R),title:R.label,children:[R.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:W?"Loading…":B||R.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),E&&J.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>T(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:R.label}),J.map(he=>s.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[12px] transition-colors",style:{background:he.value===G?`${f}14`:"transparent",color:he.value===G?"var(--text-primary)":"var(--text-secondary)",borderLeft:he.value===G?`2px solid ${f}`:"2px solid transparent"},title:he.description||he.label,onMouseEnter:de=>{de.currentTarget.style.background=`${f}10`},onMouseLeave:de=>{de.currentTarget.style.background=he.value===G?`${f}14`:"transparent"},onClick:()=>void P(R,he.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:he.label}),he.value===G&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:f},children:"✓"})]},he.value))]})]})]},R.id);case"cycle":return s.jsxs("button",{type:"button",className:`${be} 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 K(R),title:`Click to cycle: ${J.map(he=>he.label).join(" → ")}`,children:[R.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:B||R.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},R.id);case"toggle":return s.jsxs("button",{type:"button",className:`${be} 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&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),R.label]},R.id);case"action":return s.jsxs("button",{type:"button",className:`${be} 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&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),s.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 s.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:G?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:G?`${R.label}: ${G}`:R.label})]},R.id);default:return null}})]})})}function sm({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:f}=Bi(),d=ka(l,{hostIdeType:a,providerType:i});return!e||t||d.length===0||!f?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(tm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:d,controlValues:u})})}function rm({hasDraft:e,isBusy:t=!1}){return!e||t}const Vi=o.memo(function({contextKey:t,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:w,toggleVisibility:S}=Bi();o.useEffect(()=>{m("")},[t]),o.useEffect(()=>{var x;l&&((x=d.current)==null||x.focus({preventScroll:!0}))},[t,l]);const p=async()=>{const x=h.trim();if(!x||a)return;await c(x)!==!1&&m("")};return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",f?"transition-all duration-200 ease-out":""].filter(Boolean).join(" "),style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[s.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[u&&s.jsx("button",{type:"button",onClick:S,"aria-label":w?"Hide controls":"Show controls","aria-pressed":w,title:w?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("input",{ref:d,type:"text",placeholder:i||`Send message to ${r}...`,value:h,onChange:x=>m(x.target.value),onPaste:x=>{const j=x.clipboardData.getData("text");j&&m(b=>b+j),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 j=x.relatedTarget;if((j==null?void 0:j.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))"}})}),s.jsx("button",{onClick:()=>{p()},disabled:rm({hasDraft:!!h.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${h.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:h.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:h.trim()?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),Je=e=>e.transport==="pty",Ts=(e,t)=>Je(e)?e.mode||"terminal":"chat",Gi=(e,t)=>Je(e)&&Ts(e)==="terminal",qe=e=>e.transport==="acp";function Vt(e){return e.streamSource!=="agent-stream"}function fs(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function qi(e){return e.machineName||""}function sr(e){return fs(e)}function Kt(e){return e.agentType||""}function Hr(e){return e.hostIdeType||""}function Sa(e){return e.displayPrimary||e.agentName||"Agent"}function Yi(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function nm(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function ko(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function am(e){return ko(e==null?void 0:e.receivedAt)||ko(e==null?void 0:e.timestamp)||0}function Xi(e){const t=nm(e),r=Vs(t==null?void 0:t.content),n=am(t),a=Vs(e.lastMessagePreview),i=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0;return a&&!r?a:r&&!a?r:a&&r&&i>0&&n>0&&i>n?a:r||a||""}function om(e){return Xi(e)||e.displaySecondary||""}function Ji(e){return[e.displaySecondary,qi(e)].filter(Boolean)}function Ns(e){return e.agentName||Ze(Kt(e))}function im(e){var t,r;if(!Vt(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return Ze(Hr(e)||Kt(e))}function Qi(e){return Vt(e)?e.sessionId:e.nativeSessionId}function So(e){return Vt(e)?"native":e.tabKey}function cm(e){return e.sessionId}function lm(e,t){if(t)return Vt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function dm(e,t){const r=Kt(e),n=Vt(e),a=Je(e)||qe(e),i=n?a?Ns(e)||(t==null?void 0:t.cliName)||Ze(Hr(e)||r):t!=null&&t.type?Ze(t.type):Ze(Hr(e)||r):Ns(e);return{isNativeConversation:n,isCli:Je(e),isAcp:qe(e),isCliTerminal:Gi(e),providerType:r,displayLabel:i,targetEntry:lm(e,t)}}function gt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ht(e,t){const r=gt(t);return r?`${e}:${r}`:void 0}function zt(e,t,r){const n=Ht(t,r),a=gt(r);n&&e.push(n),a&&e.push(a)}function gs(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function Zi(e){return gt(e.providerSessionId)||gt(e.sessionId)||gt(e.tabKey)||gt(e.routeId)}function Na(e){return gs([gt(e.providerSessionId),gt(e.sessionId)])}function ws(e){const t=[];return zt(t,"provider",e.providerSessionId),zt(t,"session",e.sessionId),zt(t,"tab",e.tabKey),zt(t,"route",e.routeId),gs(t)}function um(e){const t=[];return gt(e.providerSessionId)?(zt(t,"provider",e.providerSessionId),gs(t)):gt(e.sessionId)?(zt(t,"session",e.sessionId),gs(t)):gt(e.tabKey)?(zt(t,"tab",e.tabKey),gs(t)):gt(e.routeId)?(zt(t,"route",e.routeId),gs(t)):[]}function Ca(e){return Ht("provider",e.providerSessionId)||Ht("session",e.sessionId)||Ht("tab",e.tabKey)||Ht("route",e.routeId)||"unknown:"}function rr(e){return Na(e)[0]}function mm(e){const t=gt(e.providerSessionId),r=gt(e.sessionId),n=gt(e.tabKey),a=gt(e.routeId),i=[Ht("provider",t),Ht("session",r),Ht("tab",n),Ht("route",a)].filter(u=>typeof u=="string"),c=ws({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=Ca({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:Zi({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:rr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function Zn(e,t){const r=mm(e);return um(t).some(n=>r.lookupKeys.includes(n))}function No(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function es(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],r=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,n=No(t==null?void 0:t.receivedAt)||No(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function ea(e,t=0){return es(e)||e.lastUpdated||t||0}function ec(e){return es(e)||e.lastUpdated||0}function tc(e,t,r=ec){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(t.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(t.displaySecondary);return c!==0?c:e.tabKey.localeCompare(t.tabKey)}function ta(e){var r;const t=bt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function fm(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!ta(e)&&!e.title.trim()}function pm(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(ta(r))-Number(ta(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:tc(t,r)})[0]||null}function _t(e,t){const r=e.filter(c=>c.routeId===t);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,a=r.filter(c=>c.streamSource==="agent-stream"),i=pm(a);return n?i&&fm(n)?i:n:i||r[0]||null}function Gt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ia(e){return rr(e)||e.tabKey||e.routeId||null}function sc(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(t)return t;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=_t(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?Ia(a):null}function rc({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=As(),c=fs(e),l=qi(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=im(e),w=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),S=o.useCallback(()=>{if(r){r();return}const p=Ia(e);p&&i(Gt(p))},[e,i,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:m,children:[s.jsx(Ct,{size:12}),s.jsx("span",{children:m})]}):s.jsxs("span",{className:"conversation-meta-chip",title:m,children:[s.jsx(Ct,{size:12}),s.jsx("span",{children:m})]})),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:h})]}),d&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:h})]}),l&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:l,children:[s.jsx(ls,{size:12}),s.jsx("span",{children:l})]}):s.jsxs("span",{className:"conversation-meta-chip",title:l,children:[s.jsx(ls,{size:12}),s.jsx("span",{children:l})]}))]})}function xn(e,t){return`${e}:${t}`}function hm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function hr(e,t){hm()&&console.debug(`[subscription-manager] ${e}`,t)}class xm{constructor(){Ge(this,"active",new Map)}subscribe(t,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=t.sendData)==null?void 0:f.call(t,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=t.sendData)==null||m.call(t,r,h)};return u.initialSendAccepted=l,u}publish(t){const r=xn(t.topic,t.key),n=this.active.get(r);n&&(n.lastUpdate=t,ks.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),n.handlers.forEach(a=>{a(t),ks.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,r,n){const a=xn(t,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(t){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=t.sendData)==null||r.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,r){var a;const n=Array.from(this.active.values()).filter(i=>i.daemonId===t);hr("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}}const qt=new xm;function bm(e,t){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===t&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker});for(const i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function gm(e){const t=[],r=new Map;for(const n of e)if(n.parentId){const a=r.get(n.parentId)||[];a.push(n),r.set(n.parentId,a)}else t.push(n);return{topLevel:t,childrenByParent:r}}function Fr(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=t,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:f,childrenByParent:d}=gm(u),h=bm(i,n),m=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,w=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:w.some(x=>!!x.cdpConnected)});for(const x of w){const j=h.get(x.id),b=Bs(x,j),N=(d.get(x.id)||[]).map(T=>Bs(T,h.get(T.id)));r.push({id:`${n}:ide:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,status:b.cdpConnected?"online":"detected",daemonId:n,instanceId:x.id,workspace:b.workspace,terminals:0,childSessions:N,agents:N.map(T=>({id:T.id,name:T.providerName||T.providerType,type:T.providerType,status:T.status})),activeChat:b.activeChat,chats:[],cdpConnected:b.cdpConnected,...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l})}for(const x of S){const j=h.get(x.id),b=Bs(x,j);r.push({id:`${n}:cli:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:x.id,cliName:b.providerName||b.providerType,mode:b.mode||(j==null?void 0:j.mode)||"terminal",workspace:b.workspace||"",activeChat:b.activeChat,...b.resume!==void 0&&{resume:b.resume},...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isCli:!0})}for(const x of p){const j=h.get(x.id),b=Bs(x,j);r.push({id:`${n}:acp:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:x.id,cliName:b.providerName||b.providerType,mode:"chat",workspace:b.workspace||"",activeChat:b.activeChat,...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const ym=15e3,vm=15e3,wm=6e4,jm=1200,Co=12,km=8e3,Sm=4e3,bn=new Map,gn=new Map,xr=new Set,Ws=new Map;function Nm(e){if(!e||typeof e!="object")return null;const t=e,r=t.status;if(r&&typeof r=="object")return r;const n=t.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return t}function Io(e,t){const r=Ws.get(e);!r||r.size===0||(Ws.delete(e),r.forEach(n=>n(t)))}function Cm(e,t){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),t);n.add(a)})}function nr(){const{sendCommand:e,sendData:t}=jt(),{injectEntries:r,getIdes:n}=Gs();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??wm,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(t&&!xr.has(a)){const p=qt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},x=>{const j=n(),b=j.find(T=>T.id===a),N=Fr(x.status,{daemonId:a,existingDaemon:b,existingEntries:j,timestamp:x.timestamp});N.length>0&&r(N),gn.set(a,Date.now()),Io(a,!0)});if(p.initialSendAccepted?xr.add(a):xr.delete(a),!(i!=null&&i.force)&&p.initialSendAccepted&&await Cm(a,jm))return}const d=await e(a,"get_status_metadata"),h=Nm(d);if(!h)return;const m=n(),w=m.find(p=>p.id===a),S=Fr(h,{daemonId:a,existingDaemon:w,existingEntries:m,timestamp:h.timestamp||Date.now()});S.length>0&&r(S,{authoritativeDaemonIds:[a]}),gn.set(a,Date.now()),Io(a,!0)})().finally(()=>{bn.delete(a)});return bn.set(a,f),f},[n,r,e,t])}function Im(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}function js(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:Je(e)||qe(e)?{agentType:Kt(e)}:e.streamSource==="agent-stream"?{agentType:Kt(e)}:t}function Js(e){return e?sr(e):""}function Rs(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Aa(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Am(e){const t=e instanceof Error?e.message:String(e||""),r=t.toLowerCase();return r.includes("still processing the previous prompt")?"Wait for the current reply to finish before sending another message.":r.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":r.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":r.includes("not running")?"Runtime is not available right now.":t||"Unable to send message right now."}const Mm=60,Tm=1e3;function nc(e={}){return e.isCliLike?Tm:Mm}function Lm(e={}){return nc(e)}const ar=60,Rm=1e3,Ma=12e4,Pm=new Set(["generating","waiting_approval","starting","streaming","working"]),Ao=new Map;function ac(e,t){return`${e}::${t}`}function sa(e=ar){return{liveMessages:[],cursor:oc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function ra(e){return ji(e)}function oc(e,t=ar){return{knownMessageCount:e.length,lastMessageSignature:ra(e[e.length-1]),tailLimit:t}}function br(e,t){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function _m(e,t){const r=Array.isArray(t.messages)?t.messages:[];switch(t.syncMode){case"noop":return e;case"append":return[...e,...r];case"replace_tail":{const n=Math.max(0,Math.min(Number(t.replaceFrom??e.length),e.length));return[...e.slice(0,n),...r]}case"full":return r;default:return r}}class Dm{constructor(t){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=t.manager||qt,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=sa(Math.max(0,t.tailLimit??ar))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);if(r!==this.snapshot.cursor.tailLimit){const n=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(t){const r=Array.isArray(t)?t:[];if(r.length===0)return;const n=r,a=oc(n,this.snapshot.cursor.tailLimit);br(this.snapshot.liveMessages)===br(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a},this.emit())}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await t(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},knownMessageCount:this.snapshot.cursor.knownMessageCount,lastMessageSignature:this.snapshot.cursor.lastMessageSignature,...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}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()},Rm))}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)}),this.transportSubscription.initialSendAccepted||this.scheduleSubscribeRetry())}disconnect(){var t;this.clearPendingSubscribeRetry(),(t=this.transportSubscription)==null||t.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(t=>t(this.snapshot))}handleUpdate(t){this.clearPendingSubscribeRetry();const r=typeof t.lastMessageSignature=="string"?t.lastMessageSignature:"",n=ra(this.snapshot.liveMessages[this.snapshot.liveMessages.length-1]);if(t.syncMode!=="full"&&r&&n===r){const u={knownMessageCount:Math.max(this.snapshot.cursor.knownMessageCount,Number(t.totalMessages||0)),lastMessageSignature:r,tailLimit:this.snapshot.cursor.tailLimit};this.snapshot.cursor.knownMessageCount===u.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===u.lastMessageSignature||(this.snapshot={...this.snapshot,cursor:u},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:u.knownMessageCount,lastMessageSignature:u.lastMessageSignature}));return}const a=_m(this.snapshot.liveMessages,t),i={knownMessageCount:a.length,lastMessageSignature:typeof t.lastMessageSignature=="string"?t.lastMessageSignature:ra(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 ic(e){const t=ac(e.daemonId,e.sessionId),r=Ao.get(t);if(r)return r.updateOptions(e),r;const n=new Dm(e);return Ao.set(t,n),n}function Em(e,t){return{...e,loadHistoryPage:t}}function $m(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Bm(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Pm.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=t.now??Date.now(),a=Math.max(0,Number(t.recentActivityMs??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 Km(e=Ma){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Om(e,t={}){const r=new Set,n=[];for(const a of e){if(!Bm(a,t))continue;const i=sr(a),c=a.sessionId||"";if(!i||!c)continue;const l=ac(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($m),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Wm(e,t){const{sendData:r,sendCommand:n}=jt(),a=(t==null?void 0:t.enabled)!==!1,i=sr(e),c=e.sessionId||"",l=rr(e)||c,u=`daemon:${i}:session:${c}`,f=Math.max(0,(t==null?void 0:t.tailLimit)??ar),d=o.useMemo(()=>!a||!i||!c?null:ic({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())||sa(f));o.useEffect(()=>{if(!d){m(sa(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 w=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(()=>Em(h,w),[w,h])}function Hm(e,t){const{sendData:r}=jt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??ar),i=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Ma)),c=Km(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(()=>Om(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||f.descriptors.length===0)return;const d=f.descriptors.map(h=>ic({...h,sendData:r,tailLimit:a}));return d.forEach(h=>h.retain()),()=>{d.forEach(h=>h.release())}},[f.signature,n,r,a])}function Fm(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Um(e){return Fm(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const zm=60;function na({activeConv:e,ideEntry:t,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 ye,ge,ve,z,F;const w=o.useRef(new Map),S=nr();tr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const p=St.useMemo(()=>Ms(e),[e.status,e.connectionState]),x=o.useMemo(()=>dm(e,t),[e,t]),j=o.useMemo(()=>{var Q;return ka((Q=x.targetEntry)==null?void 0:Q.providerControls,{hostIdeType:e.hostIdeType,providerType:x.providerType})},[e.hostIdeType,x.providerType,(ye=x.targetEntry)==null?void 0:ye.providerControls]),b=nc({isCliLike:x.isCli||x.isAcp}),N=Lm({isCliLike:x.isCli||x.isAcp}),T=Wm(e,{enabled:m&&!!e.sessionId,tailLimit:N}),[y,C]=o.useState(b),k=e.tabKey,v=T.historyMessages,g=T.hasMoreHistory,D=T.historyError,M=T.liveMessages.length>0?T.liveMessages:e.messages;o.useEffect(()=>{C(b)},[b,k]);const I=Math.max(0,M.length-y),P=Sa(e),K=sr(e),V=Um(e),L=Aa(e),R=a||L,G=!!L,[B,E]=o.useState(!1);o.useEffect(()=>{const Q=x.targetEntry;K&&(!Q||Q.providerControls===void 0||Q.controlValues===void 0)&&S(K,{minFreshMs:3e4}).catch(()=>{})},[K,x.isAcp,(ge=x.targetEntry)==null?void 0:ge.providerControls,(ve=x.targetEntry)==null?void 0:ve.controlValues,S]);const W=o.useCallback(async()=>{if(!B){if(M.length>y){C(Q=>Math.min(M.length,Q+zm));return}E(!0);try{await T.loadHistoryPage()}finally{E(!1)}}},[T,B,M.length,y]),{allMessages:J,receivedAtMap:be}=o.useMemo(()=>{const Q=I>0?M.slice(-y):M,ue=v.length===0?Q:[...v,...Q],te={};return ue.forEach((fe,ne)=>{const xe=`${e.tabKey}:${Kr(fe,ne)}`;let re=Im(fe)||w.current.get(xe)||0;re||(re=Date.now(),w.current.set(xe,re)),te[Kr(fe,ne)]=re}),{allMessages:ue,receivedAtMap:te}},[e.tabKey,I,v,M,y]),he=o.useMemo(()=>l.filter(Q=>Q.routeId===e.tabKey).sort((Q,ue)=>Q.timestamp-ue.timestamp),[l,e.tabKey]),de=o.useMemo(()=>{if(M.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((p.isGenerating||e.status==="streaming")&&E(!1),e.status==="not_monitored"&&V)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Ys,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ss,{size:14})," Open ",P," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&V)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Ii,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ss,{size:14})," Open ",P," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!B)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,V,i,c,B,M.length,P,p.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[f&&s.jsx(rc,{conversation:e,className:"chat-pane-meta-row"}),s.jsx(ru,{messages:J,actionLogs:he,agentName:Ns(e)||P||"Agent",userName:u,isCliMode:x.isCli||x.isAcp,isWorking:p.isGenerating,contextKey:e.tabKey,receivedAtMap:be,onLoadMore:W,isLoadingMore:B,hasMoreHistory:g,hiddenLiveCount:I,loadError:D??void 0,emptyState:de,scrollToBottomRequestNonce:d,isVisible:m}),s.jsx(sm,{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:(F=x.targetEntry)==null?void 0:F.controlValues,isActive:h,isCliTerminal:x.isCliTerminal}),!x.isCliTerminal&&s.jsx(Vi,{contextKey:e.tabKey,panelLabel:P,isSending:n,isBusy:G,statusMessage:R,onSend:r,isActive:h,showControlsToggle:j.length>0})]})}let cc=cs;function lc(){return cc()}class Vm{constructor(){Ge(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{var n;(n=this.listeners.get(t))==null||n.delete(r)}}emit(t,...r){var n;(n=this.listeners.get(t))==null||n.forEach(a=>a(...r))}}let dc=new Vm;class Gm{sendPtyInput(t,r,n){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,r){return!1}get(t){}onScreenshot(t,r){return()=>{}}onRuntimeEvent(t,r,n){return()=>{}}requestRuntimeSnapshot(t,r){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let at=new Gm;function qm(e){e.dashboardWS&&(dc=e.dashboardWS),e.connectionManager&&(at=e.connectionManager),e.useDaemonsHook&&(cc=e.useDaemonsHook)}const Ym=.5,Xm=1.25;function tt(e){return Sa(e)}function us(e){return Ji(e).join(" · ")}function uc(e){const t=Xi(e);return t||(e.title?e.title:us(e)||"No messages yet")}function mc(e,t){const{isReconnecting:r,isConnecting:n}=Ms(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function Jm(e,t){const r=["Chat",...Ji(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function ts(e){return mc(e)||us(e)}function Qm(e){return`${tt(e)} · ${uc(e)}`}function Zm(e){const t=Hr(e),r=t?Ze(t):Ns(e);return`${tt(e)} — ${r||"Agent"}`}function ef(e){return Ns(e)||"CLI"}function fc(e){return Yi(e)}function pc(e){return e?`Remote · ${tt(e)||e.workspaceName||"Session"}`:"Remote"}function tf({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var oe;cs();const{sendPtyInput:u}=jt(),[f,d]=o.useState(!1),h=o.useRef(!1);h.current=f;const[m,w]=o.useState("Runtime terminal unavailable"),[S,p]=o.useState(1),[x,j]=o.useState({width:0,height:0}),[b,N]=o.useState({width:0,height:0}),T=o.useRef(null),y=o.useRef(null),C=o.useRef(!1),k=o.useRef(!1),v=o.useRef(0),g=o.useRef(!1),D=o.useRef(""),M=o.useRef(null),I=o.useRef(!1),P=o.useRef(null),K=32*1024,V=()=>{var Y,X,ae,A;return((X=(Y=T.current)==null?void 0:Y.ownerDocument)==null?void 0:X.defaultView)||((A=(ae=y.current)==null?void 0:ae.ownerDocument)==null?void 0:A.defaultView)||window},L=Y=>{const X=V();return{ownerWindow:X,frameId:X.requestAnimationFrame(Y)}},R=()=>{const Y=P.current;if(Y){try{Y.ownerWindow.cancelAnimationFrame(Y.frameId)}catch{}P.current=null}},G=()=>{c&&P.current===null&&(P.current=L(()=>{ne()}))},B=e.tabKey,E=e.sessionId||"",W=e.daemonId||((oe=e.routeId)==null?void 0:oe.split(":")[0])||e.routeId||"",J=Aa(e),be=f?i||J:m,he=Ym,de=Xm,ye=.05,ge=()=>{const Y=b.width,X=b.height;if(!Number.isFinite(x.width)||x.width<=0||!Number.isFinite(x.height)||x.height<=0||!Number.isFinite(Y)||Y<=0||!Number.isFinite(X)||X<=0)return 1;const ae=x.width/Y,A=x.height/X;return Number(Math.min(de,Math.max(he,Math.min(ae,A))).toFixed(2))},ve=ge(),z=C.current&&S>ve,F=Number.isFinite(b.width)&&b.width>0?Math.max(x.width,Math.round(b.width*S)):x.width,Q=Number.isFinite(b.height)&&b.height>0?Math.max(x.height,Math.round(b.height*S)):x.height,ue=()=>{L(()=>{const Y=y.current;Y&&(Y.scrollLeft=0,Y.scrollTop=Y.scrollHeight-Y.clientHeight)})},te=()=>{var Y,X;v.current=0,g.current=!1,D.current="",M.current=null,I.current=!1,C.current||(k.current=!1,p(1)),P.current!==null&&R(),d(!1),w("Runtime terminal unavailable"),(X=(Y=r.current)==null?void 0:Y.reset)==null||X.call(Y)},fe=()=>{var Y,X;v.current=0,g.current=!1,D.current="",M.current=null,I.current=!1,P.current!==null&&R(),d(!0),w(""),(X=(Y=r.current)==null?void 0:Y.reset)==null||X.call(Y)},ne=()=>{var ae;if(P.current=null,!c)return;const Y=D.current;if(!Y)return;const X=Y.slice(0,K);D.current=Y.slice(X.length),(ae=r.current)==null||ae.write(X),D.current.length>0&&G()},xe=Y=>{Y&&(D.current+=Y,G())},re=(Y,X=0,ae,A)=>{var H,ce,me,we;X>0&&v.current>=X||X===0&&g.current||(v.current=X,d(!0),w(""),typeof ae=="number"&&typeof A=="number"&&ae>0&&A>0&&((ce=(H=r.current)==null?void 0:H.resize)==null||ce.call(H,ae,A)),D.current="",(we=(me=r.current)==null?void 0:me.reset)==null||we.call(me),Y&&xe(Y))};o.useEffect(()=>{te()},[E]),o.useEffect(()=>{var X;if(!E)return;const Y=((X=at.onRuntimeEvent)==null?void 0:X.call(at,E,ae=>{if(!(!ae||ae.sessionId!==E)){if(ae.type==="runtime_snapshot"){if(!c){M.current={text:ae.text||"",seq:ae.seq||0,cols:ae.cols,rows:ae.rows};return}re(ae.text||"",ae.seq||0,ae.cols,ae.rows);return}if(ae.type==="session_output"){g.current=!0,typeof ae.seq=="number"&&(v.current=Math.max(v.current,ae.seq)),h.current||d(!0),h.current||w(""),typeof ae.data=="string"&&xe(ae.data);return}if(ae.type==="session_cleared"){if(!c){I.current=!0,D.current="",M.current=null;return}fe();return}if(ae.type==="session_io_error"){const A=typeof ae.error=="string"&&ae.error?ae.error:typeof ae.reason=="string"&&ae.reason?ae.reason:"unknown error";d(!1),w(`Runtime input failed: ${A}`);return}}},W))||(()=>{});return()=>{Y()}},[W,E,r,c]);const le=async()=>{var Y;if(!(!W||!E)){w("Loading runtime terminal...");try{const X=await((Y=at.requestRuntimeSnapshot)==null?void 0:Y.call(at,W,E));X&&X.success===!1&&(d(!1),w(`Runtime terminal unavailable: ${X.error}`))}catch(X){d(!1),w(`Runtime terminal unavailable: ${(X==null?void 0:X.message)||String(X)}`)}}};return o.useEffect(()=>{var X,ae;if(!E)return;W&&((X=at.getState)==null?void 0:X.call(at,W))==="connected"&&le();const Y=(ae=at.onStateChange)==null?void 0:ae.call(at,(A,H)=>{A!==W||H!=="connected"||le()});return()=>{Y==null||Y()}},[W,E,r]),o.useEffect(()=>{t&&te()},[t,B,r]),o.useEffect(()=>{var A,H;const Y=T.current,X=(H=(A=Y==null?void 0:Y.ownerDocument)==null?void 0:A.defaultView)==null?void 0:H.ResizeObserver;if(!Y||!X)return;const ae=new X(ce=>{const me=ce[0];if(!me)return;const{width:we,height:_e}=me.contentRect;j(Ae=>{const Ke=Math.round(we),Fe=Math.round(_e);return Ae.width===Ke&&Ae.height===Fe?Ae:{width:Ke,height:Fe}})});return ae.observe(Y),()=>ae.disconnect()},[]),o.useEffect(()=>{if(C.current)return;const Y=ge();!Number.isFinite(Y)||Y<=0||p(X=>k.current?Y<X-ye?Y:X:(k.current=!0,Y))},[b.height,b.width,x.height,x.width]),o.useEffect(()=>{z&&ue()},[z,Q,F]),o.useEffect(()=>{var X;if(!c)return;I.current&&(I.current=!1,fe());const Y=M.current;Y&&(M.current=null,re(Y.text,Y.seq,Y.cols,Y.rows)),W&&E&&((X=at.getState)==null?void 0:X.call(at,W))==="connected"&&le(),D.current&&P.current===null&&G(),L(()=>{var ae;(ae=r.current)==null||ae.bumpResize()})},[W,c,E]),o.useEffect(()=>()=>{P.current!==null&&R()},[]),o.useEffect(()=>{const Y=A=>{var ce;const H=A.detail;H!=null&&H.sessionId&&H.sessionId!==E||f&&((ce=r.current)==null||ce.bumpResize())},X=V(),ae=X===window?[window]:[window,X];for(const A of ae)A.addEventListener("adhdev:fit-cli-terminal",Y);return()=>{for(const A of ae)A.removeEventListener("adhdev:fit-cli-terminal",Y)}},[f,E,r]),s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:T,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{C.current=!0,p(Y=>{const X=Math.max(ve,Number((Y-.1).toFixed(2)));return X>ve&&ue(),X})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{C.current=!0,p(Y=>{const X=Math.min(de,Number((Y+.1).toFixed(2)));return X>ve&&ue(),X})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:y,className:z?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:F>0?`${F}px`:"100%",height:Q>0?`${Q}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:b.width>0?`${b.width}px`:"100%",height:b.height>0?`${b.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:S},children:s.jsx(_i,{ref:r,readOnly:!f||!c,sizingMode:"measured",onViewportMetrics:N,onInput:Y=>{!f||(u==null||u(W,E,Y))}})})})}),!f&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:m})]}),s.jsx(Vi,{contextKey:e.tabKey,panelLabel:tt(e),isSending:a,isBusy:!f||!!J,statusMessage:be,onSend:async Y=>!f||J?!1:n(Y),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const sf=2500;function rf(e){return e==="disconnected"||e==="reconnecting"}function nf({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=sf}){const i=rf(e),[c,l]=o.useState(()=>!i||a<=0),u=o.useRef(!1);o.useEffect(()=>{if(!i){l(!1);return}if(u.current=!1,a<=0){u.current=!0,l(!0);return}l(!1);const j=setTimeout(()=>{u.current=!0,l(!0)},a);return()=>clearTimeout(j)},[a,i]);const f=i?c:e==="offline"||e==="auth_failed",d=o.useMemo(()=>!t||e!=="connected"?!1:a<=0||u.current,[a,t,e]),h=e==="auth_failed"?"red":e==="offline"?"orange":"accent",m={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))"},w={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},S={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},p="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",x={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[f&&s.jsx("div",{className:p,style:x,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-4 py-3 text-[13px] font-semibold flex items-center gap-2.5 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:m[h],border:w[h],color:S[h]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center",children:[e==="offline"&&"Network offline — waiting for connection...",e==="disconnected"&&"Reconnecting to server...",e==="reconnecting"&&"Reconnecting to server...",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),n&&e!=="auth_failed"&&s.jsx("button",{type:"button",className:"ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:n,disabled:e==="offline",children:"Reconnect now"})]})}),d&&s.jsx("div",{className:p,style:x,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function af({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=o.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=o.useState(!1);if(o.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!t||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",u=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!0)};return s.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[l," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:u,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Ta({mode:e,onChange:t,compact:r=!1}){const n=r?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?s.jsx(ga,{size:n}):s.jsx(Ft,{size:n})})}const $t="New session",hc="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 of({wsStatus:e,isConnected:t,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),i=a.filter(l=>l==="connected").length,c=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&c>0&&i===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:t?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function Mo({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function To({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=Jr(e.updatedAt),l=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),i()},children:"Delete"})]})]})}function cf({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:u,onHideConversation:f,hiddenConversations:d=[],onShowConversation:h,onShowAllHidden:m,onResetPanelsToMain:w,inboxOpen:S,onInboxOpenChange:p,hiddenOpen:x,onHiddenOpenChange:j,onOpenNewSession:b,actionShortcuts:N,notifications:T,notificationUnreadCount:y,onOpenNotification:C,onMarkNotificationRead:k,onMarkNotificationUnread:v,onDeleteNotification:g}){const{ides:D,p2pStates:M={}}=cs(),I=!!e&&Je(e)&&!qe(e),P=!!e&&qe(e),K=l||(e?Gi(e)?"terminal":"chat":null),[V,L]=o.useState(!1),R=o.useRef(null),G=o.useRef(null),B=D.filter(z=>z.type==="adhdev-daemon"),E=of({wsStatus:t,isConnected:r,daemonCount:B.length,p2pStates:M}),W=E.subtitle,J=E.tone==="connected"?"#22c55e":E.tone==="limited"?"#eab308":"#ef4444",be=E.tone==="connected"?"0 0 4px #22c55e80":E.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",he=o.useMemo(()=>T.filter(z=>!z.readAt),[T]),de=o.useMemo(()=>T.filter(z=>!!z.readAt),[T]),ye=o.useMemo(()=>he.slice(0,9),[he]),ge=y;o.useEffect(()=>{if(!S)return;const z=F=>{var Q;(Q=R.current)!=null&&Q.contains(F.target)||p(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[S,p]),o.useEffect(()=>{if(!x)return;const z=F=>{var Q;(Q=G.current)!=null&&Q.contains(F.target)||j(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[x,j]),o.useEffect(()=>{if(!x&&!S)return;const z=F=>{if(!F.altKey)return;const Q=F.code.match(/^Digit([1-9])$/);if(!Q)return;const ue=Number(Q[1])-1,te=x?d[ue]:void 0,fe=S?ye[ue]:void 0;if(!(!te&&!fe)){if(F.preventDefault(),F.stopPropagation(),te){h==null||h(te),j(!1);return}fe&&(C(fe),p(!1))}};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[d,x,S,ye,j,p,C,h]);const ve=z=>{if(!z)return;const F=n.find(Q=>Q.tabKey===z);F&&(f==null||f(F))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Ft,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?tt(e):"Dashboard"}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:J,boxShadow:be}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[s.jsx("span",{title:E.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:J,boxShadow:be}}),W&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",W]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:$t,"aria-label":$t,children:s.jsx(Ti,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(I||P||!qe(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:us(e)||tt(e),children:tt(e)}),(I||P)&&c&&s.jsxs(s.Fragment,{children:[I&&u&&K&&s.jsx(Ta,{mode:K,onChange:u,compact:!0}),s.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:s.jsx(wt,{size:14})})]}),!qe(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(ba,{size:14})}),!I&&!qe(e)&&s.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Ct,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:R,children:[s.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 F=z.dataTransfer.getData("text/tab-key");z.preventDefault(),L(!1),ve(F)},children:[s.jsxs("button",{type:"button",onClick:()=>j(!x),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${N!=null&&N.toggleHiddenTabs?` (${N.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Ai,{size:16}),d.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),x&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(Mo,{value:N==null?void 0:N.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[w&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:w,children:"Reset panels"}),d.length>0&&m&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{m(),j(!1)},children:"Restore all"})]})]}),e&&f&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>f(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(Mo,{value:N==null?void 0:N.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:tt(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(z=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(z),j(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:tt(z)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(z)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(z)+1]}):null,us(z)]})]},z.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!S),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Xr,{size:16}),ge>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ge})]}),S&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[he.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),he.map(z=>s.jsx(To,{notification:z,shortcutIndex:ye.indexOf(z)>=0?ye.indexOf(z)+1:void 0,onOpen:()=>C(z),onMarkRead:()=>k(z.id),onMarkUnread:()=>v(z.id),onDelete:()=>g(z.id)},z.id))]}),de.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),de.map(z=>s.jsx(To,{notification:z,onOpen:()=>C(z),onMarkRead:()=>k(z.id),onMarkUnread:()=>v(z.id),onDelete:()=>g(z.id)},z.id))]}),T.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function ht(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function lf(e,t){return String(e||"")!==String(t||"")}function df(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),i=!!t.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(u=>String(u||"").toLowerCase()).join(`
|
|
30
|
-
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!
|
|
31
|
-
`).includes(a)))}function uf(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const i=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function xc(e,t={}){return uf(df(e,t),t.sortMode||"recent")}function Ur(e){return e?"Resume saved history":"Start fresh"}function La(e){return e?"Resuming saved history…":"Starting fresh…"}function mf(){return"Start fresh"}function bc(e,t=!1){return e==="cli"?Ur(t):e==="ide"?"Start IDE":"Start ACP session"}function gc(e,t=!1){return e==="cli"?La(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function ff(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function pf(){return"Open saved history"}function hf(){return"Saved History"}function Ra(){return"Use saved history when you want continuity in the same provider conversation."}function xf(){return"No saved history found yet."}function bf(){return"Refresh saved history"}function gf(){return"Refreshing saved history…"}function ss(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}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 Pa(e){return`Resume saved history with ${e}?`}function _a(){return"Review or change the target workspace before resuming saved history."}function yf(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 Da({activeConv:e,ides:t,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:w}){var v;const S=t.find(g=>g.id===e.routeId),p=(S==null?void 0:S.chats)||[],x=(v=S==null?void 0:S.activeChat)==null?void 0:v.id,j=Je(e)&&!qe(e),[b,N]=o.useState(()=>ht()),T=l||b,y=g=>{if(u){u(g);return}N(g)},C=o.useMemo(()=>xc(a,{textQuery:T.textQuery,workspaceQuery:T.workspaceQuery,modelQuery:T.modelQuery,resumableOnly:T.resumableOnly,sortMode:T.sortMode}),[T.modelQuery,T.resumableOnly,T.sortMode,T.textQuery,T.workspaceQuery,a]),k=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:f,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:j?hf():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Zm(e)}),j&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ra()})]}),s.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:s.jsx(wt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!j&&s.jsx("button",{onClick:d,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),j?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:T.textQuery,onChange:g=>y({...T,textQuery:g.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:T.workspaceQuery,onChange:g=>y({...T,workspaceQuery:g.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:T.modelQuery,onChange:g=>y({...T,modelQuery:g.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:T.sortMode,onChange:g=>y({...T,sortMode:g.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:T.resumableOnly,onChange:g=>y({...T,resumableOnly:g.target.checked})}),"Resume-ready only"]})]}),C.map(g=>{const D=e.providerSessionId===g.providerSessionId,M=D||!g.canResume||!!c;return s.jsxs("button",{type:"button",onClick:()=>{M||!w||w(g)},disabled:M,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${D?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${M?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${D?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:g.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:g.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:yf(g.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:g.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[g.workspace||"Workspace unknown",ds(g.summaryMetadata)?` · ${ds(g.summaryMetadata)}`:"",g.messageCount>0?` · ${g.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:D?"ACTIVE":g.canResume?c===g.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},g.id)})]}):p.map(g=>s.jsxs("div",{onClick:()=>{h(e.routeId,g.id),f()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===g.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${x===g.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:g.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[g.id.substring(0,12),"..."]}),x===g.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},g.id)),(j&&!i&&C.length===0||!j&&p.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Dd,{size:32})}),s.jsx("div",{className:"text-[13px]",children:j?a.length>0?"No saved history matches these filters.":xf():"No recent chat sessions found."})]}),j&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:gf()})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:m,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(er,{size:13})," ",j?bf():"Refresh History"]})})})]})]});return typeof document>"u"?k:zs.createPortal(k,document.body)}const Lo={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Done"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Attention"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Update"}};function yc({toasts:e,onDismiss:t,onClickToast:r}){return s.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const a=Lo[n.type]||Lo.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=n.actions)!=null&&i.length||r&&r(n)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(wt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:l=>{l.stopPropagation(),i.onClick(),t(n.id)},children:i.label},c))})]})]},n.id)})})}const vf=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function wf(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function jf(e){return e.sessionId||e.instanceId||e.agentType}function yn(e,t){return e||t}function vc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Mt(r,{fallbackId:r.id}));return t}function wc(e,t={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=t.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Ea(e,t={}){return kf(e,wc(e,t))}function kf(e,t={}){var d,h,m,w,S,p;const r=[],n=t.machineName,a=t.connectionState,i=wf(e),c=ju(e.type,{agentName:e.cliName}),l=Je(e)||qe(e)?c:Ze(e.type),u=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var j,b;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||Ze(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((j=x.activeChat)==null?void 0:j.messages)||[],activeModal:((b=x.activeChat)==null?void 0:b.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,surfaceHidden:x.surfaceHidden}}):[],f=vf(e);if(f){const x=e.sessionId||e.instanceId,j=c,b=(d=e.activeChat)==null?void 0:d.activeModal,N=b&&Array.isArray(b.buttons)&&b.buttons.length>0,T=bt((h=e.activeChat)==null?void 0:h.status,{activeModal:(m=e.activeChat)==null?void 0:m.activeModal})||bt((S=(w=e.agents)==null?void 0:w[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 k=(p=e.activeChat)==null?void 0:p.id,v=e.chats;if(k&&Array.isArray(v)&&v.length>0){const I=v.find(P=>P.id===k||P.id&&String(P.id)===String(k));I!=null&&I.title&&String(I.title).trim()&&(C=String(I.title).trim())}const g=(Je(e)||qe(e),e.type),D=(Je(e)||qe(e))&&vo(C,j,g)?"":C,M=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:j,agentType:g,status:T,title:D,messages:M,resume:e.resume,hostIdeType:!Je(e)&&!qe(e)?e.type:void 0,workspaceName:i,displayPrimary:D||i||(Je(e)?e.mode==="chat"?j:"Terminal":j),displaySecondary:l,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:N?b.buttons:void 0,modalMessage:N?b.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 j=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,b=ku(x),N=jf(x),T=`${e.id}:${N}`,y=x.title&&String(x.title).trim()||"",C=vo(y,x.agentName,x.agentType)?"":y,k=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||k.length>0||j||C||!["idle","panel_hidden","disconnected","not_monitored"].includes(b))&&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:b,title:C,messages:k,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:j?x.activeModal.buttons:void 0,modalMessage:j?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:yn(x.sessionId||x.instanceId,T),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 Sf(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function jc(e,t){const r=Sf(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const kc=[{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:"🏄"}],Sc=[{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:"🧩"}],Nc=[{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:"🟠"}],Nf=kc,Cf=Sc,If=Nc;function ms(...e){return Yl(Xl(e))}function Af({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:ms("dashboard-header",i),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function Cc({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Af,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ms("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const aa="adhdev:themechange";function Mf(){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"?Mf():e}function Ic(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Lr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(aa,{detail:{preference:e,theme:t}}))}function Tf(){const e=xs(),t=bs(e);Ic(t),Lr(e,t)}function $a(){const[e,t]=o.useState(xs),[r,n]=o.useState(()=>bs(xs()));o.useEffect(()=>{Ic(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;t(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);t(f),n(d)};return window.addEventListener(aa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(aa,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=bs(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Lr(c,l)},[]),i=o.useCallback(()=>{t(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 Ro={dark:"Dark",light:"Light",system:"System"};function Lf({collapsed:e}){const{preference:t,cycleTheme:r}=$a(),n=t==="dark"?s.jsx($d,{size:16}):t==="light"?s.jsx(Ed,{size:16}):s.jsx(Bd,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Ro[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Ro[t]})]})}function vn(e,t){return e?typeof e=="function"?e(t):e:null}function Rf({children:e,brand:t,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}}),w=()=>d(!0),S=()=>d(!1),p=()=>{m(N=>{const T=!N;try{localStorage.setItem(u,T?"1":"0")}catch{}return T})},x=o.useMemo(()=>({collapsed:h,mobileMenuOpen:f,openMobileMenu:w,closeMobileMenu:S,toggleCollapsed:p}),[h,f]),j=N=>`nav-item${N.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${N.className?` ${N.className}`:""}`,b=N=>s.jsxs("div",{className:j(N),id:`nav-${N.id}`,onClick:()=>{N.onSelect(),S()},title:h?N.title??(typeof N.label=="string"?N.label:void 0):N.title,children:[s.jsx("span",{className:"nav-icon",children:N.icon}),!h&&N.label]},N.id);return s.jsxs("div",{className:`app-layout${f?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:w,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),f&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:S,onKeyDown:N=>N.key==="Escape"&&S()}),s.jsxs("aside",{className:`sidebar ${f?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:vn(t,x)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:S,children:s.jsx(wt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),n.map(N=>s.jsxs("div",{className:N.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&N.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:N.title}):null,N.items.map(b)]},N.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),vn(i,x),s.jsx(Lf,{collapsed:h}),vn(c,x)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function Nt({title:e,icon:t,description:r,accentColor:n,className:a,children:i}){return s.jsxs("div",{className:ms("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function Ac({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ms("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Pf={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"},_f={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function gr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ms("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Pf[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:_f[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const Df={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"},Ef={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function $f({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ms("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Df[e],r),children:[s.jsx("span",{className:ms("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Ef[e])}),n]})}function Qt({label:e,description:t,checked:r,disabled:n,onChange:a,extra:i}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,s.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Bf({onPrefChange:e}){const[t,r]=Pu(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>i("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ct,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>i("browserNotifications",c)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{Ui().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Od,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ys,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function zr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Kf(e,t){const r=zr(e),n=zr(t);if(!r||!n)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function Mc(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function Hs(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Kf(r,t)>=0)return!1;const n=zr(r),a=zr(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Of(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function wn(e,t){return e instanceof Error?e.message:t}function Wf({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Ac,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:t||"Install ADHDev on a machine and sign in to connect it here."}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>s.jsx(Ff,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Po({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return zs.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:i,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function Hf(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Nf,...Cf,...If].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function Ff({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var K,V;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[f,d]=o.useState(null),[h,m]=o.useState("idle"),[w,S]=o.useState(""),p=e.version||null,x=((K=e.machine)==null?void 0:K.platform)||((V=e.system)==null?void 0:V.platform)||"",j=Mt(e,{fallbackId:e.id}),b=x==="win32"?"🪟":x==="darwin"?"🍎":"🐧",N=t.filter(L=>L.daemonId===e.id&&L.transport==="cdp-page"),T=t.filter(L=>L.daemonId===e.id&&L.transport==="pty"),y=t.filter(L=>L.daemonId===e.id&&L.transport==="acp"),C=e.p2p,k=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const L=Of(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"))}}},v=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"))}}},g=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"))}}},D="0.9.23",M=Mc(e,D),I=Hs(e,D),P=N.length+T.length+y.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:b}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:j}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),p&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${M?"":"bg-bg-secondary"}`,style:M?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!M&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&M&&s.jsx("button",{onClick:k,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${D}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${I?"↑ Update now":`↑ Update${` to v${D}`}`}`}),n&&s.jsx("button",{onClick:()=>d("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>d("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx($f,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[C&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${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}),s.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&&s.jsxs("span",{className:"text-text-muted/60",children:["(",C.peers," peer",C.peers!==1?"s":"",")"]})]}),C&&P>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),P>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(L=>{const R=Hf(L.type),G=L.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:R.icon}),s.jsx("span",{children:R.name}),G!==void 0&&s.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)}),T.map(L=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:L.cliName||"CLI"})]},L.id)),y.map(L=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:L.cliName||"ACP"})]},L.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||w)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-red-400":i==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:w||l})]}),f==="disconnect"&&s.jsx(Po,{title:"🔌 Disconnect Machine",message:`Disconnect "${j}" from ADHDev?
|
|
29
|
+
`)))return}const G=(c==null?void 0:c[R.id])??p[R.id];try{const K=await w(R.invokeScript),E=pr(K);if(E&&!E.ok||hr(K))throw new Error((E==null?void 0:E.error)||Ps(K)||`Could not run ${R.label}`);E&&g(R,G??!0,E)}catch(K){D(R,G);const E=K instanceof Error?K.message:`Could not run ${R.label}`;lt.showToast(E,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${f}33`,background:`${f}12`,color:f},children:a}),A.map(R=>{const G=String(h[R.id]||""),K=om(R,j,G),E=N===R.id,W=y===R.id,J=Tr(R,j),be="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 s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${f}55`:"var(--border-default)",background:E?`${f}10`:"var(--surface-tertiary)",color:G?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void I(R),title:R.label,children:[R.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:W?"Loading…":K||R.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),E&&J.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>T(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:R.label}),J.map(xe=>s.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[12px] transition-colors",style:{background:xe.value===G?`${f}14`:"transparent",color:xe.value===G?"var(--text-primary)":"var(--text-secondary)",borderLeft:xe.value===G?`2px solid ${f}`:"2px solid transparent"},title:xe.description||xe.label,onMouseEnter:de=>{de.currentTarget.style.background=`${f}10`},onMouseLeave:de=>{de.currentTarget.style.background=xe.value===G?`${f}14`:"transparent"},onClick:()=>void P(R,xe.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:xe.label}),xe.value===G&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:f},children:"✓"})]},xe.value))]})]})]},R.id);case"cycle":return s.jsxs("button",{type:"button",className:`${be} 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(xe=>xe.label).join(" → ")}`,children:[R.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:K||R.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},R.id);case"toggle":return s.jsxs("button",{type:"button",className:`${be} 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&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),R.label]},R.id);case"action":return s.jsxs("button",{type:"button",className:`${be} 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&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),s.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 s.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:G?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:G?`${R.label}: ${G}`:R.label})]},R.id);default:return null}})]})})}function lm({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:d}){const{isVisible:f}=Fi(),u=ka(l,{hostIdeType:a,providerType:i});return!e||t||u.length===0||!f?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(cm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:u,controlValues:d})})}function dm({hasDraft:e,isBusy:t=!1}){return!e||t}const Ji=o.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:d=!1,animateVisibility:f=!0}){const u=o.useRef(null),[x,m]=o.useState(""),{isVisible:v,toggleVisibility:S}=Fi();o.useEffect(()=>{m("")},[t]),o.useEffect(()=>{var h;l&&((h=u.current)==null||h.focus({preventScroll:!0}))},[t,l]);const p=async()=>{const h=x.trim();if(!h||a)return;await c(h)!==!1&&m("")};return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",f?"transition-all duration-200 ease-out":""].filter(Boolean).join(" "),style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[s.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[d&&s.jsx("button",{type:"button",onClick:S,"aria-label":v?"Hide controls":"Show controls","aria-pressed":v,title:v?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("input",{ref:u,type:"text",placeholder:i||`Send message to ${r}...`,value:x,onChange:h=>m(h.target.value),onPaste:h=>{const j=h.clipboardData.getData("text");j&&m(b=>b+j),h.preventDefault()},onKeyDown:h=>{if(h.key==="Enter"){if(h.nativeEvent.isComposing){h.preventDefault();return}h.preventDefault(),p()}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),s.jsx("button",{onClick:()=>{p()},disabled:dm({hasDraft:!!x.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${x.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:x.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:x.trim()?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),Qe=e=>e.transport==="pty",Ls=(e,t)=>Qe(e)?e.mode||"terminal":"chat",Qi=(e,t)=>Qe(e)&&Ls(e)==="terminal",Xe=e=>e.transport==="acp";function Vt(e){return e.streamSource!=="agent-stream"}function fs(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Zi(e){return e.machineName||""}function Rs(e){return fs(e)}function Kt(e){return e.agentType||""}function Hr(e){return e.hostIdeType||""}function Sa(e){return e.displayPrimary||e.agentName||"Agent"}function ec(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function um(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function No(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function mm(e){return No(e==null?void 0:e.receivedAt)||No(e==null?void 0:e.timestamp)||0}function tc(e){const t=um(e),r=Ss(t==null?void 0:t.content),n=mm(t),a=Ss(e.lastMessagePreview),i=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0;return a&&!r?a:r&&!a?r:a&&r&&i>0&&n>0&&i>n?a:r||a||""}function fm(e){return tc(e)||e.displaySecondary||""}function sc(e){return[e.displaySecondary,Zi(e)].filter(Boolean)}function Cs(e){return e.agentName||tt(Kt(e))}function pm(e){var t,r;if(!Vt(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return tt(Hr(e)||Kt(e))}function rc(e){return Vt(e)?e.sessionId:e.nativeSessionId}function Co(e){return Vt(e)?"native":e.tabKey}function hm(e){return e.sessionId}function xm(e,t){if(t)return Vt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function bm(e,t){const r=Kt(e),n=Vt(e),a=Qe(e)||Xe(e),i=n?a?Cs(e)||(t==null?void 0:t.cliName)||tt(Hr(e)||r):t!=null&&t.type?tt(t.type):tt(Hr(e)||r):Cs(e);return{isNativeConversation:n,isCli:Qe(e),isAcp:Xe(e),isCliTerminal:Qi(e),providerType:r,displayLabel:i,targetEntry:xm(e,t)}}function gt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ft(e,t){const r=gt(t);return r?`${e}:${r}`:void 0}function zt(e,t,r){const n=Ft(t,r),a=gt(r);n&&e.push(n),a&&e.push(a)}function gs(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function nc(e){return gt(e.providerSessionId)||gt(e.sessionId)||gt(e.tabKey)||gt(e.routeId)}function Na(e){return gs([gt(e.providerSessionId),gt(e.sessionId)])}function ws(e){const t=[];return zt(t,"provider",e.providerSessionId),zt(t,"session",e.sessionId),zt(t,"tab",e.tabKey),zt(t,"route",e.routeId),gs(t)}function gm(e){const t=[];return gt(e.providerSessionId)?(zt(t,"provider",e.providerSessionId),gs(t)):gt(e.sessionId)?(zt(t,"session",e.sessionId),gs(t)):gt(e.tabKey)?(zt(t,"tab",e.tabKey),gs(t)):gt(e.routeId)?(zt(t,"route",e.routeId),gs(t)):[]}function Ca(e){return Ft("provider",e.providerSessionId)||Ft("session",e.sessionId)||Ft("tab",e.tabKey)||Ft("route",e.routeId)||"unknown:"}function nr(e){return Na(e)[0]}function ym(e){const t=gt(e.providerSessionId),r=gt(e.sessionId),n=gt(e.tabKey),a=gt(e.routeId),i=[Ft("provider",t),Ft("session",r),Ft("tab",n),Ft("route",a)].filter(d=>typeof d=="string"),c=ws({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=Ca({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:nc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:nr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function Zn(e,t){const r=ym(e);return gm(t).some(n=>r.lookupKeys.includes(n))}function Io(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function es(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],r=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,n=Io(t==null?void 0:t.receivedAt)||Io(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function ea(e,t=0){return es(e)||e.lastUpdated||t||0}function ac(e){return es(e)||e.lastUpdated||0}function oc(e,t,r=ac){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(t.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(t.displaySecondary);return c!==0?c:e.tabKey.localeCompare(t.tabKey)}function ta(e){var r;const t=bt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function vm(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!ta(e)&&!e.title.trim()}function wm(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(ta(r))-Number(ta(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:oc(t,r)})[0]||null}function _t(e,t){const r=e.filter(c=>c.routeId===t);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,a=r.filter(c=>c.streamSource==="agent-stream"),i=wm(a);return n?i&&vm(n)?i:n:i||r[0]||null}function Gt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ia(e){return nr(e)||e.tabKey||e.routeId||null}function ic(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(t)return t;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=_t(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?Ia(a):null}function cc({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=As(),c=fs(e),l=Zi(e),d=e.transport==="cdp-page"||e.transport==="cdp-webview",f=e.streamSource==="agent-stream"&&!!e.agentName,u=!f&&(e.transport==="pty"||e.transport==="acp"),x=Cs(e),m=pm(e),v=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),S=o.useCallback(()=>{if(r){r();return}const p=Ia(e);p&&i(Gt(p))},[e,i,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:m,children:[s.jsx(Nt,{size:12}),s.jsx("span",{children:m})]}):s.jsxs("span",{className:"conversation-meta-chip",title:m,children:[s.jsx(Nt,{size:12}),s.jsx("span",{children:m})]})),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Js,{size:12}),s.jsx("span",{children:x})]}),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Js,{size:12}),s.jsx("span",{children:x})]}),l&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:v,title:l,children:[s.jsx(ls,{size:12}),s.jsx("span",{children:l})]}):s.jsxs("span",{className:"conversation-meta-chip",title:l,children:[s.jsx(ls,{size:12}),s.jsx("span",{children:l})]}))]})}function xn(e,t){return`${e}:${t}`}function jm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function _s(e,t){jm()&&console.debug(`[subscription-manager] ${e}`,t)}class km{constructor(){Ge(this,"active",new Map);Ge(this,"retryTimers",new Map)}subscribe(t,r,n,a,i){var u;const c=xn(n.topic,n.key),l=this.active.get(c);let d=!0;if(l)l.handlers.add(a),l.lastUpdate&&a(l.lastUpdate);else{const x={daemonId:r,request:n,handlers:new Set([a])};this.active.set(c,x),_s("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(i!=null&&i.retryIntervalMs)&&this.scheduleRetry(c,t,i.retryIntervalMs)}const f=()=>{var v;this.clearRetry(c);const x=this.active.get(c);if(!x||(x.handlers.delete(a),x.handlers.size>0))return;this.active.delete(c);const m={type:"unsubscribe",topic:n.topic,key:n.key};_s("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(v=t.sendData)==null||v.call(t,r,m)};return f.initialSendAccepted=d,f}publish(t){const r=xn(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,ks.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),n.handlers.forEach(a=>{a(t),ks.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,r,n){const a=xn(t,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(t){var r;_s("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=t.sendData)==null||r.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,r){var a;const n=Array.from(this.active.values()).filter(i=>i.daemonId===t);_s("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}scheduleRetry(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var l;this.retryTimers.delete(t);const i=this.active.get(t);if(!i)return;const c=((l=r.sendData)==null?void 0:l.call(r,i.daemonId,i.request))??!1;_s("subscribe_retry",{id:t,accepted:c,topic:i.request.topic,key:i.request.key}),c||this.scheduleRetry(t,r,n)},n);this.retryTimers.set(t,a)}clearRetry(t){const r=this.retryTimers.get(t);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(t))}}const qt=new km;function Sm(e,t){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===t&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker});for(const i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function Nm(e){const t=[],r=new Map;for(const n of e)if(n.parentId){const a=r.get(n.parentId)||[];a.push(n),r.set(n.parentId,a)}else t.push(n);return{topLevel:t,childrenByParent:r}}function Fr(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=t,l=c||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:f,childrenByParent:u}=Nm(d),x=Sm(i,n),m=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,v=f.filter(h=>h.kind==="workspace"&&h.transport==="cdp-page"),S=f.filter(h=>h.kind==="agent"&&h.transport==="pty"),p=f.filter(h=>h.kind==="agent"&&h.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:v.some(h=>!!h.cdpConnected)});for(const h of v){const j=x.get(h.id),b=Ws(h,j),N=(u.get(h.id)||[]).map(T=>Ws(T,x.get(T.id)));r.push({id:`${n}:ide:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,status:b.cdpConnected?"online":"detected",daemonId:n,instanceId:h.id,workspace:b.workspace,terminals:0,childSessions:N,agents:N.map(T=>({id:T.id,name:T.providerName||T.providerType,type:T.providerType,status:T.status})),activeChat:b.activeChat,chats:[],cdpConnected:b.cdpConnected,...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l})}for(const h of S){const j=x.get(h.id),b=Ws(h,j);r.push({id:`${n}:cli:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:h.id,cliName:b.providerName||b.providerType,mode:b.mode||(j==null?void 0:j.mode)||"terminal",workspace:b.workspace||"",activeChat:b.activeChat,...b.resume!==void 0&&{resume:b.resume},...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isCli:!0})}for(const h of p){const j=x.get(h.id),b=Ws(h,j);r.push({id:`${n}:acp:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:h.id,cliName:b.providerName||b.providerType,mode:"chat",workspace:b.workspace||"",activeChat:b.activeChat,...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const Cm=15e3,Im=15e3,Mm=6e4,Am=1200,Mo=12,Tm=8e3,Lm=4e3,bn=new Map,gn=new Map,xr=new Set,Us=new Map;function Rm(e){if(!e||typeof e!="object")return null;const t=e,r=t.status;if(r&&typeof r=="object")return r;const n=t.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return t}function Ao(e,t){const r=Us.get(e);!r||r.size===0||(Us.delete(e),r.forEach(n=>n(t)))}function Pm(e,t){return new Promise(r=>{const n=Us.get(e)||new Set;Us.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&Us.delete(e),r(c)},i=setTimeout(()=>a(!1),t);n.add(a)})}function ar(){const{sendCommand:e,sendData:t}=wt(),{injectEntries:r,getIdes:n}=Ys();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 d=bn.get(a);if(d)return d;const f=(async()=>{if(t&&!xr.has(a)){const p=qt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},h=>{const j=n(),b=j.find(T=>T.id===a),N=Fr(h.status,{daemonId:a,existingDaemon:b,existingEntries:j,timestamp:h.timestamp});N.length>0&&r(N),gn.set(a,Date.now()),Ao(a,!0)});if(p.initialSendAccepted?xr.add(a):xr.delete(a),!(i!=null&&i.force)&&p.initialSendAccepted&&await Pm(a,Am))return}const u=await e(a,"get_status_metadata"),x=Rm(u);if(!x)return;const m=n(),v=m.find(p=>p.id===a),S=Fr(x,{daemonId:a,existingDaemon:v,existingEntries:m,timestamp:x.timestamp||Date.now()});S.length>0&&r(S,{authoritativeDaemonIds:[a]}),gn.set(a,Date.now()),Ao(a,!0)})().finally(()=>{bn.delete(a)});return bn.set(a,f),f},[n,r,e,t])}function Ma(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}function js(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:Qe(e)||Xe(e)?{agentType:Kt(e)}:e.streamSource==="agent-stream"?{agentType:Kt(e)}:t}function Zs(e){return e?Rs(e):""}function Ds(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Aa(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function _m(e){const t=e instanceof Error?e.message:String(e||""),r=t.toLowerCase();return r.includes("still processing the previous prompt")?"Wait for the current reply to finish before sending another message.":r.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":r.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":r.includes("not running")?"Runtime is not available right now.":t||"Unable to send message right now."}const Dm=60,Em=1e3;function lc(e={}){return e.isCliLike?Em:Dm}function $m(e={}){return lc(e)}const or=60,Bm=1e3,Ta=12e4,Km=new Set(["generating","waiting_approval","starting","streaming","working"]),To=new Map;function La(e,t){return`${e}::${t}`}function sa(e=or){return{liveMessages:[],cursor:dc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function ra(e){return Ii(e)}function dc(e,t=or){return{knownMessageCount:e.length,lastMessageSignature:ra(e[e.length-1]),tailLimit:t}}function br(e,t){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function Om(e,t){const r=Array.isArray(t.messages)?t.messages:[];switch(t.syncMode){case"noop":return e;case"append":return[...e,...r];case"replace_tail":{const n=Math.max(0,Math.min(Number(t.replaceFrom??e.length),e.length));return[...e.slice(0,n),...r]}case"full":return r;default:return r}}class Wm{constructor(t){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);this.manager=t.manager||qt,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=sa(Math.max(0,t.tailLimit??or))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);if(r!==this.snapshot.cursor.tailLimit){const n=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(t){const r=Array.isArray(t)?t:[];if(r.length===0)return;const n=r,a=dc(n,this.snapshot.cursor.tailLimit);br(this.snapshot.liveMessages)===br(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a},this.emit())}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await t(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},knownMessageCount:this.snapshot.cursor.knownMessageCount,lastMessageSignature:this.snapshot.cursor.lastMessageSignature,...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:Bm}))}disconnect(){var t;(t=this.transportSubscription)==null||t.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return;const r=typeof t.lastMessageSignature=="string"?t.lastMessageSignature:"",n=ra(this.snapshot.liveMessages[this.snapshot.liveMessages.length-1]);if(t.syncMode!=="full"&&r&&n===r){const d={knownMessageCount:Math.max(this.snapshot.cursor.knownMessageCount,Number(t.totalMessages||0)),lastMessageSignature:r,tailLimit:this.snapshot.cursor.tailLimit};this.snapshot.cursor.knownMessageCount===d.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===d.lastMessageSignature||(this.snapshot={...this.snapshot,cursor:d},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:d.knownMessageCount,lastMessageSignature:d.lastMessageSignature}));return}const a=Om(this.snapshot.liveMessages,t),i={knownMessageCount:a.length,lastMessageSignature:typeof t.lastMessageSignature=="string"?t.lastMessageSignature:ra(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 uc(e){const t=La(e.daemonId,e.sessionId),r=To.get(t);if(r)return r.updateOptions(e),r;const n=new Wm(e);return To.set(t,n),n}function Hm(e,t){return{...e,loadHistoryPage:t}}function Fm(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Um(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Km.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=t.now??Date.now(),a=Math.max(0,Number(t.recentActivityMs??Ta)),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 zm(e=Ta){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Vm(e,t={}){const r=new Set,n=[];for(const a of e){if(!Um(a,t))continue;const i=Rs(a),c=a.sessionId||"";if(!i||!c)continue;const l=La(i,c);if(r.has(l))continue;r.add(l);const d=nr(a);n.push({daemonId:i,sessionId:c,historySessionId:d||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Fm),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Gm(e,t){const{sendData:r,sendCommand:n}=wt(),a=(t==null?void 0:t.enabled)!==!1,i=Rs(e),c=e.sessionId||"",l=nr(e)||c,d=`daemon:${i}:session:${c}`,f=Math.max(0,(t==null?void 0:t.tailLimit)??or),u=o.useMemo(()=>!a||!i||!c?null:uc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:d,sendData:r,tailLimit:f}),[i,a,l,r,c,d,f]),[x,m]=o.useState(()=>(u==null?void 0:u.getSnapshot())||sa(f));o.useEffect(()=>{if(!u){m(sa(f));return}u.retain(),m(u.getSnapshot());const S=u.subscribe(p=>{m(p)});return()=>{S(),u.release()}},[u,f]),o.useEffect(()=>{u&&(u.hydrateLiveMessages(e.messages),m(u.getSnapshot()))},[e.messages,u]);const v=o.useCallback(async()=>{!u||!i||!c||await u.loadHistoryPage(async()=>{const S=e.agentType,p=await n(i,"chat_history",{agentType:S,offset:u.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),h=p&&typeof p=="object"&&"result"in p?p.result||{}:p||{};return{messages:Array.isArray(h.messages)?h.messages:[],hasMore:h.hasMore===!0}})},[e.agentType,u,i,l,n,c]);return o.useMemo(()=>Hm(x,v),[v,x])}function qm(e,t){const{sendData:r}=wt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??or),i=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Ta)),c=zm(i),[l,d]=o.useState(0),[f,u]=o.useState(()=>new Map);o.useEffect(()=>{if(!n||e.length===0)return;const m=setInterval(()=>{d(v=>v+1)},c);return()=>{clearInterval(m)}},[e.length,n,c]);const x=o.useMemo(()=>Vm(e,{recentActivityMs:i}),[e,i,l]);return o.useEffect(()=>{if(!n||!r||x.descriptors.length===0){u(h=>h.size===0?h:new Map);return}const m=x.descriptors.map(h=>({key:La(h.daemonId,h.sessionId),controller:uc({...h,sendData:r,tailLimit:a})})),v=new Set(m.map(({key:h})=>h)),S=(h,j)=>{u(b=>{const N=new Map(b);for(const T of N.keys())v.has(T)||N.delete(T);return N.set(h,j),N})},p=m.map(({key:h,controller:j})=>(j.retain(),S(h,j.getSnapshot()),j.subscribe(b=>S(h,b))));return()=>{p.forEach(h=>h()),m.forEach(({controller:h})=>h.release())}},[x.signature,n,r,a]),f}function Lo(e,t){const r=e[e.length-1];if(!r)return`empty:${t||""}`;let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return[t||"",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function Ro(e){for(let t=e.length-1;t>=0;t-=1){const r=Ma(e[t]);if(r>0)return r}return 0}function Ym(e){const t=Rs(e),r=e.sessionId||"";return t&&r?`${t}::${r}`:""}function Xm(e,t){if(t.length===0)return!1;const r=Array.isArray(e.messages)?e.messages:[];if(r.length===0)return!0;const n=Ro(r),a=Ro(t);if(n>0&&a>0&&a<n)return!1;const i=Lo(r,e.status),c=Lo(t,e.status);return i!==c}function Jm(e,t){const r=t[t.length-1],n=Ma(r),a=Ss(r==null?void 0:r.content);return{...e,messages:t,...a?{lastMessagePreview:a}:{},...n>0?{lastMessageAt:n}:{}}}function Qm(e,t){const r=(t==null?void 0:t.liveMessages)||[];return r.length>0?r:e.messages}function Zm(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,i=Math.max(0,r.length-n)>0?r.slice(-n):r;return t.length===0?i:[...t,...i]}function Po(e,t){if(t.size===0||e.length===0)return e;let r=!1;const n=e.map(a=>{var l;const i=Ym(a);if(!i)return a;const c=((l=t.get(i))==null?void 0:l.liveMessages)||[];return Xm(a,c)?(r=!0,Jm(a,c)):a});return r?n:e}function ef(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function tf(e){return ef(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const sf=60;function na({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:d,showMetaChips:f=!1,scrollToBottomRequestNonce:u,isInputActive:x=!0,isVisible:m=!0}){var ye,ge,ve,z,F;const v=o.useRef(new Map),S=ar();rr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const p=kt.useMemo(()=>Ts(e),[e.status,e.connectionState]),h=o.useMemo(()=>bm(e,t),[e,t]),j=o.useMemo(()=>{var Q;return ka((Q=h.targetEntry)==null?void 0:Q.providerControls,{hostIdeType:e.hostIdeType,providerType:h.providerType})},[e.hostIdeType,h.providerType,(ye=h.targetEntry)==null?void 0:ye.providerControls]),b=lc({isCliLike:h.isCli||h.isAcp}),N=$m({isCliLike:h.isCli||h.isAcp}),T=Gm(e,{enabled:m&&!!e.sessionId,tailLimit:N}),[y,C]=o.useState(b),k=e.tabKey,w=T.historyMessages,g=T.hasMoreHistory,D=T.historyError,A=Qm(e,T);o.useEffect(()=>{C(b)},[b,k]);const I=Math.max(0,A.length-y),P=Sa(e),O=Rs(e),V=tf(e),L=Aa(e),R=a||L,G=!!L,[K,E]=o.useState(!1);o.useEffect(()=>{const Q=h.targetEntry;O&&(!Q||Q.providerControls===void 0||Q.controlValues===void 0)&&S(O,{minFreshMs:3e4}).catch(()=>{})},[O,h.isAcp,(ge=h.targetEntry)==null?void 0:ge.providerControls,(ve=h.targetEntry)==null?void 0:ve.controlValues,S]);const W=o.useCallback(async()=>{if(!K){if(A.length>y){C(Q=>Math.min(A.length,Q+sf));return}E(!0);try{await T.loadHistoryPage()}finally{E(!1)}}},[T,K,A.length,y]),{allMessages:J,receivedAtMap:be}=o.useMemo(()=>{const Q=Zm({historyMessages:w,liveMessages:A,visibleLiveCount:y}),ue={};return Q.forEach((te,fe)=>{const re=`${e.tabKey}:${Kr(te,fe)}`;let pe=Ma(te)||v.current.get(re)||0;pe||(pe=Date.now(),v.current.set(re,pe)),ue[Kr(te,fe)]=pe}),{allMessages:Q,receivedAtMap:ue}},[e.tabKey,I,w,A,y]),xe=o.useMemo(()=>l.filter(Q=>Q.routeId===e.tabKey).sort((Q,ue)=>Q.timestamp-ue.timestamp),[l,e.tabKey]),de=o.useMemo(()=>{if(A.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((p.isGenerating||e.status==="streaming")&&E(!1),e.status==="not_monitored"&&V)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Js,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ns,{size:14})," Open ",P," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&V)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Ri,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ns,{size:14})," Open ",P," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!K)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,V,i,c,K,A.length,P,p.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[f&&s.jsx(cc,{conversation:e,className:"chat-pane-meta-row"}),s.jsx(du,{messages:J,actionLogs:xe,agentName:Cs(e)||P||"Agent",userName:d,isCliMode:h.isCli||h.isAcp,isWorking:p.isGenerating,contextKey:e.tabKey,receivedAtMap:be,onLoadMore:W,isLoadingMore:K,hasMoreHistory:g,hiddenLiveCount:I,loadError:D??void 0,emptyState:de,scrollToBottomRequestNonce:u,isVisible:m}),s.jsx(lm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:h.providerType,displayLabel:h.displayLabel,controls:(z=h.targetEntry)==null?void 0:z.providerControls,controlValues:(F=h.targetEntry)==null?void 0:F.controlValues,isActive:x,isCliTerminal:h.isCliTerminal}),!h.isCliTerminal&&s.jsx(Ji,{contextKey:e.tabKey,panelLabel:P,isSending:n,isBusy:G,statusMessage:R,onSend:r,isActive:x,showControlsToggle:j.length>0})]})}let mc=cs;function fc(){return mc()}class rf{constructor(){Ge(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{var n;(n=this.listeners.get(t))==null||n.delete(r)}}emit(t,...r){var n;(n=this.listeners.get(t))==null||n.forEach(a=>a(...r))}}let pc=new rf;class nf{sendPtyInput(t,r,n){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,r){return!1}get(t){}onScreenshot(t,r){return()=>{}}onRuntimeEvent(t,r,n){return()=>{}}requestRuntimeSnapshot(t,r){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let ot=new nf;function af(e){e.dashboardWS&&(pc=e.dashboardWS),e.connectionManager&&(ot=e.connectionManager),e.useDaemonsHook&&(mc=e.useDaemonsHook)}const of=.5,cf=1.25;function rt(e){return Sa(e)}function us(e){return sc(e).join(" · ")}function hc(e){const t=tc(e);return t||(e.title?e.title:us(e)||"No messages yet")}function xc(e,t){const{isReconnecting:r,isConnecting:n}=Ts(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function lf(e,t){const r=["Chat",...sc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function ts(e){return xc(e)||us(e)}function df(e){return`${rt(e)} · ${hc(e)}`}function uf(e){const t=Hr(e),r=t?tt(t):Cs(e);return`${rt(e)} — ${r||"Agent"}`}function mf(e){return Cs(e)||"CLI"}function bc(e){return ec(e)}function gc(e){return e?`Remote · ${rt(e)||e.workspaceName||"Session"}`:"Remote"}function ff({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var ae;cs();const{sendPtyInput:d}=wt(),[f,u]=o.useState(!1),x=o.useRef(!1);x.current=f;const[m,v]=o.useState("Runtime terminal unavailable"),[S,p]=o.useState(1),[h,j]=o.useState({width:0,height:0}),[b,N]=o.useState({width:0,height:0}),T=o.useRef(null),y=o.useRef(null),C=o.useRef(!1),k=o.useRef(!1),w=o.useRef(0),g=o.useRef(!1),D=o.useRef(""),A=o.useRef(null),I=o.useRef(!1),P=o.useRef(null),O=32*1024,V=()=>{var Y,X,ne,M;return((X=(Y=T.current)==null?void 0:Y.ownerDocument)==null?void 0:X.defaultView)||((M=(ne=y.current)==null?void 0:ne.ownerDocument)==null?void 0:M.defaultView)||window},L=Y=>{const X=V();return{ownerWindow:X,frameId:X.requestAnimationFrame(Y)}},R=()=>{const Y=P.current;if(Y){try{Y.ownerWindow.cancelAnimationFrame(Y.frameId)}catch{}P.current=null}},G=()=>{c&&P.current===null&&(P.current=L(()=>{re()}))},K=e.tabKey,E=e.sessionId||"",W=e.daemonId||((ae=e.routeId)==null?void 0:ae.split(":")[0])||e.routeId||"",J=Aa(e),be=f?i||J:m,xe=of,de=cf,ye=.05,ge=()=>{const Y=b.width,X=b.height;if(!Number.isFinite(h.width)||h.width<=0||!Number.isFinite(h.height)||h.height<=0||!Number.isFinite(Y)||Y<=0||!Number.isFinite(X)||X<=0)return 1;const ne=h.width/Y,M=h.height/X;return Number(Math.min(de,Math.max(xe,Math.min(ne,M))).toFixed(2))},ve=ge(),z=C.current&&S>ve,F=Number.isFinite(b.width)&&b.width>0?Math.max(h.width,Math.round(b.width*S)):h.width,Q=Number.isFinite(b.height)&&b.height>0?Math.max(h.height,Math.round(b.height*S)):h.height,ue=()=>{L(()=>{const Y=y.current;Y&&(Y.scrollLeft=0,Y.scrollTop=Y.scrollHeight-Y.clientHeight)})},te=()=>{var Y,X;w.current=0,g.current=!1,D.current="",A.current=null,I.current=!1,C.current||(k.current=!1,p(1)),P.current!==null&&R(),u(!1),v("Runtime terminal unavailable"),(X=(Y=r.current)==null?void 0:Y.reset)==null||X.call(Y)},fe=()=>{var Y,X;w.current=0,g.current=!1,D.current="",A.current=null,I.current=!1,P.current!==null&&R(),u(!0),v(""),(X=(Y=r.current)==null?void 0:Y.reset)==null||X.call(Y)},re=()=>{var ne;if(P.current=null,!c)return;const Y=D.current;if(!Y)return;const X=Y.slice(0,O);D.current=Y.slice(X.length),(ne=r.current)==null||ne.write(X),D.current.length>0&&G()},pe=Y=>{Y&&(D.current+=Y,G())},oe=(Y,X=0,ne,M)=>{var H,ce,me,je;X>0&&w.current>=X||X===0&&g.current||(w.current=X,u(!0),v(""),typeof ne=="number"&&typeof M=="number"&&ne>0&&M>0&&((ce=(H=r.current)==null?void 0:H.resize)==null||ce.call(H,ne,M)),D.current="",(je=(me=r.current)==null?void 0:me.reset)==null||je.call(me),Y&&pe(Y))};o.useEffect(()=>{te()},[E]),o.useEffect(()=>{var X;if(!E)return;const Y=((X=ot.onRuntimeEvent)==null?void 0:X.call(ot,E,ne=>{if(!(!ne||ne.sessionId!==E)){if(ne.type==="runtime_snapshot"){if(!c){A.current={text:ne.text||"",seq:ne.seq||0,cols:ne.cols,rows:ne.rows};return}oe(ne.text||"",ne.seq||0,ne.cols,ne.rows);return}if(ne.type==="session_output"){g.current=!0,typeof ne.seq=="number"&&(w.current=Math.max(w.current,ne.seq)),x.current||u(!0),x.current||v(""),typeof ne.data=="string"&&pe(ne.data);return}if(ne.type==="session_cleared"){if(!c){I.current=!0,D.current="",A.current=null;return}fe();return}if(ne.type==="session_io_error"){const M=typeof ne.error=="string"&&ne.error?ne.error:typeof ne.reason=="string"&&ne.reason?ne.reason:"unknown error";u(!1),v(`Runtime input failed: ${M}`);return}}},W))||(()=>{});return()=>{Y()}},[W,E,r,c]);const le=async()=>{var Y;if(!(!W||!E)){v("Loading runtime terminal...");try{const X=await((Y=ot.requestRuntimeSnapshot)==null?void 0:Y.call(ot,W,E));X&&X.success===!1&&(u(!1),v(`Runtime terminal unavailable: ${X.error}`))}catch(X){u(!1),v(`Runtime terminal unavailable: ${(X==null?void 0:X.message)||String(X)}`)}}};return o.useEffect(()=>{var X,ne;if(!E)return;W&&((X=ot.getState)==null?void 0:X.call(ot,W))==="connected"&&le();const Y=(ne=ot.onStateChange)==null?void 0:ne.call(ot,(M,H)=>{M!==W||H!=="connected"||le()});return()=>{Y==null||Y()}},[W,E,r]),o.useEffect(()=>{t&&te()},[t,K,r]),o.useEffect(()=>{var M,H;const Y=T.current,X=(H=(M=Y==null?void 0:Y.ownerDocument)==null?void 0:M.defaultView)==null?void 0:H.ResizeObserver;if(!Y||!X)return;const ne=new X(ce=>{const me=ce[0];if(!me)return;const{width:je,height:_e}=me.contentRect;j(Me=>{const Be=Math.round(je),We=Math.round(_e);return Me.width===Be&&Me.height===We?Me:{width:Be,height:We}})});return ne.observe(Y),()=>ne.disconnect()},[]),o.useEffect(()=>{if(C.current)return;const Y=ge();!Number.isFinite(Y)||Y<=0||p(X=>k.current?Y<X-ye?Y:X:(k.current=!0,Y))},[b.height,b.width,h.height,h.width]),o.useEffect(()=>{z&&ue()},[z,Q,F]),o.useEffect(()=>{var X;if(!c)return;I.current&&(I.current=!1,fe());const Y=A.current;Y&&(A.current=null,oe(Y.text,Y.seq,Y.cols,Y.rows)),W&&E&&((X=ot.getState)==null?void 0:X.call(ot,W))==="connected"&&le(),D.current&&P.current===null&&G(),L(()=>{var ne;(ne=r.current)==null||ne.bumpResize()})},[W,c,E]),o.useEffect(()=>()=>{P.current!==null&&R()},[]),o.useEffect(()=>{const Y=M=>{var ce;const H=M.detail;H!=null&&H.sessionId&&H.sessionId!==E||f&&((ce=r.current)==null||ce.bumpResize())},X=V(),ne=X===window?[window]:[window,X];for(const M of ne)M.addEventListener("adhdev:fit-cli-terminal",Y);return()=>{for(const M of ne)M.removeEventListener("adhdev:fit-cli-terminal",Y)}},[f,E,r]),s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:T,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{C.current=!0,p(Y=>{const X=Math.max(ve,Number((Y-.1).toFixed(2)));return X>ve&&ue(),X})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{C.current=!0,p(Y=>{const X=Math.min(de,Number((Y+.1).toFixed(2)));return X>ve&&ue(),X})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:y,className:z?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:F>0?`${F}px`:"100%",height:Q>0?`${Q}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:b.width>0?`${b.width}px`:"100%",height:b.height>0?`${b.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:S},children:s.jsx(Ki,{ref:r,readOnly:!f||!c,sizingMode:"measured",onViewportMetrics:N,onInput:Y=>{!f||(d==null||d(W,E,Y))}})})})}),!f&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:m})]}),s.jsx(Ji,{contextKey:e.tabKey,panelLabel:rt(e),isSending:a,isBusy:!!J,statusMessage:be,onSend:async Y=>J?!1:n(Y),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const pf=2500;function hf(e){return e==="disconnected"||e==="reconnecting"}function xf({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=pf}){const i=hf(e),[c,l]=o.useState(()=>!i||a<=0),d=o.useRef(!1);o.useEffect(()=>{if(!i){l(!1);return}if(d.current=!1,a<=0){d.current=!0,l(!0);return}l(!1);const j=setTimeout(()=>{d.current=!0,l(!0)},a);return()=>clearTimeout(j)},[a,i]);const f=i?c:e==="offline"||e==="auth_failed",u=o.useMemo(()=>!t||e!=="connected"?!1:a<=0||d.current,[a,t,e]),x=e==="auth_failed"?"red":e==="offline"?"orange":"accent",m={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},v={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},S={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},p="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",h={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[f&&s.jsx("div",{className:p,style:h,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-4 py-3 text-[13px] font-semibold flex items-center gap-2.5 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:m[x],border:v[x],color:S[x]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center",children:[e==="offline"&&"Network offline — waiting for connection...",e==="disconnected"&&"Reconnecting to server...",e==="reconnecting"&&"Reconnecting to server...",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),n&&e!=="auth_failed"&&s.jsx("button",{type:"button",className:"ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:n,disabled:e==="offline",children:"Reconnect now"})]})}),u&&s.jsx("div",{className:p,style:h,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function bf({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=o.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=o.useState(!1);if(o.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!t||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!0)};return s.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[l," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:d,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Ra({mode:e,onChange:t,compact:r=!1}){const n=r?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?s.jsx(ga,{size:n}):s.jsx(Ut,{size:n})})}const $t="New session",yc="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 gf({wsStatus:e,isConnected:t,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),i=a.filter(l=>l==="connected").length,c=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&c>0&&i===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:t?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function _o({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Do({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=Jr(e.updatedAt),l=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),i()},children:"Delete"})]})]})}function yf({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:f,hiddenConversations:u=[],onShowConversation:x,onShowAllHidden:m,onResetPanelsToMain:v,inboxOpen:S,onInboxOpenChange:p,hiddenOpen:h,onHiddenOpenChange:j,onOpenNewSession:b,actionShortcuts:N,notifications:T,notificationUnreadCount:y,onOpenNotification:C,onMarkNotificationRead:k,onMarkNotificationUnread:w,onDeleteNotification:g}){const{ides:D,p2pStates:A={}}=cs(),I=!!e&&Qe(e)&&!Xe(e),P=!!e&&Xe(e),O=l||(e?Qi(e)?"terminal":"chat":null),[V,L]=o.useState(!1),R=o.useRef(null),G=o.useRef(null),K=D.filter(z=>z.type==="adhdev-daemon"),E=gf({wsStatus:t,isConnected:r,daemonCount:K.length,p2pStates:A}),W=E.subtitle,J=E.tone==="connected"?"#22c55e":E.tone==="limited"?"#eab308":"#ef4444",be=E.tone==="connected"?"0 0 4px #22c55e80":E.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",xe=o.useMemo(()=>T.filter(z=>!z.readAt),[T]),de=o.useMemo(()=>T.filter(z=>!!z.readAt),[T]),ye=o.useMemo(()=>xe.slice(0,9),[xe]),ge=y;o.useEffect(()=>{if(!S)return;const z=F=>{var Q;(Q=R.current)!=null&&Q.contains(F.target)||p(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[S,p]),o.useEffect(()=>{if(!h)return;const z=F=>{var Q;(Q=G.current)!=null&&Q.contains(F.target)||j(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[h,j]),o.useEffect(()=>{if(!h&&!S)return;const z=F=>{if(!F.altKey)return;const Q=F.code.match(/^Digit([1-9])$/);if(!Q)return;const ue=Number(Q[1])-1,te=h?u[ue]:void 0,fe=S?ye[ue]:void 0;if(!(!te&&!fe)){if(F.preventDefault(),F.stopPropagation(),te){x==null||x(te),j(!1);return}fe&&(C(fe),p(!1))}};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[u,h,S,ye,j,p,C,x]);const ve=z=>{if(!z)return;const F=n.find(Q=>Q.tabKey===z);F&&(f==null||f(F))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Ut,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?rt(e):"Dashboard"}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:J,boxShadow:be}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[s.jsx("span",{title:E.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:J,boxShadow:be}}),W&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",W]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:$t,"aria-label":$t,children:s.jsx(Di,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(I||P||!Xe(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:us(e)||rt(e),children:rt(e)}),(I||P)&&c&&s.jsxs(s.Fragment,{children:[I&&d&&O&&s.jsx(Ra,{mode:O,onChange:d,compact:!0}),s.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:s.jsx(vt,{size:14})})]}),!Xe(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(ba,{size:14})}),!I&&!Xe(e)&&s.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Nt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:R,children:[s.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 F=z.dataTransfer.getData("text/tab-key");z.preventDefault(),L(!1),ve(F)},children:[s.jsxs("button",{type:"button",onClick:()=>j(!h),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${N!=null&&N.toggleHiddenTabs?` (${N.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Pi,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),h&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(_o,{value:N==null?void 0:N.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[v&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:v,children:"Reset panels"}),u.length>0&&m&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{m(),j(!1)},children:"Restore all"})]})]}),e&&f&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>f(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(_o,{value:N==null?void 0:N.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:rt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(z=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{x==null||x(z),j(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:rt(z)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(z)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(z)+1]}):null,us(z)]})]},z.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!S),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Xr,{size:16}),ge>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ge})]}),S&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[xe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),xe.map(z=>s.jsx(Do,{notification:z,shortcutIndex:ye.indexOf(z)>=0?ye.indexOf(z)+1:void 0,onOpen:()=>C(z),onMarkRead:()=>k(z.id),onMarkUnread:()=>w(z.id),onDelete:()=>g(z.id)},z.id))]}),de.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),de.map(z=>s.jsx(Do,{notification:z,onOpen:()=>C(z),onMarkRead:()=>k(z.id),onMarkUnread:()=>w(z.id),onDelete:()=>g(z.id)},z.id))]}),T.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function ht(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function vf(e,t){return String(e||"")!==String(t||"")}function wf(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),i=!!t.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(d=>String(d||"").toLowerCase()).join(`
|
|
30
|
+
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!Vi(c.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
31
|
+
`).includes(a)))}function jf(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const i=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function vc(e,t={}){return jf(wf(e,t),t.sortMode||"recent")}function Ur(e){return e?"Resume saved history":"Start fresh"}function Pa(e){return e?"Resuming saved history…":"Starting fresh…"}function kf(){return"Start fresh"}function wc(e,t=!1){return e==="cli"?Ur(t):e==="ide"?"Start IDE":"Start ACP session"}function jc(e,t=!1){return e==="cli"?Pa(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Sf(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Nf(){return"Open saved history"}function Cf(){return"Saved History"}function _a(){return"Use saved history when you want continuity in the same provider conversation."}function If(){return"No saved history found yet."}function Mf(){return"Refresh saved history"}function Af(){return"Refreshing saved history…"}function ss(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}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 Is(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ms(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Da(e){return`Resume saved history with ${e}?`}function Ea(){return"Review or change the target workspace before resuming saved history."}function Tf(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:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:d,onClose:f,onNewChat:u,onSwitchSession:x,onRefreshHistory:m,onResumeSavedSession:v}){var w;const S=t.find(g=>g.id===e.routeId),p=(S==null?void 0:S.chats)||[],h=(w=S==null?void 0:S.activeChat)==null?void 0:w.id,j=Qe(e)&&!Xe(e),[b,N]=o.useState(()=>ht()),T=l||b,y=g=>{if(d){d(g);return}N(g)},C=o.useMemo(()=>vc(a,{textQuery:T.textQuery,workspaceQuery:T.workspaceQuery,modelQuery:T.modelQuery,resumableOnly:T.resumableOnly,sortMode:T.sortMode}),[T.modelQuery,T.resumableOnly,T.sortMode,T.textQuery,T.workspaceQuery,a]),k=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:f,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:j?Cf():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:uf(e)}),j&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:_a()})]}),s.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:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!j&&s.jsx("button",{onClick:u,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"}),j?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:T.textQuery,onChange:g=>y({...T,textQuery:g.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:T.workspaceQuery,onChange:g=>y({...T,workspaceQuery:g.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:T.modelQuery,onChange:g=>y({...T,modelQuery:g.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:T.sortMode,onChange:g=>y({...T,sortMode:g.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:T.resumableOnly,onChange:g=>y({...T,resumableOnly:g.target.checked})}),"Resume-ready only"]})]}),C.map(g=>{const D=e.providerSessionId===g.providerSessionId,A=D||!g.canResume||!!c;return s.jsxs("button",{type:"button",onClick:()=>{A||!v||v(g)},disabled:A,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${D?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${A?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${D?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:g.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:g.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Tf(g.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:g.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[g.workspace||"Workspace unknown",ds(g.summaryMetadata)?` · ${ds(g.summaryMetadata)}`:"",g.messageCount>0?` · ${g.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:D?"ACTIVE":g.canResume?c===g.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},g.id)})]}):p.map(g=>s.jsxs("div",{onClick:()=>{x(e.routeId,g.id),f()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${h===g.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${h===g.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:g.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[g.id.substring(0,12),"..."]}),h===g.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},g.id)),(j&&!i&&C.length===0||!j&&p.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Hd,{size:32})}),s.jsx("div",{className:"text-[13px]",children:j?a.length>0?"No saved history matches these filters.":If():"No recent chat sessions found."})]}),j&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Af()})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:m,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(sr,{size:13})," ",j?Mf():"Refresh History"]})})})]})]});return typeof document>"u"?k:qs.createPortal(k,document.body)}const Eo={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 kc({toasts:e,onDismiss:t,onClickToast:r}){return s.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const a=Eo[n.type]||Eo.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=n.actions)!=null&&i.length||r&&r(n)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(vt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:l=>{l.stopPropagation(),i.onClick(),t(n.id)},children:i.label},c))})]})]},n.id)})})}const Lf=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Rf(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Pf(e){return e.sessionId||e.instanceId||e.agentType}function yn(e,t){return e||t}function Sc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=At(r,{fallbackId:r.id}));return t}function Nc(e,t={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=t.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Ba(e,t={}){return _f(e,Nc(e,t))}function _f(e,t={}){var u,x,m,v,S,p;const r=[],n=t.machineName,a=t.connectionState,i=Rf(e),c=Au(e.type,{agentName:e.cliName}),l=Qe(e)||Xe(e)?c:tt(e.type),d=Array.isArray(e.childSessions)?e.childSessions.map(h=>{var j,b;return{sessionId:h.id,instanceId:h.id,providerSessionId:h.providerSessionId,transport:h.transport,sessionCapabilities:h.capabilities,agentType:h.providerType,agentName:h.providerName||tt(h.providerType),status:h.status,title:h.title,lastMessagePreview:h.lastMessagePreview,lastMessageRole:h.lastMessageRole,lastMessageAt:h.lastMessageAt,lastMessageHash:h.lastMessageHash,messages:((j=h.activeChat)==null?void 0:j.messages)||[],activeModal:((b=h.activeChat)==null?void 0:b.activeModal)||void 0,unread:h.unread,lastSeenAt:h.lastSeenAt,lastUpdated:h.lastUpdated,inboxBucket:h.inboxBucket,surfaceHidden:h.surfaceHidden}}):[],f=Lf(e);if(f){const h=e.sessionId||e.instanceId,j=c,b=(u=e.activeChat)==null?void 0:u.activeModal,N=b&&Array.isArray(b.buttons)&&b.buttons.length>0,T=bt((x=e.activeChat)==null?void 0:x.status,{activeModal:(m=e.activeChat)==null?void 0:m.activeModal})||bt((S=(v=e.agents)==null?void 0:v[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 k=(p=e.activeChat)==null?void 0:p.id,w=e.chats;if(k&&Array.isArray(w)&&w.length>0){const I=w.find(P=>P.id===k||P.id&&String(P.id)===String(k));I!=null&&I.title&&String(I.title).trim()&&(C=String(I.title).trim())}const g=(Qe(e)||Xe(e),e.type),D=(Qe(e)||Xe(e))&&jo(C,j,g)?"":C,A=y.messages||[];r.push({routeId:e.id,sessionId:h,providerSessionId:e.providerSessionId,nativeSessionId:h,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:Qe(e)?e.mode||"terminal":"chat",agentName:j,agentType:g,status:T,title:D,messages:A,resume:e.resume,hostIdeType:!Qe(e)&&!Xe(e)?e.type:void 0,workspaceName:i,displayPrimary:D||i||(Qe(e)?e.mode==="chat"?j:"Terminal":j),displaySecondary:l,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:N?b.buttons:void 0,modalMessage:N?b.message:void 0,streamSource:"native",tabKey:yn(h,e.id),machineName:n,connectionState:a})}if(f&&(Qe(e)||Xe(e)))return r;for(const h of d){const j=h.activeModal&&Array.isArray(h.activeModal.buttons)&&h.activeModal.buttons.length>0,b=Tu(h),N=Pf(h),T=`${e.id}:${N}`,y=h.title&&String(h.title).trim()||"",C=jo(y,h.agentName,h.agentType)?"":y,k=h.messages||[];(h.transport==="cdp-webview"||h.sessionId||h.providerSessionId||k.length>0||j||C||!["idle","panel_hidden","disconnected","not_monitored"].includes(b))&&r.push({routeId:e.id,sessionId:h.sessionId||h.instanceId,providerSessionId:h.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:h.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:h.sessionCapabilities,mode:"chat",agentName:h.agentName,agentType:h.agentType,status:b,title:C,messages:k,hostIdeType:e.type,workspaceName:i,displayPrimary:C||i||h.agentName||l,displaySecondary:`${l} · ${h.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:h.lastMessagePreview,lastMessageRole:h.lastMessageRole,lastMessageAt:h.lastMessageAt,lastMessageHash:h.lastMessageHash,lastUpdated:h.lastUpdated||e.lastUpdated,modalButtons:j?h.activeModal.buttons:void 0,modalMessage:j?h.activeModal.message:void 0,streamSource:"agent-stream",tabKey:yn(h.sessionId||h.instanceId,T),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 Df(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function Cc(e,t){const r=Df(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Ic=[{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"trae",name:"Trae",icon:"🔮"},{id:"vscode",name:"VS Code",icon:"💙"},{id:"vscodium",name:"VSCodium",icon:"💚"},{id:"windsurf",name:"Windsurf",icon:"🏄"}],Mc=[{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:"🧩"}],Ac=[{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:"🟠"}],Ef=Ic,$f=Mc,Bf=Ac;function ms(...e){return sd(rd(e))}function Kf({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:ms("dashboard-header",i),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function Tc({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Kf,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ms("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const aa="adhdev:themechange";function Of(){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"?Of():e}function Lc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Lr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(aa,{detail:{preference:e,theme:t}}))}function Wf(){const e=xs(),t=bs(e);Lc(t),Lr(e,t)}function Ka(){const[e,t]=o.useState(xs),[r,n]=o.useState(()=>bs(xs()));o.useEffect(()=>{Lc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const f=d.matches?"light":"dark";n(f),Lr("system",f)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=d=>{const f=d.detail||{},u=f.preference,x=f.theme;t(u==="dark"||u==="light"||u==="system"?u:xs()),n(x==="dark"||x==="light"?x:bs(xs()))},l=d=>{if(d.key!=="theme")return;const f=xs(),u=bs(f);t(f),n(u)};return window.addEventListener(aa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(aa,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=bs(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Lr(c,l)},[]),i=o.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=bs(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Lr(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const $o={dark:"Dark",light:"Light",system:"System"};function Hf({collapsed:e}){const{preference:t,cycleTheme:r}=Ka(),n=t==="dark"?s.jsx(Ud,{size:16}):t==="light"?s.jsx(Fd,{size:16}):s.jsx(zd,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${$o[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:$o[t]})]})}function vn(e,t){return e?typeof e=="function"?e(t):e:null}function Ff({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[f,u]=o.useState(!1),[x,m]=o.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),v=()=>u(!0),S=()=>u(!1),p=()=>{m(N=>{const T=!N;try{localStorage.setItem(d,T?"1":"0")}catch{}return T})},h=o.useMemo(()=>({collapsed:x,mobileMenuOpen:f,openMobileMenu:v,closeMobileMenu:S,toggleCollapsed:p}),[x,f]),j=N=>`nav-item${N.active?" active":""} cursor-pointer ${x?"justify-center py-2.5 px-0":""}${N.className?` ${N.className}`:""}`,b=N=>s.jsxs("div",{className:j(N),id:`nav-${N.id}`,onClick:()=>{N.onSelect(),S()},title:x?N.title??(typeof N.label=="string"?N.label:void 0):N.title,children:[s.jsx("span",{className:"nav-icon",children:N.icon}),!x&&N.label]},N.id);return s.jsxs("div",{className:`app-layout${f?" mobile-menu-open":""}${x?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:v,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),f&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:S,onKeyDown:N=>N.key==="Escape"&&S()}),s.jsxs("aside",{className:`sidebar ${f?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${x?"justify-center gap-0":""}`,children:vn(t,h)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:S,children:s.jsx(vt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),n.map(N=>s.jsxs("div",{className:N.className??"border-t border-border-subtle pt-2 mt-2",children:[!x&&N.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:N.title}):null,N.items.map(b)]},N.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),vn(i,h),s.jsx(Hf,{collapsed:x}),vn(c,h)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function St({title:e,icon:t,description:r,accentColor:n,className:a,children:i}){return s.jsxs("div",{className:ms("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function Rc({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ms("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Uf={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"},zf={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function gr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ms("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Uf[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:zf[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const Vf={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"},Gf={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function qf({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ms("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Vf[e],r),children:[s.jsx("span",{className:ms("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Gf[e])}),n]})}function Qt({label:e,description:t,checked:r,disabled:n,onChange:a,extra:i}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,s.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Yf({onPrefChange:e}){const[t,r]=Ou(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>i("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>i("browserNotifications",c)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{Yi().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Gd,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Js,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function zr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Xf(e,t){const r=zr(e),n=zr(t);if(!r||!n)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function Pc(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function zs(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Xf(r,t)>=0)return!1;const n=zr(r),a=zr(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Jf(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function wn(e,t){return e instanceof Error?e.message:t}function Qf({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Rc,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:t||"Install ADHDev on a machine and sign in to connect it here."}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>s.jsx(ep,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Bo({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return qs.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:i,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function Zf(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Ef,...$f,...Bf].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function ep({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var O,V;const[i,c]=o.useState("idle"),[l,d]=o.useState(""),[f,u]=o.useState(null),[x,m]=o.useState("idle"),[v,S]=o.useState(""),p=e.version||null,h=((O=e.machine)==null?void 0:O.platform)||((V=e.system)==null?void 0:V.platform)||"",j=At(e,{fallbackId:e.id}),b=h==="win32"?"🪟":h==="darwin"?"🍎":"🐧",N=t.filter(L=>L.daemonId===e.id&&L.transport==="cdp-page"),T=t.filter(L=>L.daemonId===e.id&&L.transport==="pty"),y=t.filter(L=>L.daemonId===e.id&&L.transport==="acp"),C=e.p2p,k=async()=>{if(r){c("upgrading"),d("Starting upgrade...");try{const L=Jf(await r(e.id,"daemon_upgrade",{}));L.alreadyLatest?(c("done"),d(`Already on v${L.version||"latest"}.`)):L.upgraded||L.success?(c("done"),d(`Upgrade to v${L.version||"latest"} started. Daemon is restarting...`)):(c("error"),d(L.error||"Upgrade failed"))}catch(L){c("error"),d(wn(L,"Connection lost during upgrade"))}}},w=async()=>{if(u(null),!!n){m("loading");try{await n(e.id),m("done"),S("Machine disconnected.")}catch(L){m("error"),S(wn(L,"Failed to disconnect"))}}},g=async()=>{if(u(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"))}}},D="0.9.25",A=Pc(e,D),I=zs(e,D),P=N.length+T.length+y.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:b}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:j}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),p&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${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&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&A&&s.jsx("button",{onClick:k,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${D}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${I?"↑ Update now":`↑ Update${` to v${D}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:x==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:x==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(qf,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[C&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${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}),s.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&&s.jsxs("span",{className:"text-text-muted/60",children:["(",C.peers," peer",C.peers!==1?"s":"",")"]})]}),C&&P>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),P>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(L=>{const R=Zf(L.type),G=L.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:R.icon}),s.jsx("span",{children:R.name}),G!==void 0&&s.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)}),T.map(L=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:L.cliName||"CLI"})]},L.id)),y.map(L=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:L.cliName||"ACP"})]},L.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||v)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||x==="error"?"text-red-400":i==="done"||x==="done"?"text-green-400":"text-text-muted"}`,children:v||l})]}),f==="disconnect"&&s.jsx(Bo,{title:"🔌 Disconnect Machine",message:`Disconnect "${j}" from ADHDev?
|
|
32
32
|
|
|
33
33
|
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
34
34
|
|
|
35
|
-
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:
|
|
35
|
+
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:w,onCancel:()=>u(null)}),f==="revoke"&&s.jsx(Bo,{title:"⚠️ Remove Machine",message:`Remove "${j}" from your dashboard?
|
|
36
36
|
|
|
37
37
|
This will:
|
|
38
38
|
• Immediately disconnect the machine
|
|
39
39
|
• Delete the machine registration
|
|
40
40
|
• Require restarting ADHDev on that machine
|
|
41
41
|
|
|
42
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:g,onCancel:()=>d(null)})]})}const Uf=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function zf(){const{preference:e,setPreference:t}=$a();return s.jsx("div",{className:"flex gap-2",children:Uf.map(r=>s.jsxs("button",{onClick:()=>t(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx("span",{children:r.icon}),r.label]},r.id))})}function Vf(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function Gf(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 t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function _o(e){const{r:t,g:r,b:n}=Gf(e);return .2126*jn(t)+.7152*jn(r)+.0722*jn(n)}function Do(e,t){const r=_o(e),n=_o(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Tc(e){const t=Vf(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Do(t,r)>=Do(t,n)?r:n}const oa={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},ia={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},qf=[{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"}}}],Lc="adhdev-chat-theme",Rc="adhdev-chat-theme-custom";function Rr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Lc)||"ember"}catch{return"ember"}}function Pt(e){try{const t=localStorage.getItem(Rc);if(t){const r=JSON.parse(t);return{...e==="dark"?oa:ia,...r[e]}}}catch{}return e==="dark"?oa:ia}function yr(e,t){try{localStorage.setItem(Rc,JSON.stringify({dark:e,light:t}))}catch{}}function It(e,t){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${t})`}function Vr(e,t){const r=Math.min(255,parseInt(e.slice(1,3),16)+t),n=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const Yf={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Fs(e,t){var a;const r=(a=Yf[e])==null?void 0:a[t];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Vr(r,24)),n.style.setProperty("--accent-on-primary",Tc(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 t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",It(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",It(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",It(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",It(e.borderSubtle,.5)),t.style.setProperty("--border-default",It(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Vr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Tc(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Vr(e.accentColor,40)})`),t.style.setProperty("--border-accent",It(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",It(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${It(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${It(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function Ba(){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 Xf(e){try{localStorage.setItem(Lc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=as()?"dark":"light";ns(Pt(t))}else Ba(),Fs(e,as()?"dark":"light")}function Jf(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Rr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=as()?"dark":"light";ns(Pt(t))}else Ba(),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:t,onChange:r}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Ps({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function Qf({dark:e,onColorsChange:t}){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),t(f),f})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",s.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(Ps,{title:"App Background",children:[s.jsx(xt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(xt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(xt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Ps,{title:"App Text",children:[s.jsx(xt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(xt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(xt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Ps,{title:"Borders & Accent",children:[s.jsx(xt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(xt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(xt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Ps,{title:"Chat Bubbles",children:[s.jsx(xt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(xt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(xt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(xt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Ps,{title:"Chat Layout",children:[s.jsx(xt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(xt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(xt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?oa:ia,u=Pt(e?"light":"dark");e?yr(c,u):yr(u,c),a(c),ns(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function Zf(){const[e,t]=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")):(Ba(),Fs(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Pt(r?"dark":"light"))},[r]);const c=u=>{t(u),Xf(u)},l=[...qf,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const 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 s.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:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:d.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.userBubble,color:h},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[f&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&s.jsx(Qf,{dark:r,onColorsChange:u=>i(u)})]})}const Ka="adhdev_mobileDashboardMode_v1",ca="adhdev:mobile-dashboard-mode-change";function Oa(){try{return localStorage.getItem(Ka)==="workspace"?"workspace":"chat"}catch{return"chat"}}function ep(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Oa())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==Ka||t()};return window.addEventListener(ca,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ca,r),window.removeEventListener("storage",n)}}function tp(e){try{localStorage.setItem(Ka,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ca,{detail:e}))}function sp(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(Oa()==="chat")},[]),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.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=>{t(r),tp(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const kn=new Map,Eo=new Map;function rp(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function np(e,t,r,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n,platform:r.platform,machine:r}}function Pc(){const{sendCommand:e}=jt(),{injectEntries:t,getIdes:r}=Gs();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??vm,c=Eo.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=rp(f);if(!d)return;const h=r().find(w=>w.id===n),m=np(h,n,d.machine,d.timestamp||Date.now());t([m]),Eo.set(n,Date.now())})().finally(()=>{kn.delete(n)});return kn.set(n,u),u},[r,t,e])}function ap(e,t,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...r.machine}}}function op(e,t){const{sendData:r}=jt(),{injectEntries:n,getIdes:a}=Gs(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>qt.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const h=a().find(w=>w.id===u),m=ap(h,u,d);n([m])}));return()=>{l.forEach(u=>u())}},[i,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function ip(e,t){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(!(t!=null&&t.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const u=qt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},f=>{l&&(clearTimeout(l),l=null),a(f.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},Sm):c(!1),()=>{l&&clearTimeout(l),u()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:a}}function cp(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function _c(e){const{sendData:t}=jt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=cp(e);if(!a||!e.sessionId||!t){n({});return}const i=qt.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),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,t]),r}const Dc="adhdev_hiddenTabs";function lp(){try{const e=localStorage.getItem(Dc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ps(e){try{localStorage.setItem(Dc,JSON.stringify([...e]))}catch{}}function Sn(e){return Ca(e)}function Wa(e,t){return ws(t).some(r=>e.has(r))}function dp(){const[e,t]=o.useState(lp),r=o.useCallback(f=>{const d=Sn(f);t(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);t(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);t(h=>{if(!h.has(d))return h;const m=new Set(h);return m.delete(d),ps(m),m})},[]),i=o.useCallback(()=>{t(f=>{if(f.size===0)return f;const d=new Set;return ps(d),d})},[]),c=o.useCallback((f,d)=>{t(h=>{const m=new Set(h);for(const w of d)m.add(w);return ps(m),m})},[]),l=o.useCallback((f,d)=>{t(h=>{const m=new Set(h);for(const w of d)m.delete(w);return ps(m),m})},[]),u=o.useCallback(f=>Wa(e,f),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Ec(e){return e instanceof Error?e.message:String(e||"")}function $c(e){const t=Ec(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function Bc(e){const t=Ec(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Kc({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Je(e)||qe(e))return;const i=Ts(e);if(i===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(fs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Kt(e),mode:t})}catch(l){const u=Bc(l);c&&!u&&a(f=>{const d={...f};return i===Oc(r,c)?delete d[c]:d[c]=i,d}),$c(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,t){const r=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!r||e.transport!=="pty")return e;const n=t[r];return!n||e.mode===n?e:{...e,mode:n}}function up(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let r=!1;const n=e.map(a=>{const i=$o(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>$o(u,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Oc(e,t){if(!t)return null;for(const r of e){if(r.sessionId===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function mp(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))Oc(t,a)===i&&(delete n[a],r=!0);return r?n:e}function fp({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Ui()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:fc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Eu(a),o.useEffect(()=>{if(Object.keys(t).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)},[t,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 pp(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const i=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function Nn(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function hp(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Bo(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?hp(Vs(r.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((r==null?void 0:r.id)||""),String((r==null?void 0:r.index)??""),String((r==null?void 0:r.receivedAt)??(r==null?void 0:r.timestamp)??""),n].join(":")}function xp(e){const t=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),Bo(e.activeChat),...t.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastMessageAt||""),r.lastMessagePreview||"",r.lastMessageRole||"",String(r.lastUpdated||""),Bo(r.activeChat)].join(":"))].join("|")}function bp(e,t){const r=Date.now();return e.map(n=>{const a=t[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function gp(e,t){const r=new Map;for(const n of e){const a=t.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 yp(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function vp(e){const t=yp(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const r=String(t.role||""),n=Vs(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function wp({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>pp(e),[e]),i=o.useMemo(()=>vc(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 T=new Map,y=[];for(const g of a){const{connectionState:D="new",machineName:M}=wc(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),I=xp(g),P=f.current.get(g.id);if(P&&P.ide===g&&P.sourceSignature===I&&P.connectionState===D&&P.machineName===M){T.set(g.id,P),y.push(...P.conversations);continue}const K=Ea(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),V={ide:g,sourceSignature:I,connectionState:D,machineName:M,conversations:K};T.set(g.id,V),y.push(...K)}f.current=T;const C=new Map,k=g=>{const D=vp(g),M=d.current.get(g.tabKey);if(M&&M.signature===D)return C.set(g.tabKey,M),M.timestamp;const I={signature:D,timestamp:ec(g)||(M==null?void 0:M.timestamp)||0};return C.set(g.tabKey,I),I.timestamp},v=[...y].sort((g,D)=>tc(g,D,k));return d.current=C,v},[a,t,i]),m=o.useMemo(()=>{const T=bp(h,r);return Nn(c.current,T)?c.current:(c.current=T,T)},[h,r]),w=o.useMemo(()=>{const T=new Map,y=Array.from(new Set(m.map(C=>C.routeId)));for(const C of y){const k=_t(m,C);k&&T.set(C,k)}return T},[m]),S=o.useMemo(()=>{const T=new Map;for(const y of m){const C=w.get(y.routeId),k=y.streamSource==="native"&&C?C:y;for(const v of ws({providerSessionId:y.providerSessionId,sessionId:y.sessionId}))T.set(v,k)}return T},[m,w]),p=o.useMemo(()=>gp(m,w),[m,w]),x=o.useCallback(T=>{if(T)return S.get(T)},[S]),j=o.useCallback(T=>{if(T)return p.get(T)},[p]),b=o.useMemo(()=>{const T=m.filter(y=>!Wa(n,y));return Nn(l.current,T)?l.current:(l.current=T,T)},[m,n]),N=o.useMemo(()=>{const T=b.map(y=>y.tabKey);return Nn(u.current,T)?u.current:(u.current=T,T)},[b]);return{chatIdes:a,conversations:m,visibleConversations:b,visibleTabKeys:N,resolveConversationBySessionId:x,resolveConversationByTarget:j}}function jp({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),i=o.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=o.useCallback(()=>{t&&n(l=>{const u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function kp({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{lt.setIdes(e)},[e]),o.useEffect(()=>{lt.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),o.useEffect(()=>{const a=lt.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=dc.on("status_event",i=>{lt.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",w=String(m).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(w);t(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,t])}const Sp="adhdev_dashboardLayout_v1",Np="adhdev_dashboardDockview_v1",Cp="adhdev_dashboardDockviewHiddenRestore_v1",_s={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ha(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Ip(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Wc(e){return`${Sp}:${e}`}function Ap(e){const t=Wc(e);return Ha(t,null)}function Mp(e,t){try{const r=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,n=Wc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Hc(e){return`${Np}:${e}`}function Tp(e){const t=Hc(e);return Ha(t,null)}function Lp(e,t){try{const r=Hc(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Fc(e){return`${Cp}:${e}`}function Rp(e){const t=Fc(e);return Ha(t,{})}function Pp(e,t){try{const r=Fc(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function _p(){return{groupAssignments:[..._s.groupAssignments],focusedGroup:_s.focusedGroup,groupActiveTabIds:{..._s.groupActiveTabIds},groupTabOrders:{..._s.groupTabOrders},groupSizes:[..._s.groupSizes]}}function Dp(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Ep(){const[e]=o.useState(()=>Ip(typeof window<"u"?window.innerWidth:1280)),[t,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[f,d]=o.useState([]),[h,m]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[w,S]=o.useState(!1),p=o.useCallback(()=>{if(w)return;const g=Ap(e)??_p();r(new Map(g.groupAssignments)),a(g.focusedGroup),c(g.groupActiveTabIds),u(g.groupTabOrders),d(g.groupSizes),S(!0)},[w,e]);o.useEffect(()=>{w&&Mp(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:f})},[w,e,t,n,i,l,f]),o.useEffect(()=>{const g=window.matchMedia("(max-width: 767px)"),D=M=>m(M.matches);return g.addEventListener("change",D),()=>g.removeEventListener("change",D)},[]);const x=o.useCallback(g=>{r(g)},[]),j=o.useCallback(g=>{a(g)},[]),b=o.useCallback(g=>{c(g)},[]),N=o.useCallback(g=>{u(g)},[]),T=o.useCallback(g=>{d(g)},[]),y=o.useCallback(g=>{j(g)},[j]),C=o.useCallback((g,D)=>{c(M=>(M[g]??null)===(D??null)?M:{...M,[g]:D})},[]),k=o.useCallback((g,D)=>{u(M=>{const I=M[g];return Dp(I,D)?M:{...M,[g]:D}})},[]),v=o.useCallback((g,D)=>{const M=D.get(g)??0;return C(M,g),y(M),M},[y,C]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:n,updateFocusedGroup:j,focusGroup:y,groupActiveTabIds:i,updateGroupActiveTabIds:b,setGroupActiveTab:C,groupTabOrders:l,updateGroupTabOrders:N,setGroupTabOrder:k,groupSizes:f,updateGroupSizes:T,isMobile:h,hasHydratedStoredLayout:w,hydrateStoredLayout:p,focusConversationTab:v}}function $p(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Na(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Bp({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:u,activeConv:f,isRefreshingHistory:d,ides:h,handleRefreshHistory:m}){const w=o.useRef(!1),S=o.useRef(!1),p=o.useRef(null),x=o.useRef(!1);o.useEffect(()=>{if(!e||w.current||t.length===0)return;if(!a){i();return}const j=r(e);j&&(c(j.tabKey,n),w.current=!0,S.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(b=>{const N=new URLSearchParams(b);return N.delete("activeTab"),N},{replace:!0}))},[e,t,r,n,a,i,c,l]),o.useEffect(()=>{if(!(S.current||a)&&t.length!==0){if(!e){i(),S.current=!0;return}if(w.current){S.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(S.current||a)&&(i(),S.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,i]),o.useEffect(()=>{if(!u){x.current=!1;return}if(!f||x.current||d)return;const j=h.find(b=>b.id===f.routeId);j&&(!j.chats||j.chats.length===0||$p(j.chats,f))&&(x.current=!0,m())},[u,f,d,h,m]),o.useEffect(()=>{if(!f)return;let j=null,b=0,N=-1,T=0;const y=()=>{j=null;const C=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(v=>v.offsetParent!==null);if(C.length===0){b<18&&(b+=1,j=requestAnimationFrame(y));return}let k=0;for(const v of C)v.scrollTop=v.scrollHeight,k+=v.scrollHeight;k===N?T+=1:(T=0,N=k),b+=1,!(T>=2||b>=18)&&(j=requestAnimationFrame(y))};return j=requestAnimationFrame(y),()=>{j!=null&&cancelAnimationFrame(j)}},[f==null?void 0:f.tabKey])}function Cn(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=Na(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Uc({sendDaemonCommand:e,activeConv:t,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||(t==null?void 0:t.daemonId)||"",j=await e(x,"switch_chat",{id:p,sessionId:p,...js(t)}),b=j==null?void 0:j.result;if((j==null?void 0:j.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Rs(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Rs(a,`⚠️ Switch error: ${b}`):Rs(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Rs(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,a]),m=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const S=Js(t);await e(S,"new_chat",{...js(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(S){console.error("New chat failed",S)}finally{l(!1)}}},[t,c,e,i]),w=o.useCallback(async()=>{var S,p;if(!(!t||u)){f(!0);try{const x=Js(t),j=async()=>e(x,"list_chats",{forceExpand:!0,...js(t)});let b=await j(),N=(b==null?void 0:b.chats)||((S=b==null?void 0:b.result)==null?void 0:S.chats);Cn(N,t)&&(await new Promise(T=>setTimeout(T,450)),b=await j(),N=(b==null?void 0:b.chats)||((p=b==null?void 0:b.result)==null?void 0:p.chats)),b!=null&&b.success&&Array.isArray(N)&&(n(t.routeId,N),Cn(N,t)&&!Cn(r,t)&&Rs(a,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{f(!1)}}},[t,r,u,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:h,handleNewChat:m,handleRefreshHistory:w}}function Kp(e,t){if(e.size!==t.size)return!1;for(const[r,n]of e)if(t.get(r)!==n)return!1;return!0}function Op(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Ko(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length!==n.length?!1:r.every(a=>t[Number(a)]===e[Number(a)])}function vr(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const u=a[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function Oo(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=t[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function Wp(e,t,r){if(t.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...t].reverse().find(a=>a<e)??t[0];return r[n]??0}function Hp(e,t,r){if(t.length<=1)return[];const n=t.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===t.length?n:Array(r).fill(100/r),i=a.reduce((c,l)=>c+l,0);return i>0?a.map(c=>c/i*100):Array(r).fill(100/r)}function Wo(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=t?i+1:i]=a}return r}function Ho(e){return Array(e).fill(100/e)}function Fp({groupAssignments:e,updateGroupAssignments:t,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,w=o.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),S=w>1,p=o.useCallback((y,C)=>{t(k=>{const v=new Map(vr(k,f).assignments);return C===0?v.delete(y):v.set(y,C),v}),n(k=>({...k,[C]:y})),r(C)},[t,f,n,r]),x=o.useCallback(y=>{t(C=>{const k=vr(C,f).assignments,v=new Map;for(const[g,D]of k)D!==y&&(D>y?v.set(g,D-1):v.set(g,D));return v}),c(C=>{if(C.length<=1)return[];const k=[...C];k.splice(y,1);const v=k.reduce((g,D)=>g+D,0);return v>0?k.map(g=>g/v*100):[]}),r(0)},[t,f,c,r]),j=o.useCallback((y,C)=>{C.preventDefault();const k=d.current;if(!k)return;const v=C.clientX,g=k.offsetWidth,D=i.length===w?[...i]:Ho(w),M=P=>{const V=(P.clientX-v)/g*100,L=[...D];L[y]=Math.max(15,D[y]+V),L[y+1]=Math.max(15,D[y+1]-V),c(L)},I=()=>{document.removeEventListener("mousemove",M),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",M),document.addEventListener("mouseup",I)},[i,w,c]),b=o.useCallback((y,C,k)=>{if(w>=4)return;const v=k==="left"?C:C+1;t(g=>{const D=vr(g,f).assignments,M=new Map;for(const I of u){const P=D.get(I.tabKey)??0,K=P>=v?P+1:P;K>0&&M.set(I.tabKey,K)}return v>0&&M.set(y,v),M}),c(g=>{const D=g.length===w?[...g]:Ho(w),M=D[C]??100/w,I=Math.max(15,M/2),P=Math.max(15,M/2),K=[...D];K[C]=I,K.splice(v,0,P);const V=K.reduce((L,R)=>L+R,0);return K.map(L=>L/V*100)}),n(g=>{const D=Wo(g,v);return D[v]=y,D}),a(g=>{const D=Wo(g,v);return D[v]=[y],D}),r(v)},[w,t,f,u,c,n,a,r]);o.useEffect(()=>{Kp(e,m)||t(m)},[e,m,t]),o.useEffect(()=>{const{mapping:y,usedGroups:C}=h;n(k=>{const v=Oo(k,y);return Ko(k,v)?k:v}),a(k=>{const v=Oo(k,y);return Ko(k,v)?k:v}),r(k=>{const v=l?0:Wp(k,C,y);return k===v?k:v}),c(k=>{const v=l?[]:Hp(k,C,h.groupCount);return Op(k,v)?k:v})},[h,l,n,a,r,c]);const N=o.useMemo(()=>{const y=Array.from({length:w},()=>[]);for(const C of u){const k=m.get(C.tabKey)??0,v=Math.min(k,w-1);y[v].push(C)}return y},[u,m,w]),T=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:d,normalizedGroupAssignments:m,numGroups:w,isSplitMode:S,groupedConvs:N,moveTabToGroup:p,closeGroup:x,handleResizeStart:j,splitTabRelative:b,clearAllSplits:T}}function Up({ides:e,sendDaemonCommand:t}){const r="0.9.23",n=o.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:Mc(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(w=>({...w,[d]:"upgrading"}));try{const w=await t(d,"daemon_upgrade",{});(h=w==null?void 0:w.result)!=null&&h.upgraded||(m=w==null?void 0:w.result)!=null&&m.success?u(S=>({...S,[d]:"done"})):u(S=>({...S,[d]:"error"}))}catch{u(w=>({...w,[d]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}const zc=80;function Pr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function zp(e){return{...e,createdAt:Pr(e.createdAt),updatedAt:Pr(e.updatedAt,e.createdAt),lastEventAt:Pr(e.lastEventAt,e.updatedAt||e.createdAt)}}function Vp(e){const t=Ca(e);return t==="unknown:"?e.id:t}function Gp(e){return[e.type,Zi(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function qp(e,t=zc){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Vp(n),i=r.get(a);if(!i){r.set(a,n);continue}(n.updatedAt>i.updatedAt||n.updatedAt===i.updatedAt&&n.createdAt>i.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const i=a.updatedAt-n.updatedAt;return i!==0?i:a.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function Yp(e,t){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?t.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=Qr(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const u=Pr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),f=Gp({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(zp({id:f,dedupKey:f,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Yi(a),preview:om(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return qp(n)}function Xp(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Jp(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=zc}=e,a=o.useMemo(()=>Yp(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>Xp(a),[a]);return{notifications:a,unreadCount:i}}function Qp({notifications:e,sendDaemonCommand:t}){const r=o.useCallback(i=>{const c=e.find(u=>u.id===i),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,t]),n=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}function tn(...e){const t=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();t.has(c)||(t.add(c),r.push(i))};for(const a of e){if(Array.isArray(a)){for(const i of a)n(i);continue}n(a)}return r}function Zp(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const r=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function sn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=Zp(r);if(n)return n}return"C:\\"}for(const r of t){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function eh(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const r=t.includes("\\")?"\\":"/",n=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(n[0]||"")?n.length<=2?`${n[0]}\\`:n.slice(0,-1).join("\\"):n.length<=2?r:n.slice(0,-1).join(r)||r}function th(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function rn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=th(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 sh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Fo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function rh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function nh({ides:e,conversations:t,onOpenSession:r}){const[n,a]=o.useState(null),i=o.useCallback(c=>{a(c)},[]);return o.useEffect(()=>{if(!n)return;const c=Fo(n.workspacePath),l=e.find(f=>{var S,p,x,j;if(!f||f.type==="adhdev-daemon"||sh(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 b=Fo(f.workspace||f.runtimeWorkspaceLabel);return b?b===c:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((j=(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:j.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const u=sc({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});u&&(a(null),r(u))},[t,e,r,n]),o.useEffect(()=>{if(!n)return;const c=window.setTimeout(()=>{a(l=>!l||l.startedAt!==n.startedAt?l:null)},45e3);return()=>window.clearTimeout(c)},[n]),{trackPendingLaunch:i}}function ah({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=o.useCallback(async(m,w)=>rn(e,m,w),[e]),l=o.useCallback(async(m,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const S=await e(m,"workspace_add",{path:w.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,w,S)=>{var p;try{const x={ideType:w,enableCdp:!0};(p=S==null?void 0:S.workspacePath)!=null&&p.trim()&&(x.workspace=S.workspacePath.trim());const j=await e(m,"launch_ide",x);return!(j!=null&&j.success)&&(j==null?void 0:j.success)!==void 0?{ok:!1,error:(j==null?void 0:j.error)||"Could not launch IDE"}:(t({machineId:m,kind:"ide",providerType:w,workspacePath:(S==null?void 0:S.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Could not launch IDE"}}},[e,t]),f=o.useCallback(async(m,w,S,p)=>{var j,b,N;const x=Date.now();try{const T={cliType:S};(j=p==null?void 0:p.workspacePath)!=null&&j.trim()?T.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(T.workspaceId=p.workspaceId),(b=p==null?void 0:p.resumeSessionId)!=null&&b.trim()&&(T.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(T.cliArgs=p.cliArgs),(N=p==null?void 0:p.initialModel)!=null&&N.trim()&&(T.initialModel=p.initialModel.trim());const y=await e(m,"launch_cli",T),C=(y==null?void 0:y.result)||y,k=(C==null?void 0:C.sessionId)||(C==null?void 0:C.id);return y!=null&&y.success&&k?(r(k),{ok:!0}):y!=null&&y.success?(t({machineId:m,kind:w,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 ${w.toUpperCase()} session`}}catch(T){return rh(T)?(t({machineId:m,kind:w,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:T instanceof Error?T.message:`Could not launch ${w.toUpperCase()} session`}}},[r,e,t]),d=o.useCallback(async(m,w)=>{if(!m||!w)return[];try{const S=await e(m,"list_saved_sessions",{providerType:w,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 Kc({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 oh(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 ih(e,t,r=Date.now()){return!e||!oh(t)?null:{tabKey:e,nonce:r}}function ch({isMobile:e,conversations:t,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,j;if(!e){if(l){const b=t.find(N=>N.tabKey===l);if(b)return b}return r[0]}const p=n[a];if(p){const b=t.find(N=>N.tabKey===p);if(b)return b}return((x=i[a])==null?void 0:x[0])||((j=i[0])==null?void 0:j[0])},[t,l,a,n,i,e,r]),m=o.useCallback(p=>{u(p)},[]),w=o.useCallback(p=>{u(p.tabKey),c(x=>{const j=new URLSearchParams(x),b=cm(p);return b?j.set("activeTab",b):j.delete("activeTab"),j},{replace:!0})},[c]),S=o.useCallback((p,x)=>{const j=ih(p,x);j&&d(j)},[]);return{activeConv:h,openDesktopConversation:w,requestScrollToBottom:S,scrollToBottomRequest:f,setDesktopActiveTab:m}}function lh({activeConv:e,remoteDialogConv:t,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([]),[w,S]=o.useState(()=>ht()),[p,x]=o.useState(!1),[j,b]=o.useState(null),N=o.useRef(null),T=o.useMemo(()=>r||t||e,[e,r,t]),y=!!T&&Je(T)&&!qe(T),C=o.useMemo(()=>{if(!T||!y)return null;const R=T.daemonId||T.routeId||"",G=Kt(T);return`${R}:${G}`},[T,y]),{isCreatingChat:k,isRefreshingHistory:v,handleSwitchSession:g,handleNewChat:D,handleRefreshHistory:M}=Uc({sendDaemonCommand:a,activeConv:T,chats:(L=n.find(R=>R.id===(T==null?void 0:T.routeId)))==null?void 0:L.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),I=o.useCallback(()=>{d(!0)},[]),P=o.useCallback(()=>{d(!1)},[]),K=o.useCallback(async()=>{if(!(!T||!y||p)){x(!0);try{const R=T.daemonId||T.routeId,G=Kt(T),B=await a(R,"list_saved_sessions",{agentType:G,providerType:G,kind:"cli",limit:50}),E=(B==null?void 0:B.result)??B;m(Array.isArray(E==null?void 0:E.sessions)?E.sessions:[])}catch(R){console.error("Refresh saved sessions failed",R),m([])}finally{x(!1)}}},[T,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,K())},[K,f,p,y,C]);const V=o.useCallback(async R=>{if(!T||!y||!R.providerSessionId||!R.workspace)return;const G=T.daemonId||T.routeId,B=Kt(T);try{b(R.providerSessionId);const E=await a(G,"launch_cli",{cliType:B,dir:R.workspace,resumeSessionId:R.providerSessionId,initialModel:Hi(R.summaryMetadata,"model",{preferShortValue:!0})||void 0}),W=(E==null?void 0:E.result)??E,J=typeof(W==null?void 0:W.sessionId)=="string"?W.sessionId:typeof(W==null?void 0:W.id)=="string"?W.id:"";J&&u(be=>{const he=new URLSearchParams(be);return he.set("activeTab",J),he},{replace:!0}),P()}catch(E){console.error("Resume saved session failed",E)}finally{b(null)}},[P,T,y,a,u]);return{historyModalOpen:f,openHistoryModal:I,closeHistoryModal:P,historyTargetConv:T,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:k,isHistoryRefreshingHistory:v,handleHistorySwitchSession:g,handleHistoryNewChat:D,handleHistoryRefresh:M,savedHistorySessions:h,savedHistoryFilters:w,setSavedHistoryFilters:S,isSavedHistoryLoading:p,resumingSavedHistorySessionId:j,handleRefreshSavedHistory:K,handleResumeSavedHistorySession:V}}function dh({isMobile:e,location:t,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 j=l(n);return j&&!Je(j)&&!qe(j)?j:null},[e,n,l]),w=o.useMemo(()=>{const j=u==null?void 0:u.routeId;if(!j)return null;const b=u!=null&&u.tabKey?i.find(N=>N.tabKey===u.tabKey):a?i.find(N=>N.tabKey===a):null;return(b==null?void 0:b.routeId)===j?b:_t(i,j)},[i,u,a]),S=o.useMemo(()=>{if(w)return c.find(j=>j.id===w.routeId)},[c,w]);o.useEffect(()=>{m&&(f({routeId:m.routeId,tabKey:So(m)}),h(m),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,m]);const p=o.useCallback(j=>{j&&(f({routeId:j.routeId,tabKey:So(j)}),h(j))},[]),x=o.useCallback(()=>{f(null),h(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:S,remoteDialogActiveConv:d,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:x}}function uh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:u,sendDaemonCommand:f}){const{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:m,setRemoteDialogActiveConv:w,openRemoteDialog:S,closeRemoteDialog:p}=dh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[x,j]=o.useState(!1),[b,N]=o.useState(null),T=o.useCallback(async k=>{const v=k||u;!v||!Je(v)&&!qe(v)||(N(v),j(!0))},[u]),y=o.useCallback(()=>{j(!1),N(null)},[]),C=o.useCallback(async k=>{const v=b||u;if(!v||!Je(v)&&!qe(v)){y();return}j(!1);try{const g=Kt(v),D=v.routeId||v.daemonId||"";await f(D,"stop_cli",{cliType:g,targetSessionId:v.sessionId,mode:k})}catch(g){console.error("Stop CLI failed:",g)}finally{N(null)}},[u,y,b,f]);return{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:m,setRemoteDialogActiveConv:w,openRemoteDialog:S,closeRemoteDialog:p,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:T,cancelCliStop:y,confirmCliStop:C}}function Vc(){return"select_session"}function mh(){return"open_panel"}function fh({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function ph(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Uo(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function zo(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Fa(e){return e instanceof Error?e.message:String(e||"")}function Vo(e){const t=Fa(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Go(e,t){const r=Fa(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function nn({sendDaemonCommand:e,activeConv:t,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)},[t==null?void 0:t.tabKey]);const m=o.useCallback(async x=>{if(!t)return!1;const j=x.trim(),b=Aa(t);if(fh({hasMessage:!!j,blockedMessage:b,sendInFlight:d.current}))return b&&f(b),!1;const N=Date.now(),T={tabKey:t.tabKey,message:j,timestamp:N};if(ph(h.current,T))return f(null),!0;d.current=!0,l(!0),f(null),h.current=T;try{const y=Js(t);if(!y)return h.current=Uo(h.current,T),f("Unable to send message right now."),!1;const C=await e(y,"send_chat",{message:j,...js(t)}),k=zo(C);if(k!=null&&k.deduplicated)return f(null),!0;if((k==null?void 0:k.sent)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");if((k==null?void 0:k.success)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");return f(null),!0}catch(y){const C=Fa(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=Uo(h.current,T),f(Am(y)),!1}finally{d.current=!1,l(!1)}},[t,e]),w=o.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(x){console.error("Relaunch failed",x)}},[t,e]),S=o.useCallback(async x=>{if(t)try{const b=(t.modalButtons||[]).indexOf(x),N=x.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),T=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),y=Js(t);if(!y)return;const C=await e(y,"resolve_action",{button:x,action:T?"approve":"reject",...b>=0&&{buttonIndex:b},...js(t)}),k=zo(C);k.success||r(v=>[...v,{routeId:t.tabKey,text:Go(x,k==null?void 0:k.error),timestamp:Date.now()}])}catch(j){Vo(j)||console.error("[ModalButton] Error:",j),r(b=>[...b,{routeId:t.tabKey,text:Vo(j)?Go(x,j):`❌ **${x}** error`,timestamp:Date.now()}])}},[t,e,r]),p=o.useCallback(async()=>{if(!(!t||a)){i(!0);try{await e(t.routeId,mh(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(x){console.error("Focus agent failed",x)}finally{i(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:u,isFocusingAgent:a,handleSendChat:m,handleRelaunch:w,handleModalButton:S,handleFocusAgent:p}}function In(e,t=!0){return(e??!0)&&t}const Ua=o.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d=null,handleFocusAgent:h,isFocusingAgent:m,actionLogs:w,userName:S,scrollToBottomRequestNonce:p,isInputActive:x=!0,isVisible:j=!0}){const[b,N]=o.useState(n),T=o.useRef(n);o.useEffect(()=>{const I=T.current;if(T.current=n,!n){N(!1);return}if(I){N(!0);return}N(!1);let P=0,K=0;return P=window.requestAnimationFrame(()=>{K=window.requestAnimationFrame(()=>{N(!0)})}),()=>{window.cancelAnimationFrame(P),window.cancelAnimationFrame(K)}},[n]);const y=n&&b,C=!n||!b,k=In(j,n),v=In(j,C),g=In(j),D=_c(t),M=D.status||D.modalMessage||D.modalButtons?{...t,...D.status?{status:D.status}:{},...D.modalMessage!==void 0?{modalMessage:D.modalMessage}:{},...D.modalButtons!==void 0?{modalButtons:D.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx($i,{activeConv:M,onModalButton:c}),M.transport!=="pty"&&M.transport!=="acp"&&M.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(qs,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:l,children:"Relaunch with CDP"})]})}):null,M.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:y?"visible":"hidden",pointerEvents:y?"auto":"none"},children:s.jsx(tf,{activeConv:M,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,isVisible:k,isInputActive:x&&k})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(na,{activeConv:M,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:m,actionLogs:w,userName:S,scrollToBottomRequestNonce:p,isInputActive:x&&v,isVisible:v})})]}):s.jsx(na,{activeConv:M,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:m,actionLogs:w,userName:S,scrollToBottomRequestNonce:p,isInputActive:x&&g,isVisible:g})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function hh({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:f,onOpenNativeConversation:d,onOpenMachine:h,onOpenHistory:m,onOpenRemote:w,onHideConversation:S,onStopCli:p,cliViewMode:x,onSetCliViewMode:j,handleSendChat:b,handleFocusAgent:N,handleModalButton:T,handleRelaunch:y}){const C=o.useRef(null),k=Je(e)&&!t,v=k&&x==="terminal",g=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${g} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:f,type:"button","aria-label":"Back",children:s.jsx(xa,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:tt(e)}),s.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:s.jsx(rc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>h(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[k&&x&&s.jsx(Ta,{mode:x,onChange:j,compact:!0}),k&&p&&s.jsx("button",{onClick:()=>{p(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(wt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(e),type:"button",children:s.jsx(ba,{size:14})}),!t&&!k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:s.jsx(Ct,{size:14})}),S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Close chat",children:s.jsx(wt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(Ua,{activeConv:e,clearToken:0,isCliTerminal:v,ideEntry:n,terminalRef:C,handleModalButton:T,handleRelaunch:y,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:N,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const An={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function xh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Gc(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(xh())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(An[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:An[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:An[c].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function qc({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Ct},{key:"chats",label:"Chats",icon:Ft}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:i})=>{const c=e===n;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(n),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(i,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function wr({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function hs({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function Ds({icon:e,title:t,subtitle:r,children:n}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function jr({item:e,type:t,getAvatarText:r,onOpenConversation:n}){const a=t==="needs_attention"||t==="task_complete",i=t==="working",c=t==="earlier",l=t==="task_complete",{isReconnecting:u,isConnecting:f}=Ms(e.conversation),d=tt(e.conversation),h=us(e.conversation),m=mc(e.conversation,{requiresAction:t==="needs_attention"}),w=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",j=c?"text-text-secondary opacity-80":"text-text-muted",b=c?"text-text-muted opacity-80":"text-text-muted",N="text-[color:var(--status-warning)]";return s.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${w}`,onClick:()=>n(e.conversation),type:"button",children:[a||i?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${S}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(d)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${p}`,children:d}),!i&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${b}`,children:Ei(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${x}`,children:[h,u?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${N} animate-pulse`,children:"Reconnecting…"})]}):f?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):m==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:N,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${j}`,children:e.preview})]}),a&&!l&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),i&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]},e.conversation.tabKey)}function qo({size:e=32,label:t}){return s.jsxs("div",{className:"flex flex-col items-center gap-2.5",children:[s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}}),t&&s.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:t})]})}function bh({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:f,onShowAllHidden:d,onOpenNewSession:h,onOpenMachine:m,onOpenSettings:w,onSectionChange:S,wsStatus:p="connected",isStandalone:x=!1}){const j=p==="disconnected"||p==="reconnecting"||p==="offline"||p==="auth_failed",b=c.length>0,N=t.length>0||r.length>0||n.length>0||a.length>0,T=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 s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${y}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:T}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Xr,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:w,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Yr,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${C}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:j?s.jsx(Ds,{icon:s.jsx(qo,{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?s.jsx(Ds,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:x?"Waiting for your daemon":"Connect your machines",subtitle:x?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!x&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Gc,{})})}):s.jsx(hs,{children:c.map((k,v)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>m(k.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(k.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:k.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:k.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[k.unread," new"]}):k.total>0?`${k.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:k.subtitle}),k.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[k.total," chat",k.total!==1?"s":"",k.unread>0?` · ${k.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},k.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Needs attention",className:"mb-0"}),s.jsx(hs,{children:t.map((k,v)=>s.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(hs,{children:r.map((k,v)=>s.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"task_complete",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(hs,{children:n.map((k,v)=>s.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"working",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(wr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(hs,{children:a.map((k,v)=>s.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"earlier",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))}):N?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):j?s.jsx(Ds,{icon:s.jsx(qo,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):b?s.jsx(Ds,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Ft,{size:20})}),title:"No conversations yet",subtitle:hc,children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":$t,title:$t,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:$t})]})}):s.jsx(Ds,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[s.jsx("span",{children:"Hidden"}),s.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:d,children:"Restore all"})]}),s.jsx(hs,{className:"bg-bg-secondary/25",children:i.map((k,v)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] opacity-50 saturate-0 ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(k),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(tt(k))}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:tt(k)}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:us(k)}),s.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},k.tabKey))})]})]}),e==="chats"&&h&&N&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":$t,title:$t,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),s.jsx(qc,{section:e,onSectionChange:S})]})}function gh(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 Yc(e){const t=[e.workspace||"Workspace unknown"],r=ds(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=gh(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function an({title:e,description:t,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=eh(r),w=d.trim();return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:s.jsx(wt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!m||a||u(m)},disabled:!m||a,children:[s.jsx(xa,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:S=>h(S.target.value),onKeyDown:S=>{S.key!=="Enter"||!w||a||(S.preventDefault(),u(w))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!w||a||u(w)},disabled:!w||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(S=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(S.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Ss,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:S.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:S.path})]})]},S.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>f(w||r),disabled:!w&&!r||a,children:c})]})]})})}function za({title:e,description:t,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:w,onModelChange:S,historyProviderNode:p,onConfirm:x,onCancel:j}){const b=n==null?void 0:n.find(N=>N.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:j,"aria-label":"Close launch confirmation",children:s.jsx(wt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:N=>i(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(N=>s.jsx("option",{value:N.key,children:N.label},N.key))}),(b==null?void 0:b.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:b.description})]}),p,r.map(N=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:N.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${N.value}`)),m&&S&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:w||"",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&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:d||"",onChange:N=>h(N.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:j,disabled:u,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:x,disabled:u,children:[s.jsx(ya,{size:14}),u?l:c]})]})]})})}function Yo(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function os(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${Yo(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:Yo(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 yh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function vh(e){return[yh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function wh(e){return e.lastLaunchedAt?Jr(e.lastLaunchedAt):""}function Xc(e){return{metaText:vh(e),updatedLabel:wh(e)}}function Mn(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function jh({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var ut,mt,Xe,rt;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(je=>({id:je.id,path:je.path,label:je.label})),[e]),h=e.defaultWorkspaceId||null,[m,w]=o.useState(h||((mt=d[0])==null?void 0:mt.id)||""),[S,p]=o.useState(""),[x,j]=o.useState(""),[b,N]=o.useState([]),[T,y]=o.useState(!1),[C,k]=o.useState(""),[v,g]=o.useState(!1),[D,M]=o.useState(Mn(f,t.length,r.length)),I=o.useRef(null),[P,K]=o.useState(null),V=o.useRef("__home__"),[L,R]=o.useState("__home__"),[G,B]=o.useState(""),[E,W]=o.useState(""),[J,be]=o.useState(""),[he,de]=o.useState([]),[ye,ge]=o.useState(()=>ht().textQuery),[ve,z]=o.useState(()=>ht().workspaceQuery),[F,Q]=o.useState(()=>ht().modelQuery),[ue,te]=o.useState(()=>ht().resumableOnly),[fe,ne]=o.useState(()=>ht().sortMode),[xe,re]=o.useState(!1),[le,oe]=o.useState(!1),Y=o.useRef(null),X=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const ae=m==="__custom__"?S.trim():((Xe=d.find(je=>je.id===m))==null?void 0:Xe.path)||"",A=m==="__custom__"&&!!ae&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),H=m!=="__custom__"&&((rt=d.find(je=>je.id===m))==null?void 0:rt.path)||"",ce=o.useMemo(()=>(e.recentLaunches||[]).map(je=>je.workspace),[e]),me=o.useCallback(async je=>{y(!0),k("");try{const Ee=await a(je);j(Ee.path),p(Ee.path),N(Ee.directories)}catch(Ee){k(Ee instanceof Error?Ee.message:"Could not load folder")}finally{y(!1)}},[a]),we=o.useCallback(()=>{var Ee;w("__custom__"),g(!0);const je=sn(e.platform,tn(S.trim(),H,ce,e.defaultWorkspacePath,(Ee=d.find(Be=>Be.id===h))==null?void 0:Ee.path,d.map(Be=>Be.path)));me(je)},[S,h,me,ce,H,e.platform,d]),_e=o.useCallback(je=>{if(je!=null&&je.workspaceId){w(je.workspaceId),p("");return}if(je!=null&&je.workspacePath){w("__custom__"),p(je.workspacePath);return}w(""),p("")},[]),Ae=o.useCallback(je=>{if(w(je),je==="__custom__"){we();return}p("")},[we]),Ke=o.useCallback(je=>{w("__custom__"),p(je)},[]),Fe=o.useCallback((je,Ee)=>{I.current=Ee,V.current=je.selectedWorkspaceKey||"__home__",R(je.selectedWorkspaceKey||"__home__"),B(je.initialArgs||""),W(je.initialModel||""),be(""),de([]);const Be=je.providerType?`${e.id}:${je.providerType}`:null;if(lf(X.current,Be)){const nt=ht();ge(nt.textQuery),z(nt.workspaceQuery),Q(nt.modelQuery),te(nt.resumableOnly),ne(nt.sortMode)}X.current=Be,K(je),je.providerType&&i&&(re(!0),i(je.providerType).then(nt=>de(nt||[])).catch(nt=>console.warn("Failed to load saved sessions",nt)).finally(()=>re(!1)))},[i,e.id]),ze=o.useMemo(()=>xc(he,{textQuery:ye,workspaceQuery:ve,modelQuery:F,resumableOnly:ue,sortMode:fe}),[F,ue,he,fe,ye,ve]);o.useEffect(()=>{J&&(ze.some(je=>je.providerSessionId===J)||be(""))},[ze,J]);const ot=o.useCallback(()=>{I.current&&(oe(!0),I.current().finally(()=>{I.current=null,oe(!1),K(null)}))},[]),it=o.useCallback(()=>{I.current=null,K(null)},[]),dt=o.useCallback(je=>{V.current=je,R(je)},[]);return o.useEffect(()=>{var je;Y.current!==e.id&&(Y.current=e.id,w(h||((je=d[0])==null?void 0:je.id)||"__custom__"),p(""),j(""),N([]),k(""),g(!1),ge(ht().textQuery),z(ht().workspaceQuery),Q(ht().modelQuery),te(ht().resumableOnly),ne(ht().sortMode),X.current=null,M(Mn(f,t.length,r.length)))},[r.length,t.length,h,f,e.id,d]),o.useEffect(()=>{var je;m!=="__custom__"&&(m&&d.some(Ee=>Ee.id===m)||w(h||((je=d[0])==null?void 0:je.id)||"__custom__"))},[h,m,d]),o.useEffect(()=>{D==="ide"&&f||D==="cli"&&t.length>0||D==="acp"&&r.length>0||M(Mn(f,t.length,r.length))},[D,r.length,t.length,f]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:f,workspaceRows:d,defaultWorkspaceId:h,workspaceChoice:m,customWorkspacePath:S,browseCurrentPath:x,browseDirectories:b,browseBusy:T,browseError:C,browseDialogOpen:v,activeLauncherKind:D,launchConfirm:P,launchConfirmWorkspaceKeyRef:V,launchConfirmWorkspaceKey:L,launchConfirmArgs:G,launchConfirmModel:E,launchConfirmResumeId:J,launchConfirmSavedSessions:he,launchConfirmTextFilter:ye,launchConfirmWorkspaceFilter:ve,launchConfirmModelFilter:F,launchConfirmResumableOnly:ue,launchConfirmSortMode:fe,filteredLaunchConfirmSavedSessions:ze,launchConfirmSessionsLoading:xe,launchConfirmBusy:le,resolvedWorkspacePath:ae,canCreateMissingWorkspace:A,openBrowseDialog:we,loadBrowsePath:me,handleWorkspaceChoiceChange:Ae,chooseCustomWorkspacePath:Ke,setCustomWorkspacePath:p,setBrowseDialogOpen:g,setActiveLauncherKind:M,openLaunchConfirm:Fe,handleConfirmLaunch:ot,closeLaunchConfirm:it,setWorkspaceSelectionFromOption:_e,setLaunchConfirmWorkspaceKeyAndSync:dt,setLaunchConfirmArgs:B,setLaunchConfirmModel:W,setLaunchConfirmResumeId:be,setLaunchConfirmTextFilter:ge,setLaunchConfirmWorkspaceFilter:z,setLaunchConfirmModelFilter:Q,setLaunchConfirmResumableOnly:te,setLaunchConfirmSortMode:ne}}function kh({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:f,showBottomNav:d,onBack:h,onSectionChange:m,onOpenConversation:w,onOpenRecent:S,onOpenMachineDetails:p,onMachineUpgrade:x,onLaunchDetectedIde:j,onAddWorkspace:b,onBrowseDirectory:N,onLaunchWorkspaceProvider:T,onListSavedSessions:y}){const C=L=>L==="ide"?"IDE":L==="cli"?"CLI":"ACP",k=r.slice(0,4),v=t.slice(0,3),g=jh({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:y}),D=o.useMemo(()=>k.map(L=>{const{metaText:R,updatedLabel:G}=Xc(L);return{key:`recent-launch:${L.id}`,primary:L.label,secondary:R,updatedLabel:G,onClick:()=>{const{options:B,selectedKey:E}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspacePath:L.workspace});g.openLaunchConfirm({title:L.kind==="ide"?ss("restart-ide",L.label):L.providerSessionId?Pa(L.label):ss("start-fresh",L.label),description:L.kind==="ide"?rs("restart-ide"):L.providerSessionId?_a():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?La(!0):Is("start-fresh"),workspaceOptions:B,selectedWorkspaceKey:E,details:[{label:"Mode",value:C(L.kind)},...L.providerType?[{label:"Provider",value:L.providerType}]:[]]},async()=>{const W=B.find(J=>J.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(W),await S({...L,workspace:(W==null?void 0:W.workspacePath)??null})})}}}),[g,S,k]),M=o.useMemo(()=>v.map(L=>({key:`recent-chat:${L.conversation.tabKey}`,primary:tt(L.conversation),secondary:Jm(L.conversation,{timestampLabel:L.timestamp?Ei(L.timestamp):null}),unread:L.unread,onClick:()=>w(L.conversation)})),[w,v]),I=g.showAllRecent?D:D.slice(0,4),P=D.length>0,K=M.length>0,V=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${V} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:s.jsx(xa,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Mt(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[K&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:M.map(L=>s.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:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:L.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))})]}),P&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:I.map(L=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:L.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:L.primary}),L.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:L.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))}),D.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>g.setShowAllRecent(L=>!L),children:g.showAllRecent?"Show fewer":`Show ${D.length-4} more`})})]}),(g.hasIdeOptions||n.length>0||a.length>0)&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:s.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),s.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),s.jsx("select",{value:g.workspaceChoice,onChange:L=>g.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:g.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[g.workspaceRows.map(L=>s.jsxs("option",{value:L.id,children:[L.id===g.defaultWorkspaceId?"⭐ ":"",Zr(L.path,L.label)||L.path]},L.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),g.workspaceChoice==="__custom__"&&s.jsxs("div",{className:"flex flex-col gap-2.5",children:[s.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Ss,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),s.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:g.resolvedWorkspacePath||g.browseCurrentPath||"No folder selected yet."})]})]})}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:g.openBrowseDialog,children:"Select workspace…"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{g.resolvedWorkspacePath&&b(g.resolvedWorkspacePath)},disabled:!g.resolvedWorkspacePath||g.browseBusy,children:"Save as workspace"})]})]}),g.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[g.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.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:()=>g.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.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:()=>g.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.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:()=>g.setActiveLauncherKind("acp"),children:"ACP"})]}),g.activeLauncherKind&&s.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[s.jsx("div",{className:"text-xs font-bold text-text-secondary",children:g.activeLauncherKind==="ide"?"Choose an IDE":g.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:g.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(L=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:R,selectedKey:G}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.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(E=>E.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(B),j(L.type,{workspacePath:(B==null?void 0:B.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:L.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},L.type)):(g.activeLauncherKind==="cli"?n:a).map(L=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const R=g.activeLauncherKind==="cli"?"cli":"acp",{options:G,selectedKey:B}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.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 E=G.find(W=>W.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(E),T(R,L.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.workspacePath)??null,args:g.launchConfirmArgs,model:g.launchConfirmModel,resumeSessionId:g.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[L.icon?`${L.icon} `:"",L.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},L.type))})]}),l.message&&s.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,g.canCreateMissingWorkspace&&s.jsx("div",{className:"mt-2",children:s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>b(g.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:x,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:p,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),g.browseDialogOpen&&s.jsx(an,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:g.browseCurrentPath,directories:g.browseDirectories,busy:g.browseBusy,error:g.browseError,confirmLabel:"Use this folder",onClose:()=>g.setBrowseDialogOpen(!1),onNavigate:L=>{g.loadBrowsePath(L)},onConfirm:L=>{g.chooseCustomWorkspacePath(L),g.setBrowseDialogOpen(!1)}}),g.launchConfirm&&s.jsx(za,{title:g.launchConfirm.title,description:g.launchConfirm.description,details:g.launchConfirm.details,workspaceOptions:g.launchConfirm.workspaceOptions,selectedWorkspaceKey:g.launchConfirmWorkspaceKey,onWorkspaceChange:g.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:g.launchConfirm.providerType?Ur(!!g.launchConfirmResumeId):g.launchConfirm.confirmLabel,busyLabel:g.launchConfirm.providerType?void 0:g.launchConfirm.busyLabel,busy:g.launchConfirmBusy,showArgsInput:g.launchConfirm.showArgsInput,argsValue:g.launchConfirmArgs,onArgsChange:g.setLaunchConfirmArgs,showModelInput:g.launchConfirm.showModelInput,modelValue:g.launchConfirmModel,onModelChange:g.setLaunchConfirmModel,historyProviderNode:g.launchConfirm.providerType&&(g.launchConfirmSessionsLoading||g.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),g.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Ra()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:g.launchConfirmTextFilter,onChange:L=>g.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:g.launchConfirmWorkspaceFilter,onChange:L=>g.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:g.launchConfirmModelFilter,onChange:L=>g.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsxs("select",{value:g.launchConfirmSortMode,onChange:L=>g.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:g.launchConfirmResumableOnly,onChange:L=>g.setLaunchConfirmResumableOnly(L.target.checked),disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:g.launchConfirmResumeId,onChange:L=>g.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:mf()}),g.filteredLaunchConfirmSavedSessions.map(L=>s.jsxs("option",{value:L.providerSessionId,disabled:!L.canResume,children:[L.title||L.providerSessionId," ",L.canResume?"":"(workspace missing)"]},L.providerSessionId))]}),!g.launchConfirmSessionsLoading&&g.launchConfirmSavedSessions.length>0&&g.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),g.launchConfirmResumeId&&(()=>{const L=g.filteredLaunchConfirmSavedSessions.find(G=>G.providerSessionId===g.launchConfirmResumeId);if(!L)return null;const R=Yc(L);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:R.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:R.providerSessionId}),s.jsx("div",{className:"mt-1",children:R.metaLine}),R.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:R.updatedLabel}),R.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:R.preview})]})})()]}),onConfirm:g.handleConfirmLaunch,onCancel:g.closeLaunchConfirm}),d&&s.jsx(qc,{section:f,onSectionChange:m})]})}function Sh(e){var r;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":"Offline"}function Nh(e,t){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:ds(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,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 Ch(e,t){const r=new Map;for(const n of t){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=Jn(n),u=a.filter(h=>h.unread||h.requiresAction).length,f=Sh(n),d=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:Mt(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?Qm(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 Ih(e){return e==="chat"}function kr(e,t){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function Ah({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:w,setSelectedTabKey:S,setScreen:p,setSelectedMachineId:x,setSection:j,setMachineBackTarget:b,resetMachineAction:N}){const T=o.useRef(null),y=o.useCallback(C=>{if(!(C!=null&&C.sessionId))return;const k=Or(C,c),v=Math.max(Date.now(),es(C),k.lastUpdated||0);kr("mark_read:start",{tabKey:C.tabKey,sessionId:C.sessionId,displayPrimary:tt(C),inboxBucket:k.inboxBucket,unread:k.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:es(C),readAt:v}),l(fs(C)||C.routeId,"mark_session_seen",{sessionId:C.sessionId,seenAt:v}).then(g=>{kr("mark_read:result",{tabKey:C.tabKey,sessionId:C.sessionId,result:g})}).catch(g=>{kr("mark_read:error",{tabKey:C.tabKey,sessionId:C.sessionId,error:g instanceof Error?g.message:String(g)})})},[c,l]);return o.useEffect(()=>{var k;if(!n){Ih(i)&&p("inbox"),S(((k=e[0])==null?void 0:k.tabKey)||null),T.current=null;return}if(i!=="chat"){T.current=null;return}const C=`${n.tabKey}:${n.sessionId||""}`;T.current!==C&&(T.current=C,y(n))},[e,y,i,n,p,S]),o.useEffect(()=>{if(!u)return;const C=e.find(k=>k.tabKey===u);C&&(S(C.tabKey),p("chat"),f==null||f())},[e,f,u,p,S]),o.useEffect(()=>{if(!d)return;const C=t.find(k=>k.id===d);C&&(x(C.id),N(),j("machines"),b("inbox"),p("machine"),h==null||h())},[t,h,d,N,b,p,j,x]),o.useEffect(()=>{m&&(j(m),p("inbox"),w==null||w())},[w,m,p,j]),o.useEffect(()=>{const C=r.filter(k=>k.inboxBucket==="task_complete"||k.unread);C.length!==0&&kr("inbox_state",{screen:i,selectedTabKey:a,items:C.map(k=>{const v=Or(k.conversation,c);return{liveState:v,tabKey:k.conversation.tabKey,sessionId:k.conversation.sessionId,displayPrimary:tt(k.conversation),serverBucket:v.inboxBucket,computedBucket:k.inboxBucket,serverUnread:v.unread,computedUnread:k.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:es(k.conversation)}})})},[r,c,i,a]),{markConversationRead:y}}function Mh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Xo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Th(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Lh({sendDaemonCommand:e,navigate:t,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(b,N,T)=>{var y;try{i("loading"),l(`Launching ${N}…`);const C={ideType:N,enableCdp:!0};(y=T==null?void 0:T.workspacePath)!=null&&y.trim()&&(C.workspace=T.workspacePath.trim()),await e(b,"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(b,N,T)=>{if(N.trim())try{i("loading"),l(T!=null&&T.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(b,"workspace_add",{path:N.trim(),createIfMissing:(T==null?void 0:T.createIfMissing)===!0});if(y!=null&&y.success){i("done"),l(T!=null&&T.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]),w=o.useCallback(async b=>{var N,T,y,C,k,v;try{i("loading"),l("Starting daemon upgrade…");const g=await e(b,"daemon_upgrade",{});if((N=g==null?void 0:g.result)!=null&&N.alreadyLatest){i("done"),l(`Already on v${((T=g==null?void 0:g.result)==null?void 0:T.version)||"latest"}.`);return}if((y=g==null?void 0:g.result)!=null&&y.upgraded||(C=g==null?void 0:g.result)!=null&&C.success){i("done"),l(`Upgrade to v${((k=g==null?void 0:g.result)==null?void 0:k.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((v=g==null?void 0:g.result)==null?void 0:v.error)||"Upgrade failed")}catch(g){i("error"),l(g instanceof Error?g.message:"Upgrade failed")}},[e]),S=o.useCallback(async(b,N,T,y)=>{var v,g,D;const C=Date.now(),k={machineId:b,kind:N,providerType:T,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 ${T}…`),f(k);const M={cliType:T};(v=y==null?void 0:y.workspacePath)!=null&&v.trim()?M.dir=y.workspacePath.trim():y!=null&&y.workspaceId&&(M.workspaceId=y.workspaceId),y!=null&&y.resumeSessionId&&(M.resumeSessionId=y.resumeSessionId),(g=y==null?void 0:y.args)!=null&&g.trim()&&(M.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(D=y==null?void 0:y.model)!=null&&D.trim()&&(M.initialModel=y.model.trim());const I=await e(b,"launch_cli",M),P=(I==null?void 0:I.result)||I,K=(P==null?void 0:P.sessionId)||(P==null?void 0:P.id);if(I!=null&&I.success&&K){f(null),i("done"),l(`${T} launched`),t(Gt(K));return}if(I!=null&&I.success){i("loading"),l(`${T} 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(M){if(Th(M)){i("loading"),l(`${T} launch requested — waiting for session…`);return}f(null),i("error"),l(M instanceof Error?M.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),p=o.useCallback(async(b,N)=>{try{const T=await e(b,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),y=(T==null?void 0:T.result)??T;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(T){return console.error("Failed to list saved sessions on mobile:",T),[]}},[e]),x=o.useCallback(async(b,N)=>rn(e,b,N),[e]);o.useEffect(()=>{if(!u)return;const b=Xo(u.workspacePath),N=r.find(y=>{var M,I,P,K;if(!y||y.type==="adhdev-daemon"||Mh(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 g=String(y.providerSessionId||"");if(u.resumeSessionId&&g)return g===u.resumeSessionId;if(b){const V=Xo(y.workspace||y.runtimeWorkspaceLabel);return V?V===b:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((K=(P=(I=(M=y.activeChat)==null?void 0:M.messages)==null?void 0:I.at)==null?void 0:P.call(I,-1))==null?void 0:K.timestamp)||0)>=u.startedAt-5e3});if(!N)return;const T=sc({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});T&&(f(null),i("done"),l(`${u.providerType} launched`),t(Gt(T)))},[n,r,t,u]),o.useEffect(()=>{if(!u)return;const b=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(b)},[u]);const j=o.useCallback(async(b,N)=>{if(N.kind==="ide"&&N.providerType){await h(b,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await S(b,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:w,handleLaunchWorkspaceProvider:S,handleListSavedSessions:p,handleBrowseDirectory:x,handleOpenRecent:j}}function Rh({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:f}){const d=o.useCallback(j=>{i(j.tabKey),c("chat"),n(j)},[n,c,i]),h=o.useCallback(j=>{const b=e.find(N=>N.routeId===j.routeId&&N.streamSource==="native");b&&(i(b.tabKey),c("chat"),n(b))},[e,n,c,i]),m=o.useCallback(()=>{n(t),c("inbox")},[n,t,c]),w=o.useCallback((j,b="inbox")=>{l(j),a(),u("machines"),f(b),c("machine")},[a,f,c,u,l]),S=o.useCallback(j=>{const b=fs(j);b&&w(b,"chat")},[w]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),x=o.useCallback(j=>{u(j),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:h,backFromConversation:m,openMachine:w,openConversationMachine:S,backFromMachine:p,changeMachineSection:x}}function Ph(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Sr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function _h({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:w,onOpenHistory:S,onOpenRemote:p,onStopCli:x,wsStatus:j,isConnected:b,onShowHiddenConversation:N,onShowAllHiddenConversations:T,onHideConversation:y,onOpenNewSession:C,liveSessionInboxState:k,setCliViewModeOverrides:v}){const[g,D]=o.useState(()=>{var H;return((H=e[0])==null?void 0:H.tabKey)||null}),[M,I]=o.useState(()=>e[0]?"chat":"inbox"),[P,K]=o.useState("chats"),[V,L]=o.useState(null),[R,G]=o.useState("inbox"),B=As(),E="0.9.23",W=o.useMemo(()=>e.find(H=>H.tabKey===g)||e[0]||null,[e,g]),J=o.useMemo(()=>W?r.find(H=>H.id===W.routeId):void 0,[r,W]),be=o.useMemo(()=>!W||qe(W)||!Je(W)?null:Ts(W),[W]),he=o.useMemo(()=>r.filter(H=>H.type==="adhdev-daemon").sort(wa),[r]),de=o.useMemo(()=>he.find(H=>H.id===V)||null,[he,V]),ye=nn({sendDaemonCommand:a,activeConv:W||void 0,setActionLogs:i,isStandalone:c}),ge=Lh({sendDaemonCommand:a,navigate:B,ides:r,conversations:e}),ve=o.useMemo(()=>e.map(H=>{const ce=M==="chat"&&(W==null?void 0:W.tabKey)===H.tabKey,me=Qr(H,k,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ce}),we=es(H),_e=uc(H);return{conversation:H,timestamp:we,preview:_e,unread:me.unread,requiresAction:me.requiresAction,isWorking:me.isWorking,inboxBucket:me.inboxBucket}}),[e,k,M,W]),{markConversationRead:z}=Ah({conversations:e,machineEntries:he,items:ve,selectedConversation:W,selectedTabKey:g,screen:M,liveSessionInboxState:k,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:w,setSelectedTabKey:D,setScreen:I,setSelectedMachineId:L,setSection:K,setMachineBackTarget:G,resetMachineAction:ge.resetMachineAction}),F=Rh({conversations:e,selectedConversation:W,machineBackTarget:R,markConversationRead:z,resetMachineAction:ge.resetMachineAction,setSelectedTabKey:D,setScreen:I,setSelectedMachineId:L,setSection:K,setMachineBackTarget:G}),Q=o.useMemo(()=>Sr(ve.filter(H=>H.requiresAction)),[ve]),ue=o.useMemo(()=>Sr(ve.filter(H=>H.unread&&!H.requiresAction)),[ve]),te=o.useMemo(()=>Sr(ve.filter(H=>!H.unread&&!H.requiresAction&&H.isWorking)),[ve]),fe=o.useMemo(()=>Sr(ve.filter(H=>!H.unread&&!H.requiresAction&&!H.isWorking)),[ve]),ne=o.useMemo(()=>de?ve.filter(H=>fs(H.conversation)===de.id):[],[ve,de]),xe=o.useMemo(()=>Nh(de,r),[r,de]),re=(de==null?void 0:de.version)||null,le=!!de&&!!re&&!0&&re!==E,oe=o.useMemo(()=>(de==null?void 0:de.availableProviders)||[],[de]),Y=o.useMemo(()=>oe.filter(H=>H.category==="cli"&&H.installed!==!1).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[oe]),X=o.useMemo(()=>oe.filter(H=>H.category==="acp"&&H.installed!==!1).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[oe]),ae=o.useMemo(()=>Ch(he,ve),[ve,he]),A=o.useCallback(async H=>{de&&await ge.handleOpenRecent(de.id,H)},[ge,de]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&W?s.jsx(hh,{selectedConversation:W,isAcp:qe(W),isStandalone:c,selectedIdeEntry:J,actionLogs:n,userName:l,isSendingChat:ye.isSendingChat,sendFeedbackMessage:ye.sendFeedbackMessage,isFocusingAgent:ye.isFocusingAgent,handleModalButton:ye.handleModalButton,handleRelaunch:ye.handleRelaunch,onBack:F.backFromConversation,onOpenNativeConversation:F.openNativeConversation,onOpenMachine:F.openConversationMachine,onHideConversation:y,onOpenHistory:S,onOpenRemote:p,onStopCli:x,cliViewMode:be,onSetCliViewMode:async H=>{await Kc({conversation:W,mode:H,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:v})},handleSendChat:ye.handleSendChat,handleFocusAgent:ye.handleFocusAgent}):M==="machine"&&de?s.jsx(kh,{selectedMachineEntry:de,selectedMachineConversations:ne,selectedMachineRecentLaunches:xe,cliProviders:Y,acpProviders:X,selectedMachineNeedsUpgrade:le,appVersion:E,machineAction:ge.machineAction,isStandalone:c,section:P,showBottomNav:R==="inbox",onBack:F.backFromMachine,onSectionChange:F.changeMachineSection,onOpenConversation:F.openConversation,onOpenRecent:A,onOpenMachineDetails:()=>B(`/machines/${de.id}`),onMachineUpgrade:()=>ge.handleMachineUpgrade(de.id),onLaunchDetectedIde:(H,ce)=>ge.handleLaunchDetectedIde(de.id,H,ce),onAddWorkspace:(H,ce)=>ge.handleAddWorkspace(de.id,H,ce),onBrowseDirectory:H=>ge.handleBrowseDirectory(de.id,H),onLaunchWorkspaceProvider:(H,ce,me)=>ge.handleLaunchWorkspaceProvider(de.id,H,ce,me),onListSavedSessions:H=>ge.handleListSavedSessions(de.id,H)}):s.jsx(bh,{section:P,attentionItems:Q,unreadItems:ue,workingItems:te,completedItems:fe,hiddenConversations:t,machineCards:ae,getAvatarText:Ph,onOpenConversation:F.openConversation,onShowConversation:N,onShowAllHidden:T,onOpenNewSession:C,onOpenMachine:F.openMachine,onOpenSettings:()=>B("/settings"),onSectionChange:K,wsStatus:j,isConnected:b,isStandalone:c})})}function Tn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Dh({conversations:e,numGroups:t,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))},[]),w=o.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!Tn(t,r)){d("merge");return}const j=x.currentTarget.getBoundingClientRect(),b=x.clientX-j.left,N=j.width/3;b<N?d("split-left"):b>N*2?d("split-right"):d("merge")},[t,r]),S=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),d(null))},[]),p=o.useCallback(x=>{c.current=0,u(!1);const j=x.dataTransfer.getData("text/tab-key"),b=j?e.some(T=>T.tabKey===j):!1,N=f;if(d(null),i(),!!j){if(x.preventDefault(),N==="split-left"&&Tn(t,r)){r==null||r(j,"split-left");return}if(N==="split-right"&&Tn(t,r)){r==null||r(j,"split-right");return}if(b){a(j);return}n==null||n(j)}},[e,f,t,r,n,a,i]);return{dragOver:l,dropAction:f,resetDragState:h,handleDragEnter:m,handleDragOver:w,handleDragLeave:S,handleDrop:p}}function Eh(e,t){const r=new Set(t.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=t.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function $h({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(t??null),[l,u]=o.useState(r??[]),[f,d]=o.useState(null),h=o.useRef(null),m=o.useRef(null),w=o.useRef(n),S=o.useRef(a);o.useEffect(()=>{w.current=n},[n]),o.useEffect(()=>{S.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{u(k=>{const v=Eh(k,e);return v.length===k.length&&v.every((g,D)=>g===k[D])?k:v})},[e]);const p=o.useMemo(()=>{const k=f??l;if(k.length===0)return e;const v=new Map(k.map((g,D)=>[g,D]));return[...e].sort((g,D)=>{const M=v.get(g.tabKey)??999,I=v.get(D.tabKey)??999;return M-I})},[e,f,l]);o.useEffect(()=>{var v,g;if(p.length===0){i!==null&&(c(null),(v=w.current)==null||v.call(w,null));return}if(i&&p.some(D=>D.tabKey===i))return;const k=p[0].tabKey;k!==i&&(c(k),(g=w.current)==null||g.call(w,k))},[p,i]);const x=o.useMemo(()=>p.find(k=>k.tabKey===i),[p,i]),j=o.useCallback(k=>{var v;c(k),(v=w.current)==null||v.call(w,k)},[]),b=o.useCallback((k,v,g)=>{u(D=>{var K;const M=D.filter(V=>V!==k),I=M.indexOf(v);if(I<0)return D;const P=g==="left"?I:I+1;return M.splice(P,0,k),(K=S.current)==null||K.call(S,M),M}),d(null)},[]),N=o.useCallback((k,v,g)=>{const M=(l.length>0?l:e.map(K=>K.tabKey)).filter(K=>K!==k),I=M.indexOf(v);if(I<0)return;const P=g==="left"?I:I+1;M.splice(P,0,k),h.current=M,d(M)},[l,e]),T=o.useCallback(()=>{var v;const k=h.current;k&&(u(k),(v=S.current)==null||v.call(S,k))},[]),y=o.useCallback(()=>{h.current=null,d(null)},[]),C=o.useCallback(k=>{u(v=>{var D;const g=v.filter(M=>M!==k);return g.push(k),(D=S.current)==null||D.call(S,g),g})},[]);return{activeTabId:i,activeConv:x,sortedConversations:p,previewOrderRef:h,draggingTabRef:m,selectTab:j,handleTabReorder:b,updatePreviewOrder:N,commitPreviewOrder:T,clearPreviewOrder:y,moveTabToEnd:C,setDraggingTabKey:k=>{m.current=k}}}function Bh({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),s.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function Va({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:i}){if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!r&&!n,l=n&&!!i,u=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",f=n?hc:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:u}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:f}),l&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:i,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:$t,"aria-label":$t,children:[s.jsx(Ti,{size:14}),s.jsx("span",{children:$t})]})}),c&&s.jsx(Gc,{}),c&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const Jc="adhdev-tab-shortcuts";function Qc(){try{return JSON.parse(localStorage.getItem(Jc)||"{}")}catch{return{}}}function Zc({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>Qc()),[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(Jc,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 w=f(m);if(!w)return;const S={...i};for(const[p,x]of Object.entries(S))x===w&&delete S[p];S[l]=w,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[w,S]of Object.entries(i))if(t.includes(w)&&f(m)===S){m.preventDefault(),r(),n(w);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,i,t,r,n,f]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const Kh=o.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:f,onConversationActivated:d,onPreviewReorder:h,onReorderTab:m,onCommitPreviewOrder:w,onClearPreviewOrder:S,onDragStateReset:p,onDragTabKeyChange:x,onReceiveTab:j,onOpenContextMenu:b,longPressTimer:N,isGroupActive:T}){const y=Ms(t),C=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",k=y.isReconnecting,v=o.useCallback(R=>{l.current=t.tabKey,x(t.tabKey),R.dataTransfer.setData("text/tab-key",t.tabKey),R.dataTransfer.effectAllowed="move"},[t.tabKey,l,x]),g=o.useCallback(()=>{l.current=null,x(null),w(),S(),p()},[l,x,w,S,p]),D=o.useCallback(R=>{const G=l.current;if(!(!G||G===t.tabKey)&&R.dataTransfer.types.includes("text/tab-key")){R.preventDefault(),R.stopPropagation();const B=R.currentTarget.getBoundingClientRect(),E=R.clientX<B.left+B.width/2?"left":"right";h(G,t.tabKey,E)}},[t.tabKey,l,h]),M=o.useCallback(R=>{R.preventDefault(),R.stopPropagation();const G=R.dataTransfer.getData("text/tab-key");if(G&&G!==t.tabKey){const B=R.currentTarget.getBoundingClientRect(),E=R.clientX<B.left+B.width/2?"left":"right";c.includes(G)?m(G,t.tabKey,E):j&&j(G)}S()},[t.tabKey,c,m,j,S]),I=o.useCallback(R=>{R.stopPropagation(),u(),f(t.tabKey),d(t)},[t,d,u,f]),P=o.useCallback(R=>{R.preventDefault(),b(R.clientX,R.clientY,t.tabKey)},[t.tabKey,b]),K=o.useCallback(R=>{const G=R.touches[0];N.current=setTimeout(()=>{b(G.clientX,G.clientY,t.tabKey)},600)},[t.tabKey,N,b]),V=o.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),L=["adhdev-dockview-tab",C,r&&"is-active",T&&"is-group-active",k&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:L,draggable:!0,onDragStart:v,onDragEnd:g,onDragOver:D,onDrop:M,onClick:I,onContextMenu:P,onTouchStart:K,onTouchEnd:V,onTouchMove:V,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?s.jsx("div",{className:"tab-spinner"}):y.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):k?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:tt(t),children:tt(t)}),s.jsx("span",{className:"adhdev-dockview-tab-meta",children:k?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(t)}):y.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ts(t),s.jsx("span",{className:"connecting-dots"})]}):ts(t)})]}),i&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function Oh({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:m,onDragTabKeyChange:w,onReceiveTab:S,onHideTab:p,isGroupActive:x,allowTabShortcuts:j=!0}){const[b,N]=o.useState(null),T=o.useRef(null),y=o.useRef(null),C=o.useMemo(()=>e.map(P=>P.tabKey),[e]);tr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:k,tabShortcuts:v,shortcutListening:g,setShortcutListening:D,saveShortcuts:M}=Zc({enabled:j,sortedTabKeys:e.map(P=>P.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!b)return;const P=K=>{const V=document.querySelector("[data-pane-context-menu]");V&&V.contains(K.target)||N(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[b]),o.useEffect(()=>{const P=y.current;if(!P)return;const K=V=>{Math.abs(V.deltaY)<=Math.abs(V.deltaX)||(V.preventDefault(),P.scrollLeft+=V.deltaY)};return P.addEventListener("wheel",K,{passive:!1}),()=>P.removeEventListener("wheel",K)},[]);const I=o.useCallback((P,K,V)=>{N({x:P,y:K,tabKey:V})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref: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=>s.jsx(Kh,{conv:P,isActive:t===P.tabKey,isDraggedTab:a.current===P.tabKey,isTaskCompleteUnread:n.has(P.tabKey),shortcut:j?v[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:w,onReceiveTab:S,onOpenContextMenu:I,longPressTimer:T,isGroupActive:x},P.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:b.x,top:b.y},children:[j&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:P=>{P.stopPropagation(),D(b.tabKey),N(null)},children:["⌨ ",v[b.tabKey]?`Change shortcut (${v[b.tabKey]})`:"Set shortcut"]}),v[b.tabKey]&&s.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const P={...v};delete P[b.tabKey],M(P),N(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[j&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{p(b.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),j&&g&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>D(null),children:s.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:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",k?"⌘+1":"Ctrl+1",", ",k?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Wh({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:u,groupIndex:f,onFocus:d,isSplitMode:h,numGroups:m,onMoveTab:w,onReceiveTab:S,style:p,onActiveTabChange:x,initialActiveTabId:j,initialTabOrder:b,onTabOrderChange:N,onHideTab:T,isFocused:y,allowTabShortcuts:C=!0,onOpenNewSession:k,liveSessionInboxState:v}){const{sendCommand:g}=jt(),D=o.useRef(null),{activeTabId:M,activeConv:I,sortedConversations:P,draggingTabRef:K,selectTab:V,handleTabReorder:L,updatePreviewOrder:R,commitPreviewOrder:G,clearPreviewOrder:B,moveTabToEnd:E,setDraggingTabKey:W}=$h({conversations:e,initialActiveTabId:j,initialTabOrder:b,onActiveTabChange:x,onTabOrderChange:N}),J=nn({sendDaemonCommand:a,activeConv:I,setActionLogs:i,isStandalone:c}),{dragOver:be,dropAction:he,resetDragState:de,handleDragEnter:ye,handleDragOver:ge,handleDragLeave:ve,handleDrop:z}=Dh({conversations:e,numGroups:m,onMoveTab:w,onReceiveTab:S,onOwnTabDrop:E,onClearPreviewOrder:B}),F=I&&!qe(I)&&Ts(I)==="terminal",Q=o.useMemo(()=>I?t.find(ne=>ne.id===I.routeId):void 0,[t,I]),ue=o.useMemo(()=>I?n.filter(ne=>ne.routeId===I.tabKey):[],[n,I]),te=o.useMemo(()=>new Set(P.filter(ne=>pu(ne,v,{isOpenConversation:ne.tabKey===M})).map(ne=>ne.tabKey)),[M,v,P]);tr("PaneGroup",{groupIndex:f,conversationCount:e.length,activeTabId:M,dragOver:be});const fe=o.useCallback(ne=>{ne.streamSource==="agent-stream"&&ne.agentType&&g(ne.routeId,Vc(),{agentType:ne.agentType,...ne.sessionId&&{targetSessionId:ne.sessionId}}).catch(()=>{})},[g]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...p,outline:be?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(Oh,{conversations:P,activeTabId:M,groupIndex:f,numGroups:m,unreadTabKeys:te,draggingTabRef:K,onFocus:d,onSelectTab:V,onConversationActivated:fe,onPreviewReorder:R,onReorderTab:L,onCommitPreviewOrder:G,onClearPreviewOrder:B,onDragStateReset:de,onDragTabKeyChange:W,onMoveTab:w,onReceiveTab:S,onHideTab:T,isGroupActive:y??!1,allowTabShortcuts:C}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ye,onDragOver:ge,onDragLeave:ve,onDrop:z,children:[be&&s.jsx(Bh,{dropAction:he,canSplit:!!(m<4&&w)}),I?s.jsx(Ua,{activeConv:I,clearToken:r[I.tabKey]||0,isCliTerminal:!!F,ideEntry:Q,terminalRef:D,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:ue,userName:u,isInputActive:!h||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Va,{conversationsCount:e.length,isSplitMode:h,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:k})})]})]})}function Hh({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:f,isStandalone:d,hasRegisteredMachines:h,userName:m,focusedGroup:w,focusGroup:S,moveTabToGroup:p,splitTabRelative:x,closeGroup:j,handleResizeStart:b,groupActiveTabIds:N,setGroupActiveTab:T,groupTabOrders:y,setGroupTabOrder:C,toggleHiddenTab:k,onOpenNewSession:v,allowTabShortcuts:g=!0,liveSessionInboxState:D}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((M,I)=>{const P=t&&n.length===r?`${n[I]}%`:void 0;return s.jsxs(St.Fragment,{children:[t&&I>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:K=>b(I-1,K),onDoubleClick:()=>j(I),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(Wh,{style:t?{flexBasis:P??`${100/r}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:M,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:f,isStandalone:d,hasRegisteredMachines:h,userName:m,groupIndex:I,isFocused:t&&w===I,onFocus:()=>S(I),isSplitMode:t,numGroups:r,onMoveTab:(K,V)=>{V==="left"&&I>0?p(K,I-1):V==="right"&&I<r-1?p(K,I+1):V==="split-left"&&r<4?x(K,I,"left"):V==="split-right"&&r<4&&x(K,I,"right")},onReceiveTab:K=>p(K,I),onActiveTabChange:K=>T(I,K),initialActiveTabId:N[I],initialTabOrder:y[I],onTabOrderChange:K=>C(I,K),onHideTab:k,onOpenNewSession:v,allowTabShortcuts:g,liveSessionInboxState:D})]},I)})})}function el({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?at.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=at.onStatus)==null?void 0:d.call(at,(h,m)=>{h===e&&m!=null&&m.screenshotUsage&&l(m.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,t]),o.useEffect(()=>{const f=e?at.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&t?f.startScreenshots(t):f.stopScreenshots(t),()=>{f.stopScreenshots(t)}},[n,r,t,e]);const u=o.useCallback(async(f,d)=>{const h=e?at.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(f,d,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const tl="adhdev-dashboard-action-shortcuts",Fh=1200,Uh={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function zh(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function Qe(e,t){switch(e){case"openShortcutHelp":return"?";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return t?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return t?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return t?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return t?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return t?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return t?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return t?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return t?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return t?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return t?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function sl(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:Qe("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:Qe("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:Qe("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:Qe("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:Qe("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:Qe("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:Qe("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:Qe("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:Qe("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:Qe("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:Qe("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:Qe("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:Qe("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:Qe("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:Qe("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:Qe("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:Qe("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:Qe("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:Qe("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:Qe("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:Qe("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:Qe("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:Qe("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:Qe("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:Qe("toggleCliView",e)}]}function la(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Gr(e){const t=Object.fromEntries(sl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(tl)||"{}"),n={...t,...r};for(const[a,i]of Object.entries(Uh))n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function rl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Vh({enabled:e=!0,onTrigger:t}){const r=zh(),[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(rl(p.key)),x.join("+"))},[r]),h=o.useCallback(p=>{a(p);try{localStorage.setItem(tl,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=Gr(r),x=Object.entries(n),j=Object.entries(p);x.length===j.length&&x.every(([b,N])=>p[b]===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}},[]),w=o.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},Fh))},[]);o.useEffect(()=>{if(!i)return;const p=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){c(null),u([]);return}const j=d(x);if(!j)return;const N=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(j);if(l.length===0&&N){u([j]);return}const y=[...l,j].slice(0,2).join(" "),C={...n};for(const[k,v]of Object.entries(C))v===y&&delete C[k];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 j=d(x);if(!j)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(la(x.target)&&!b)return;const N=f.current.parts,T=b?[j]:[...N.slice(-1),j].slice(-2),y=T.join(" "),C=T[T.length-1],k=Object.entries(n).filter(([,I])=>!!I),v=k.find(([,I])=>I===y);if(v){x.preventDefault(),m(),t(v[0]);return}if(k.some(([,I])=>I.startsWith(`${y} `))){x.preventDefault(),f.current.parts=T,w();return}const D=k.find(([,I])=>I===C);if(D){x.preventDefault(),m(),t(D[0]);return}if(k.some(([,I])=>I.startsWith(`${C} `))){x.preventDefault(),f.current.parts=[C],w();return}m()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,w,e,d,t,m,i]),o.useEffect(()=>()=>m(),[m]);const S=o.useMemo(()=>sl(r),[r]);return{isMac:r,actionDefinitions:S,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:h}}function Gh({isTabInPopout:e,isTabFloating:t,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}function nl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Jo({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!nl(n):!0}function qh({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:nl(r)}const al=o.createContext(null);function on(){const e=o.useContext(al);if(!e)throw new Error("DashboardDockviewContext missing");return e}function _r(e){return tt(e)||e.tabKey}function Yh(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function Qo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Ln(e){var r,n,a,i,c;const t=e==null?void 0:e.defaultView;if(t)try{t.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=t.requestAnimationFrame)==null||c.call(t,()=>{var l,u;try{t.focus(),(u=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||u.call(l)}catch{}})}catch{}}function Nr(e,t){e.classList.remove(Un.className,zn.className),e.classList.add(t==="light"?Un.className:zn.className)}function Zo(e){return e?Array.from(new Set(e.groups.map(t=>{var r,n;return(n=(r=t.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(t=>!!t&&t!==window))):[]}function Xh(e){const[,t]=o.useState(0);o.useEffect(()=>{const r=()=>t(a=>a+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const a of n)a.dispose()}},[e.api,e.containerApi])}function Jh(e,t,r){var c;const n=[t];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=t[0])==null?void 0:c.tabKey)??null}function ei(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])Lt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==_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 ti(e,t,r){var u,f;const n=r?Yh(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(t,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=pc(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 Qh({params:e,api:t}){var h;const r=on(),n=o.useRef(null),[a,i]=o.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=nn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(t.isActive);const m=[t.onDidActiveChange(w=>i(w.isActive)),t.onDidActiveGroupChange(w=>{if(!t.isActive&&!w.isActive){i(!1);return}i(t.isActive)})];return()=>{for(const w of m)w.dispose()}},[t]);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 s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(Va,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const d=!qe(c)&&Ts(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Ua,{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,isVisible:a})})}function Zh({params:e}){var u;const t=on(),r=o.useMemo(()=>_t([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>t.ides.find(f=>f.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=el({doId:a,targetSessionId:r?Qi(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Di,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:l})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function ex(){const e=on();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Va,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function tx(e){var w,S;Xh(e);const t=on(),r=o.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=_t([...t.conversationsByTabKey.values()],e.params.routeId),x=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,j=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${x?" is-active":""}${j?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,i=e.api.isGroupActive,c=Qr(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,u=c.isConnecting,f=c.isGenerating,d=c.isWaiting,h=c.unread,m=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:tt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var x;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((x=p.target)==null?void 0:x.ownerDocument)??document})},children:[h&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?s.jsx("div",{className:"tab-spinner"}):d?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):u?s.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:tt(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(n)}):u?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ts(n)}):s.jsx("span",{children:ts(n)})})]}),m&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:m,children:m})]})}function sx({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:u,userName:f,toggleHiddenTab:d,actionShortcuts:h,registerActionHandlers:m,onActiveTabChange:w,onOpenNewSession:S,onRequestScrollToBottom:p,requestedActiveTabKey:x,requestedRemoteIdeId:j,onRequestedActiveTabConsumed:b,scrollToBottomRequest:N,liveSessionInboxState:T,layoutProfile:y}){var ft,He,vt;const{theme:C}=$a(),{sendCommand:k}=jt(),v=o.useRef(null),g=o.useRef(null),D=o.useRef(!1),M=o.useRef(!1),I=o.useRef(!1),P=o.useRef(null),K=o.useRef([]),[V,L]=o.useState(null),[R,G]=o.useState(!1),[B,E]=o.useState(!1),[W,J]=o.useState(0),be=o.useRef(null),he=o.useRef(typeof window>"u"?{}:Rp(y)),de=o.useMemo(()=>new Map(e.map($=>[$.tabKey,$])),[e]),ye=o.useMemo(()=>{const $=v.current;return $?$.groups.some(O=>{try{const U=O.model.location.type;return U!=="floating"&&U!=="popout"?!1:O.panels.some(q=>de.has(q.id))}catch{return!1}}):!1},[de,W,e]),ge=o.useCallback(()=>{var $;($=v.current)==null||$.focus()},[]),ve=o.useCallback(($,O)=>{p==null||p($,O)},[p]),z=o.useCallback($=>{const O=document,U=$.document;for(const Ce of O.querySelectorAll('link[rel="stylesheet"]')){const se=U.createElement("link");se.rel="stylesheet",se.href=Ce.href,Ce.crossOrigin&&(se.crossOrigin=Ce.crossOrigin),U.head.appendChild(se)}for(const Ce of O.querySelectorAll("style")){const se=U.createElement("style");se.textContent=Ce.textContent,U.head.appendChild(se)}const q=[];for(const Ce of O.styleSheets)try{for(const se of Ce.cssRules)se instanceof CSSStyleRule&&(se.selectorText===":root"||se.selectorText==="html")&&q.push(se.cssText)}catch{}if(q.length>0){const Ce=U.createElement("style");Ce.textContent=q.join(`
|
|
43
|
-
`),U.head.appendChild(
|
|
42
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:g,onCancel:()=>u(null)})]})}const tp=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function sp(){const{preference:e,setPreference:t}=Ka();return s.jsx("div",{className:"flex gap-2",children:tp.map(r=>s.jsxs("button",{onClick:()=>t(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx("span",{children:r.icon}),r.label]},r.id))})}function rp(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function np(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 t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Ko(e){const{r:t,g:r,b:n}=np(e);return .2126*jn(t)+.7152*jn(r)+.0722*jn(n)}function Oo(e,t){const r=Ko(e),n=Ko(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function _c(e){const t=rp(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Oo(t,r)>=Oo(t,n)?r:n}const oa={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},ia={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},ap=[{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"}}}],Dc="adhdev-chat-theme",Ec="adhdev-chat-theme-custom";function Rr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Dc)||"ember"}catch{return"ember"}}function Pt(e){try{const t=localStorage.getItem(Ec);if(t){const r=JSON.parse(t);return{...e==="dark"?oa:ia,...r[e]}}}catch{}return e==="dark"?oa:ia}function yr(e,t){try{localStorage.setItem(Ec,JSON.stringify({dark:e,light:t}))}catch{}}function It(e,t){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${t})`}function Vr(e,t){const r=Math.min(255,parseInt(e.slice(1,3),16)+t),n=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const op={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Vs(e,t){var a;const r=(a=op[e])==null?void 0:a[t];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Vr(r,24)),n.style.setProperty("--accent-on-primary",_c(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 t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",It(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",It(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",It(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",It(e.borderSubtle,.5)),t.style.setProperty("--border-default",It(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Vr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",_c(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Vr(e.accentColor,40)})`),t.style.setProperty("--border-accent",It(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",It(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${It(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${It(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function Oa(){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 ip(e){try{localStorage.setItem(Dc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=as()?"dark":"light";ns(Pt(t))}else Oa(),Vs(e,as()?"dark":"light")}function cp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Rr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=as()?"dark":"light";ns(Pt(t))}else Oa(),Vs(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:t,onChange:r}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Es({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function lp({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=o.useState(()=>Pt(r));o.useEffect(()=>{a(Pt(r))},[r]);const i=o.useCallback((c,l)=>{a(d=>{const f={...d,[c]:l},x=Pt(r==="dark"?"light":"dark");return r==="dark"?yr(f,x):yr(x,f),ns(f),t(f),f})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",s.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(Es,{title:"App Background",children:[s.jsx(xt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(xt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(xt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Es,{title:"App Text",children:[s.jsx(xt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(xt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(xt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Es,{title:"Borders & Accent",children:[s.jsx(xt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(xt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(xt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Es,{title:"Chat Bubbles",children:[s.jsx(xt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(xt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(xt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(xt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Es,{title:"Chat Layout",children:[s.jsx(xt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(xt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(xt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?oa:ia,d=Pt(e?"light":"dark");e?yr(c,d):yr(d,c),a(c),ns(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function dp(){const[e,t]=o.useState(Rr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Pt("dark"));o.useEffect(()=>{n(as());const d=new MutationObserver(()=>{const x=as();n(x);const m=Rr();m==="custom"?ns(Pt(x?"dark":"light")):Vs(m,x?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const x=as();n(x);const m=Rr();m==="custom"?ns(Pt(x?"dark":"light")):Vs(m,x?"dark":"light")};return f.addEventListener("change",u),()=>{d.disconnect(),f.removeEventListener("change",u)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ns(Pt(r?"dark":"light")):(Oa(),Vs(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Pt(r?"dark":"light"))},[r]);const c=d=>{t(d),ip(d)},l=[...ap,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(d=>{const f=e===d.id,u=r?d.preview.dark:d.preview.light,x=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:u.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:x},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[f&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:d.id==="custom"?"🎨 Custom":d.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&s.jsx(lp,{dark:r,onColorsChange:d=>i(d)})]})}const Wa="adhdev_mobileDashboardMode_v1",ca="adhdev:mobile-dashboard-mode-change";function Ha(){try{return localStorage.getItem(Wa)==="workspace"?"workspace":"chat"}catch{return"chat"}}function up(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Ha())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==Wa||t()};return window.addEventListener(ca,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ca,r),window.removeEventListener("storage",n)}}function mp(e){try{localStorage.setItem(Wa,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ca,{detail:e}))}function fp(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(Ha()==="chat")},[]),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ut,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{t(r),mp(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const kn=new Map,Wo=new Map;function pp(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function hp(e,t,r,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n,platform:r.platform,machine:r}}function $c(){const{sendCommand:e}=wt(),{injectEntries:t,getIdes:r}=Ys();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??Im,c=Wo.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 d=(async()=>{const f=await e(n,"get_machine_runtime_stats"),u=pp(f);if(!u)return;const x=r().find(v=>v.id===n),m=hp(x,n,u.machine,u.timestamp||Date.now());t([m]),Wo.set(n,Date.now())})().finally(()=>{kn.delete(n)});return kn.set(n,d),d},[r,t,e])}function xp(e,t,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...r.machine}}}function bp(e,t){const{sendData:r}=wt(),{injectEntries:n,getIdes:a}=Ys(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(d=>qt.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const x=a().find(v=>v.id===d),m=xp(x,d,u);n([m])}));return()=>{l.forEach(d=>d())}},[i,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function gp(e,t){const{sendData:r}=wt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(t!=null&&t.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const d=qt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},f=>{l&&(clearTimeout(l),l=null),a(f.diagnostics),c(!1)});return d.initialSendAccepted?l=setTimeout(()=>{c(!1)},Lm):c(!1),()=>{l&&clearTimeout(l),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:a}}function yp(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Bc(e){const{sendData:t}=wt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=yp(e);if(!a||!e.sessionId||!t){n({});return}const i=qt.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),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,t]),r}const Kc="adhdev_hiddenTabs";function vp(){try{const e=localStorage.getItem(Kc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ps(e){try{localStorage.setItem(Kc,JSON.stringify([...e]))}catch{}}function Sn(e){return Ca(e)}function Fa(e,t){return ws(t).some(r=>e.has(r))}function wp(){const[e,t]=o.useState(vp),r=o.useCallback(f=>{const u=Sn(f);t(x=>{const m=new Set(x);return m.has(u)?m.delete(u):m.add(u),ps(m),m})},[]),n=o.useCallback(f=>{const u=Sn(f);t(x=>{if(x.has(u))return x;const m=new Set(x);return m.add(u),ps(m),m})},[]),a=o.useCallback(f=>{const u=Sn(f);t(x=>{if(!x.has(u))return x;const m=new Set(x);return m.delete(u),ps(m),m})},[]),i=o.useCallback(()=>{t(f=>{if(f.size===0)return f;const u=new Set;return ps(u),u})},[]),c=o.useCallback((f,u)=>{t(x=>{const m=new Set(x);for(const v of u)m.add(v);return ps(m),m})},[]),l=o.useCallback((f,u)=>{t(x=>{const m=new Set(x);for(const v of u)m.delete(v);return ps(m),m})},[]),d=o.useCallback(f=>Fa(e,f),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:d}}function Oc(e){return e instanceof Error?e.message:String(e||"")}function Wc(e){const t=Oc(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function Hc(e){const t=Oc(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Fc({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Qe(e)||Xe(e))return;const i=Ls(e);if(i===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(fs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Kt(e),mode:t})}catch(l){const d=Hc(l);c&&!d&&a(f=>{const u={...f};return i===Uc(r,c)?delete u[c]:u[c]=i,u}),Wc(l)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function Ho(e,t){const r=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!r||e.transport!=="pty")return e;const n=t[r];return!n||e.mode===n?e:{...e,mode:n}}function jp(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let r=!1;const n=e.map(a=>{const i=Ho(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>Ho(d,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Uc(e,t){if(!t)return null;for(const r of e){if(r.sessionId===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function kp(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))Uc(t,a)===i&&(delete n[a],r=!0);return r?n:e}function Sp({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Yi()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:bc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Fu(a),o.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const d=Date.now(),f={};for(const[u,x]of Object.entries(l))d-x<5e3&&(f[u]=x);return Object.keys(f).length===Object.keys(l).length?l:f})},5500);return()=>clearTimeout(c)},[t,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const d=l.filter(f=>f.timestamp>c).slice(-100);return d.length===l.length?l:d})},6e4);return()=>clearInterval(i)},[n]),null}function Np(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const i=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function Nn(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Cp(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Fo(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Cp(Ss(r.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((r==null?void 0:r.id)||""),String((r==null?void 0:r.index)??""),String((r==null?void 0:r.receivedAt)??(r==null?void 0:r.timestamp)??""),n].join(":")}function Ip(e){const t=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),Fo(e.activeChat),...t.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastMessageAt||""),r.lastMessagePreview||"",r.lastMessageRole||"",String(r.lastUpdated||""),Fo(r.activeChat)].join(":"))].join("|")}function Mp(e,t){const r=Date.now();return e.map(n=>{const a=t[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function Ap(e,t){const r=new Map;for(const n of e){const a=t.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 Tp(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Lp(e){const t=Tp(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const r=String(t.role||""),n=Ss(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Rp({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>Np(e),[e]),i=o.useMemo(()=>Sc(e),[e]),c=o.useRef([]),l=o.useRef([]),d=o.useRef([]),f=o.useRef(new Map),u=o.useRef(new Map),x=o.useMemo(()=>{const T=new Map,y=[];for(const g of a){const{connectionState:D="new",machineName:A}=Nc(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),I=Ip(g),P=f.current.get(g.id);if(P&&P.ide===g&&P.sourceSignature===I&&P.connectionState===D&&P.machineName===A){T.set(g.id,P),y.push(...P.conversations);continue}const O=Ba(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),V={ide:g,sourceSignature:I,connectionState:D,machineName:A,conversations:O};T.set(g.id,V),y.push(...O)}f.current=T;const C=new Map,k=g=>{const D=Lp(g),A=u.current.get(g.tabKey);if(A&&A.signature===D)return C.set(g.tabKey,A),A.timestamp;const I={signature:D,timestamp:ac(g)||(A==null?void 0:A.timestamp)||0};return C.set(g.tabKey,I),I.timestamp},w=[...y].sort((g,D)=>oc(g,D,k));return u.current=C,w},[a,t,i]),m=o.useMemo(()=>{const T=Mp(x,r);return Nn(c.current,T)?c.current:(c.current=T,T)},[x,r]),v=o.useMemo(()=>{const T=new Map,y=Array.from(new Set(m.map(C=>C.routeId)));for(const C of y){const k=_t(m,C);k&&T.set(C,k)}return T},[m]),S=o.useMemo(()=>{const T=new Map;for(const y of m){const C=v.get(y.routeId),k=y.streamSource==="native"&&C?C:y;for(const w of ws({providerSessionId:y.providerSessionId,sessionId:y.sessionId}))T.set(w,k)}return T},[m,v]),p=o.useMemo(()=>Ap(m,v),[m,v]),h=o.useCallback(T=>{if(T)return S.get(T)},[S]),j=o.useCallback(T=>{if(T)return p.get(T)},[p]),b=o.useMemo(()=>{const T=m.filter(y=>!Fa(n,y));return Nn(l.current,T)?l.current:(l.current=T,T)},[m,n]),N=o.useMemo(()=>{const T=b.map(y=>y.tabKey);return Nn(d.current,T)?d.current:(d.current=T,T)},[b]);return{chatIdes:a,conversations:m,visibleConversations:b,visibleTabKeys:N,resolveConversationBySessionId:h,resolveConversationByTarget:j}}function Pp({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),i=o.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=o.useCallback(()=>{t&&n(l=>{const d=new URLSearchParams(l);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function _p({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{lt.setIdes(e)},[e]),o.useEffect(()=>{lt.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),o.useEffect(()=>{const a=lt.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(d=>d.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=pc.on("status_event",i=>{lt.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 d=l.targetSessionId||l.targetKey||l.daemonId,f=n(d),u=(f==null?void 0:f.routeId)||l.daemonId;if(!u)return;const x=Number(l.buttonIndex),m=l.button||((p=f==null?void 0:f.modalButtons)==null?void 0:p[x])||"Approve",v=String(m).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(v);t(u,"resolve_action",{action:S?"approve":"reject",button:m,...Number.isFinite(x)&&{buttonIndex:x},...(f==null?void 0:f.sessionId)&&{targetSessionId:f.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(h=>console.error("[SW Action] approval failed:",h))};return(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,t])}const Dp="adhdev_dashboardLayout_v1",Ep="adhdev_dashboardDockview_v1",$p="adhdev_dashboardDockviewHiddenRestore_v1",$s={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ua(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Bp(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function zc(e){return`${Dp}:${e}`}function Kp(e){const t=zc(e);return Ua(t,null)}function Op(e,t){try{const r=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,n=zc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Vc(e){return`${Ep}:${e}`}function Wp(e){const t=Vc(e);return Ua(t,null)}function Hp(e,t){try{const r=Vc(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Gc(e){return`${$p}:${e}`}function Fp(e){const t=Gc(e);return Ua(t,{})}function Up(e,t){try{const r=Gc(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function zp(){return{groupAssignments:[...$s.groupAssignments],focusedGroup:$s.focusedGroup,groupActiveTabIds:{...$s.groupActiveTabIds},groupTabOrders:{...$s.groupTabOrders},groupSizes:[...$s.groupSizes]}}function Vp(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Gp(){const[e]=o.useState(()=>Bp(typeof window<"u"?window.innerWidth:1280)),[t,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,d]=o.useState({}),[f,u]=o.useState([]),[x,m]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[v,S]=o.useState(!1),p=o.useCallback(()=>{if(v)return;const g=Kp(e)??zp();r(new Map(g.groupAssignments)),a(g.focusedGroup),c(g.groupActiveTabIds),d(g.groupTabOrders),u(g.groupSizes),S(!0)},[v,e]);o.useEffect(()=>{v&&Op(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:f})},[v,e,t,n,i,l,f]),o.useEffect(()=>{const g=window.matchMedia("(max-width: 767px)"),D=A=>m(A.matches);return g.addEventListener("change",D),()=>g.removeEventListener("change",D)},[]);const h=o.useCallback(g=>{r(g)},[]),j=o.useCallback(g=>{a(g)},[]),b=o.useCallback(g=>{c(g)},[]),N=o.useCallback(g=>{d(g)},[]),T=o.useCallback(g=>{u(g)},[]),y=o.useCallback(g=>{j(g)},[j]),C=o.useCallback((g,D)=>{c(A=>(A[g]??null)===(D??null)?A:{...A,[g]:D})},[]),k=o.useCallback((g,D)=>{d(A=>{const I=A[g];return Vp(I,D)?A:{...A,[g]:D}})},[]),w=o.useCallback((g,D)=>{const A=D.get(g)??0;return C(A,g),y(A),A},[y,C]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:h,focusedGroup:n,updateFocusedGroup:j,focusGroup:y,groupActiveTabIds:i,updateGroupActiveTabIds:b,setGroupActiveTab:C,groupTabOrders:l,updateGroupTabOrders:N,setGroupTabOrder:k,groupSizes:f,updateGroupSizes:T,isMobile:x,hasHydratedStoredLayout:v,hydrateStoredLayout:p,focusConversationTab:w}}function qp(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Na(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Yp({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:d,activeConv:f,isRefreshingHistory:u,ides:x,handleRefreshHistory:m}){const v=o.useRef(!1),S=o.useRef(!1),p=o.useRef(null),h=o.useRef(!1);o.useEffect(()=>{if(!e||v.current||t.length===0)return;if(!a){i();return}const j=r(e);j&&(c(j.tabKey,n),v.current=!0,S.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(b=>{const N=new URLSearchParams(b);return N.delete("activeTab"),N},{replace:!0}))},[e,t,r,n,a,i,c,l]),o.useEffect(()=>{if(!(S.current||a)&&t.length!==0){if(!e){i(),S.current=!0;return}if(v.current){S.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(S.current||a)&&(i(),S.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,i]),o.useEffect(()=>{if(!d){h.current=!1;return}if(!f||h.current||u)return;const j=x.find(b=>b.id===f.routeId);j&&(!j.chats||j.chats.length===0||qp(j.chats,f))&&(h.current=!0,m())},[d,f,u,x,m]),o.useEffect(()=>{if(!f)return;let j=null,b=0,N=-1,T=0;const y=()=>{j=null;const C=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(w=>w.offsetParent!==null);if(C.length===0){b<18&&(b+=1,j=requestAnimationFrame(y));return}let k=0;for(const w of C)w.scrollTop=w.scrollHeight,k+=w.scrollHeight;k===N?T+=1:(T=0,N=k),b+=1,!(T>=2||b>=18)&&(j=requestAnimationFrame(y))};return j=requestAnimationFrame(y),()=>{j!=null&&cancelAnimationFrame(j)}},[f==null?void 0:f.tabKey])}function Cn(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=Na(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function qc({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[d,f]=o.useState(!1),u=o.useCallback(async S=>{try{await e("standalone","launch_ide",{ideType:S,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),x=o.useCallback(async(S,p)=>{try{const h=S||(t==null?void 0:t.daemonId)||"",j=await e(h,"switch_chat",{id:p,sessionId:p,...js(t)}),b=j==null?void 0:j.result;if((j==null?void 0:j.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Ds(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Ds(a,`⚠️ Switch error: ${b}`):Ds(a,"⚠️ Session switch failed")}catch(h){console.error("Switch failed",h),Ds(a,`❌ Switch failed: ${h.message||"connection error"}`)}},[t,e,a]),m=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const S=Zs(t);await e(S,"new_chat",{...js(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(S){console.error("New chat failed",S)}finally{l(!1)}}},[t,c,e,i]),v=o.useCallback(async()=>{var S,p;if(!(!t||d)){f(!0);try{const h=Zs(t),j=async()=>e(h,"list_chats",{forceExpand:!0,...js(t)});let b=await j(),N=(b==null?void 0:b.chats)||((S=b==null?void 0:b.result)==null?void 0:S.chats);Cn(N,t)&&(await new Promise(T=>setTimeout(T,450)),b=await j(),N=(b==null?void 0:b.chats)||((p=b==null?void 0:b.result)==null?void 0:p.chats)),b!=null&&b.success&&Array.isArray(N)&&(n(t.routeId,N),Cn(N,t)&&!Cn(r,t)&&Ds(a,"⚠️ History dialog did not fully open — try once more"))}catch(h){console.error("Refresh history failed",h)}finally{f(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:x,handleNewChat:m,handleRefreshHistory:v}}function Xp(e,t){if(e.size!==t.size)return!1;for(const[r,n]of e)if(t.get(r)!==n)return!1;return!0}function Jp(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Uo(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length!==n.length?!1:r.every(a=>t[Number(a)]===e[Number(a)])}function vr(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const d=a[l];typeof d=="number"&&d>0&&i.set(c,d)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function zo(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=t[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function Qp(e,t,r){if(t.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...t].reverse().find(a=>a<e)??t[0];return r[n]??0}function Zp(e,t,r){if(t.length<=1)return[];const n=t.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===t.length?n:Array(r).fill(100/r),i=a.reduce((c,l)=>c+l,0);return i>0?a.map(c=>c/i*100):Array(r).fill(100/r)}function Vo(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=t?i+1:i]=a}return r}function Go(e){return Array(e).fill(100/e)}function eh({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:d,visibleTabKeys:f}){const u=o.useRef(null),x=o.useMemo(()=>vr(e,f),[e,f]),m=x.assignments,v=o.useMemo(()=>l?1:x.groupCount,[x.groupCount,l]),S=v>1,p=o.useCallback((y,C)=>{t(k=>{const w=new Map(vr(k,f).assignments);return C===0?w.delete(y):w.set(y,C),w}),n(k=>({...k,[C]:y})),r(C)},[t,f,n,r]),h=o.useCallback(y=>{t(C=>{const k=vr(C,f).assignments,w=new Map;for(const[g,D]of k)D!==y&&(D>y?w.set(g,D-1):w.set(g,D));return w}),c(C=>{if(C.length<=1)return[];const k=[...C];k.splice(y,1);const w=k.reduce((g,D)=>g+D,0);return w>0?k.map(g=>g/w*100):[]}),r(0)},[t,f,c,r]),j=o.useCallback((y,C)=>{C.preventDefault();const k=u.current;if(!k)return;const w=C.clientX,g=k.offsetWidth,D=i.length===v?[...i]:Go(v),A=P=>{const V=(P.clientX-w)/g*100,L=[...D];L[y]=Math.max(15,D[y]+V),L[y+1]=Math.max(15,D[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,v,c]),b=o.useCallback((y,C,k)=>{if(v>=4)return;const w=k==="left"?C:C+1;t(g=>{const D=vr(g,f).assignments,A=new Map;for(const I of d){const P=D.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(g=>{const D=g.length===v?[...g]:Go(v),A=D[C]??100/v,I=Math.max(15,A/2),P=Math.max(15,A/2),O=[...D];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(g=>{const D=Vo(g,w);return D[w]=y,D}),a(g=>{const D=Vo(g,w);return D[w]=[y],D}),r(w)},[v,t,f,d,c,n,a,r]);o.useEffect(()=>{Xp(e,m)||t(m)},[e,m,t]),o.useEffect(()=>{const{mapping:y,usedGroups:C}=x;n(k=>{const w=zo(k,y);return Uo(k,w)?k:w}),a(k=>{const w=zo(k,y);return Uo(k,w)?k:w}),r(k=>{const w=l?0:Qp(k,C,y);return k===w?k:w}),c(k=>{const w=l?[]:Zp(k,C,x.groupCount);return Jp(k,w)?k:w})},[x,l,n,a,r,c]);const N=o.useMemo(()=>{const y=Array.from({length:v},()=>[]);for(const C of d){const k=m.get(C.tabKey)??0,w=Math.min(k,v-1);y[w].push(C)}return y},[d,m,v]),T=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:m,numGroups:v,isSplitMode:S,groupedConvs:N,moveTabToGroup:p,closeGroup:h,handleResizeStart:j,splitTabRelative:b,clearAllSplits:T}}function th({ides:e,sendDaemonCommand:t}){const r="0.9.25",n=o.useMemo(()=>e.filter(u=>u.type!=="adhdev-daemon"?!1:Pc(u,r)).sort((u,x)=>Number(zs(x,r))-Number(zs(u,r))),[r,e]),a=o.useMemo(()=>n.some(u=>zs(u,r)),[r,n]),[i,c]=o.useState(!1),[l,d]=o.useState({}),f=o.useCallback(async u=>{var x,m;d(v=>({...v,[u]:"upgrading"}));try{const v=await t(u,"daemon_upgrade",{});(x=v==null?void 0:v.result)!=null&&x.upgraded||(m=v==null?void 0:v.result)!=null&&m.success?d(S=>({...S,[u]:"done"})):d(S=>({...S,[u]:"error"}))}catch{d(v=>({...v,[u]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}const Yc=80;function Pr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function sh(e){return{...e,createdAt:Pr(e.createdAt),updatedAt:Pr(e.updatedAt,e.createdAt),lastEventAt:Pr(e.lastEventAt,e.updatedAt||e.createdAt)}}function rh(e){const t=Ca(e);return t==="unknown:"?e.id:t}function nh(e){return[e.type,nc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function ah(e,t=Yc){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=rh(n),i=r.get(a);if(!i){r.set(a,n);continue}(n.updatedAt>i.updatedAt||n.updatedAt===i.updatedAt&&n.createdAt>i.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const i=a.updatedAt-n.updatedAt;return i!==0?i:a.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function oh(e,t){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?t.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=Qr(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const d=Pr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),f=nh({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(sh({id:f,dedupKey:f,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:ec(a),preview:fm(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return ah(n)}function ih(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function ch(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Yc}=e,a=o.useMemo(()=>oh(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>ih(a),[a]);return{notifications:a,unreadCount:i}}function lh({notifications:e,sendDaemonCommand:t}){const r=o.useCallback(i=>{const c=e.find(d=>d.id===i),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,t]),n=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}function tn(...e){const t=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();t.has(c)||(t.add(c),r.push(i))};for(const a of e){if(Array.isArray(a)){for(const i of a)n(i);continue}n(a)}return r}function dh(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const r=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function sn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=dh(r);if(n)return n}return"C:\\"}for(const r of t){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function uh(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const r=t.includes("\\")?"\\":"/",n=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(n[0]||"")?n.length<=2?`${n[0]}\\`:n.slice(0,-1).join("\\"):n.length<=2?r:n.slice(0,-1).join(r)||r}function mh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function rn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=mh(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,u)=>/^[A-Za-z]:\\?$/.test(f)?`${f.replace(/\\?$/,"\\")}${u}`:f==="/"||f==="\\"?`${c}${u}`:`${f.replace(/[\\/]+$/,"")}${c}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(f=>(f==null?void 0:f.type)==="directory"&&typeof(f==null?void 0:f.name)=="string").map(f=>({name:f.name,path:typeof(f==null?void 0:f.path)=="string"&&f.path.trim()?f.path:l(i,f.name)})).sort((f,u)=>f.name.localeCompare(u.name)):[];return{path:i,directories:d}}function fh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function qo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ph(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function hh({ides:e,conversations:t,onOpenSession:r}){const[n,a]=o.useState(null),i=o.useCallback(c=>{a(c)},[]);return o.useEffect(()=>{if(!n)return;const c=qo(n.workspacePath),l=e.find(f=>{var S,p,h,j;if(!f||f.type==="adhdev-daemon"||fh(f.daemonId||f.id)!==n.machineId||(Qs(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 b=qo(f.workspace||f.runtimeWorkspaceLabel);return b?b===c:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((j=(h=(p=(S=f.activeChat)==null?void 0:S.messages)==null?void 0:p.at)==null?void 0:h.call(p,-1))==null?void 0:j.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const d=ic({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});d&&(a(null),r(d))},[t,e,r,n]),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 xh({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=o.useCallback(async(m,v)=>rn(e,m,v),[e]),l=o.useCallback(async(m,v)=>{if(!v.trim())return{ok:!1,error:"Choose a workspace path first."};try{const S=await e(m,"workspace_add",{path:v.trim()});return S!=null&&S.success?{ok:!0}:{ok:!1,error:(S==null?void 0:S.error)||"Could not save workspace"}}catch(S){return{ok:!1,error:S instanceof Error?S.message:"Could not save workspace"}}},[e]),d=o.useCallback(async(m,v,S)=>{var p;try{const h={ideType:v,enableCdp:!0};(p=S==null?void 0:S.workspacePath)!=null&&p.trim()&&(h.workspace=S.workspacePath.trim());const j=await e(m,"launch_ide",h);return!(j!=null&&j.success)&&(j==null?void 0:j.success)!==void 0?{ok:!1,error:(j==null?void 0:j.error)||"Could not launch IDE"}:(t({machineId:m,kind:"ide",providerType:v,workspacePath:(S==null?void 0:S.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(h){return{ok:!1,error:h instanceof Error?h.message:"Could not launch IDE"}}},[e,t]),f=o.useCallback(async(m,v,S,p)=>{var j,b,N;const h=Date.now();try{const T={cliType:S};(j=p==null?void 0:p.workspacePath)!=null&&j.trim()?T.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(T.workspaceId=p.workspaceId),(b=p==null?void 0:p.resumeSessionId)!=null&&b.trim()&&(T.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(T.cliArgs=p.cliArgs),(N=p==null?void 0:p.initialModel)!=null&&N.trim()&&(T.initialModel=p.initialModel.trim());const y=await e(m,"launch_cli",T),C=(y==null?void 0:y.result)||y,k=(C==null?void 0:C.sessionId)||(C==null?void 0:C.id);return y!=null&&y.success&&k?(r(k),{ok:!0}):y!=null&&y.success?(t({machineId:m,kind:v,providerType:S,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:h}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(C==null?void 0:C.error)||`Could not launch ${v.toUpperCase()} session`}}catch(T){return ph(T)?(t({machineId:m,kind:v,providerType:S,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:h}),{ok:!0}):{ok:!1,error:T instanceof Error?T.message:`Could not launch ${v.toUpperCase()} session`}}},[r,e,t]),u=o.useCallback(async(m,v)=>{if(!m||!v)return[];try{const S=await e(m,"list_saved_sessions",{providerType:v,kind:"cli",limit:30}),p=(S==null?void 0:S.result)??S;return Array.isArray(p==null?void 0:p.sessions)?p.sessions:[]}catch(S){return console.error("List saved sessions failed",S),[]}},[e]),x=o.useCallback(async m=>{await Fc({conversation:n,mode:m,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:i})},[n,a,e,i]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:d,handleLaunchMachineProvider:f,handleListMachineSavedSessions:u,setActiveCliViewMode:x}}function bh(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 gh(e,t,r=Date.now()){return!e||!bh(t)?null:{tabKey:e,nonce:r}}function yh({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,d]=o.useState(null),[f,u]=o.useState(null),x=o.useMemo(()=>{var h,j;if(!e){if(l){const b=t.find(N=>N.tabKey===l);if(b)return b}return r[0]}const p=n[a];if(p){const b=t.find(N=>N.tabKey===p);if(b)return b}return((h=i[a])==null?void 0:h[0])||((j=i[0])==null?void 0:j[0])},[t,l,a,n,i,e,r]),m=o.useCallback(p=>{d(p)},[]),v=o.useCallback(p=>{d(p.tabKey),c(h=>{const j=new URLSearchParams(h),b=hm(p);return b?j.set("activeTab",b):j.delete("activeTab"),j},{replace:!0})},[c]),S=o.useCallback((p,h)=>{const j=gh(p,h);j&&u(j)},[]);return{activeConv:x,openDesktopConversation:v,requestScrollToBottom:S,scrollToBottomRequest:f,setDesktopActiveTab:m}}function vh({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:d}){var L;const[f,u]=o.useState(!1),[x,m]=o.useState([]),[v,S]=o.useState(()=>ht()),[p,h]=o.useState(!1),[j,b]=o.useState(null),N=o.useRef(null),T=o.useMemo(()=>r||t||e,[e,r,t]),y=!!T&&Qe(T)&&!Xe(T),C=o.useMemo(()=>{if(!T||!y)return null;const R=T.daemonId||T.routeId||"",G=Kt(T);return`${R}:${G}`},[T,y]),{isCreatingChat:k,isRefreshingHistory:w,handleSwitchSession:g,handleNewChat:D,handleRefreshHistory:A}=qc({sendDaemonCommand:a,activeConv:T,chats:(L=n.find(R=>R.id===(T==null?void 0:T.routeId)))==null?void 0:L.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),I=o.useCallback(()=>{u(!0)},[]),P=o.useCallback(()=>{u(!1)},[]),O=o.useCallback(async()=>{if(!(!T||!y||p)){h(!0);try{const R=T.daemonId||T.routeId,G=Kt(T),K=await a(R,"list_saved_sessions",{agentType:G,providerType:G,kind:"cli",limit:50}),E=(K==null?void 0:K.result)??K;m(Array.isArray(E==null?void 0:E.sessions)?E.sessions:[])}catch(R){console.error("Refresh saved sessions failed",R),m([])}finally{h(!1)}}},[T,p,y,a]);o.useEffect(()=>{if(!f){N.current=null;return}if(!y){N.current=null,m([]),h(!1);return}!C||p||N.current!==C&&(N.current=C,O())},[O,f,p,y,C]);const V=o.useCallback(async R=>{if(!T||!y||!R.providerSessionId||!R.workspace)return;const G=T.daemonId||T.routeId,K=Kt(T);try{b(R.providerSessionId);const E=await a(G,"launch_cli",{cliType:K,dir:R.workspace,resumeSessionId:R.providerSessionId,initialModel:Gi(R.summaryMetadata,"model",{preferShortValue:!0})||void 0}),W=(E==null?void 0:E.result)??E,J=typeof(W==null?void 0:W.sessionId)=="string"?W.sessionId:typeof(W==null?void 0:W.id)=="string"?W.id:"";J&&d(be=>{const xe=new URLSearchParams(be);return xe.set("activeTab",J),xe},{replace:!0}),P()}catch(E){console.error("Resume saved session failed",E)}finally{b(null)}},[P,T,y,a,d]);return{historyModalOpen:f,openHistoryModal:I,closeHistoryModal:P,historyTargetConv:T,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:k,isHistoryRefreshingHistory:w,handleHistorySwitchSession:g,handleHistoryNewChat:D,handleHistoryRefresh:A,savedHistorySessions:x,savedHistoryFilters:v,setSavedHistoryFilters:S,isSavedHistoryLoading:p,resumingSavedHistorySessionId:j,handleRefreshSavedHistory:O,handleResumeSavedHistorySession:V}}function wh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[d,f]=o.useState(null),[u,x]=o.useState(null),m=o.useMemo(()=>{if(e||!n)return null;const j=l(n);return j&&!Qe(j)&&!Xe(j)?j:null},[e,n,l]),v=o.useMemo(()=>{const j=d==null?void 0:d.routeId;if(!j)return null;const b=d!=null&&d.tabKey?i.find(N=>N.tabKey===d.tabKey):a?i.find(N=>N.tabKey===a):null;return(b==null?void 0:b.routeId)===j?b:_t(i,j)},[i,d,a]),S=o.useMemo(()=>{if(v)return c.find(j=>j.id===v.routeId)},[c,v]);o.useEffect(()=>{m&&(f({routeId:m.routeId,tabKey:Co(m)}),x(m),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,m]);const p=o.useCallback(j=>{j&&(f({routeId:j.routeId,tabKey:Co(j)}),x(j))},[]),h=o.useCallback(()=>{f(null),x(null)},[]);return{remoteDialogConv:v,remoteDialogIdeEntry:S,remoteDialogActiveConv:u,setRemoteDialogActiveConv:x,openRemoteDialog:p,closeRemoteDialog:h}}function jh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:f}){const{remoteDialogConv:u,remoteDialogIdeEntry:x,remoteDialogActiveConv:m,setRemoteDialogActiveConv:v,openRemoteDialog:S,closeRemoteDialog:p}=wh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[h,j]=o.useState(!1),[b,N]=o.useState(null),T=o.useCallback(async k=>{const w=k||d;!w||!Qe(w)&&!Xe(w)||(N(w),j(!0))},[d]),y=o.useCallback(()=>{j(!1),N(null)},[]),C=o.useCallback(async k=>{const w=b||d;if(!w||!Qe(w)&&!Xe(w)){y();return}j(!1);try{const g=Kt(w),D=w.routeId||w.daemonId||"";await f(D,"stop_cli",{cliType:g,targetSessionId:w.sessionId,mode:k})}catch(g){console.error("Stop CLI failed:",g)}finally{N(null)}},[d,y,b,f]);return{remoteDialogConv:u,remoteDialogIdeEntry:x,remoteDialogActiveConv:m,setRemoteDialogActiveConv:v,openRemoteDialog:S,closeRemoteDialog:p,cliStopDialogOpen:h,cliStopTargetConv:b,requestCliStop:T,cancelCliStop:y,confirmCliStop:C}}function Xc(){return"select_session"}function kh(){return"open_panel"}function Sh({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Nh(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Yo(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Xo(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function za(e){return e instanceof Error?e.message:String(e||"")}function Jo(e){const t=za(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Qo(e,t){const r=za(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function nn({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[d,f]=o.useState(null),u=o.useRef(!1),x=o.useRef(null);o.useEffect(()=>{f(null)},[t==null?void 0:t.tabKey]);const m=o.useCallback(async h=>{if(!t)return!1;const j=h.trim(),b=Aa(t);if(Sh({hasMessage:!!j,blockedMessage:b,sendInFlight:u.current}))return b&&f(b),!1;const N=Date.now(),T={tabKey:t.tabKey,message:j,timestamp:N};if(Nh(x.current,T))return f(null),!0;u.current=!0,l(!0),f(null),x.current=T;try{const y=Zs(t);if(!y)return x.current=Yo(x.current,T),f("Unable to send message right now."),!1;const C=await e(y,"send_chat",{message:j,...js(t)}),k=Xo(C);if(k!=null&&k.deduplicated)return f(null),!0;if((k==null?void 0:k.sent)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");if((k==null?void 0:k.success)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");return f(null),!0}catch(y){const C=za(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),x.current=Yo(x.current,T),f(_m(y)),!1}finally{u.current=!1,l(!1)}},[t,e]),v=o.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(h){console.error("Relaunch failed",h)}},[t,e]),S=o.useCallback(async h=>{if(t)try{const b=(t.modalButtons||[]).indexOf(h),N=h.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),T=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),y=Zs(t);if(!y)return;const C=await e(y,"resolve_action",{button:h,action:T?"approve":"reject",...b>=0&&{buttonIndex:b},...js(t)}),k=Xo(C);k.success||r(w=>[...w,{routeId:t.tabKey,text:Qo(h,k==null?void 0:k.error),timestamp:Date.now()}])}catch(j){Jo(j)||console.error("[ModalButton] Error:",j),r(b=>[...b,{routeId:t.tabKey,text:Jo(j)?Qo(h,j):`❌ **${h}** error`,timestamp:Date.now()}])}},[t,e,r]),p=o.useCallback(async()=>{if(!(!t||a)){i(!0);try{await e(t.routeId,kh(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(h){console.error("Focus agent failed",h)}finally{i(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:m,handleRelaunch:v,handleModalButton:S,handleFocusAgent:p}}function In(e,t=!0){return(e??!0)&&t}const Va=o.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u=null,handleFocusAgent:x,isFocusingAgent:m,actionLogs:v,userName:S,scrollToBottomRequestNonce:p,isInputActive:h=!0,isVisible:j=!0}){const[b,N]=o.useState(n),T=o.useRef(n);o.useEffect(()=>{const I=T.current;if(T.current=n,!n){N(!1);return}if(I){N(!0);return}N(!1);let P=0,O=0;return P=window.requestAnimationFrame(()=>{O=window.requestAnimationFrame(()=>{N(!0)})}),()=>{window.cancelAnimationFrame(P),window.cancelAnimationFrame(O)}},[n]);const y=n&&b,C=!n||!b,k=In(j,n),w=In(j,C),g=In(j),D=Bc(t),A=D.status||D.modalMessage||D.modalButtons?{...t,...D.status?{status:D.status}:{},...D.modalMessage!==void 0?{modalMessage:D.modalMessage}:{},...D.modalButtons!==void 0?{modalButtons:D.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Hi,{activeConv:A,onModalButton:c}),A.transport!=="pty"&&A.transport!=="acp"&&A.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(Xs,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:l,children:"Relaunch with CDP"})]})}):null,A.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:y?"visible":"hidden",pointerEvents:y?"auto":"none"},children:s.jsx(ff,{activeConv:A,clearToken:r,terminalRef:i,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,isVisible:k,isInputActive:h&&k})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(na,{activeConv:A,ideEntry:a,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,handleFocusAgent:x,isFocusingAgent:m,actionLogs:v,userName:S,scrollToBottomRequestNonce:p,isInputActive:h&&w,isVisible:w})})]}):s.jsx(na,{activeConv:A,ideEntry:a,handleSendChat:d,isSendingChat:f,sendFeedbackMessage:u,handleFocusAgent:x,isFocusingAgent:m,actionLogs:v,userName:S,scrollToBottomRequestNonce:p,isInputActive:h&&g,isVisible:g})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function Ch({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:f,onOpenNativeConversation:u,onOpenMachine:x,onOpenHistory:m,onOpenRemote:v,onHideConversation:S,onStopCli:p,cliViewMode:h,onSetCliViewMode:j,handleSendChat:b,handleFocusAgent:N,handleModalButton:T,handleRelaunch:y}){const C=o.useRef(null),k=Qe(e)&&!t,w=k&&h==="terminal",g=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${g} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:f,type:"button","aria-label":"Back",children:s.jsx(xa,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:rt(e)}),s.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:s.jsx(cc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>x(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[k&&h&&s.jsx(Ra,{mode:h,onChange:j,compact:!0}),k&&p&&s.jsx("button",{onClick:()=>{p(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(vt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(e),type:"button",children:s.jsx(ba,{size:14})}),!t&&!k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),type:"button",children:s.jsx(Nt,{size:14})}),S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Close chat",children:s.jsx(vt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(Va,{activeConv:e,clearToken:0,isCliTerminal:w,ideEntry:n,terminalRef:C,handleModalButton:T,handleRelaunch:y,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:N,isFocusingAgent:d,actionLogs:a,userName:i})})]})}const Mn={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 Jc(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(Ih())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Mn[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:Mn[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Mn[c].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Qc({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Nt},{key:"chats",label:"Chats",icon:Ut}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:i})=>{const c=e===n;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(n),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(i,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function wr({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function hs({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function Bs({icon:e,title:t,subtitle:r,children:n}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function jr({item:e,type:t,getAvatarText:r,onOpenConversation:n}){const a=t==="needs_attention"||t==="task_complete",i=t==="working",c=t==="earlier",l=t==="task_complete",{isReconnecting:d,isConnecting:f}=Ts(e.conversation),u=rt(e.conversation),x=us(e.conversation),m=xc(e.conversation,{requiresAction:t==="needs_attention"}),v=a?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",S=a?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",p=c?"text-text-secondary":"text-text-primary",h=c?"text-text-muted":"text-text-secondary",j=c?"text-text-secondary opacity-80":"text-text-muted",b=c?"text-text-muted opacity-80":"text-text-muted",N="text-[color:var(--status-warning)]";return s.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${v}`,onClick:()=>n(e.conversation),type:"button",children:[a||i?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${S}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(u)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${p}`,children:u}),!i&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${b}`,children:Wi(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${h}`,children:[x,d?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${N} animate-pulse`,children:"Reconnecting…"})]}):f?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):m==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:N,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${j}`,children:e.preview})]}),a&&!l&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),i&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]},e.conversation.tabKey)}function Zo({size:e=32,label:t}){return s.jsxs("div",{className:"flex flex-col items-center gap-2.5",children:[s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}}),t&&s.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:t})]})}function Mh({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:d,onShowConversation:f,onShowAllHidden:u,onOpenNewSession:x,onOpenMachine:m,onOpenSettings:v,onSectionChange:S,wsStatus:p="connected",isStandalone:h=!1}){const j=p==="disconnected"||p==="reconnecting"||p==="offline"||p==="auth_failed",b=c.length>0,N=t.length>0||r.length>0||n.length>0||a.length>0,T=e==="machines"?"Machines":"Chats",y=h?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",C=h?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${y}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:T}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Xr,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:v,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Yr,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${C}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:j?s.jsx(Bs,{icon:s.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?s.jsx(Bs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:h?"Waiting for your daemon":"Connect your machines",subtitle:h?"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:!h&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Jc,{})})}):s.jsx(hs,{children:c.map((k,w)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>m(k.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(k.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:k.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:k.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[k.unread," new"]}):k.total>0?`${k.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:k.subtitle}),k.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[k.total," chat",k.total!==1?"s":"",k.unread>0?` · ${k.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},k.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Needs attention",className:"mb-0"}),s.jsx(hs,{children:t.map((k,w)=>s.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"needs_attention",getAvatarText:l,onOpenConversation:d})},k.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(hs,{children:r.map((k,w)=>s.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"task_complete",getAvatarText:l,onOpenConversation:d})},k.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(hs,{children:n.map((k,w)=>s.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"working",getAvatarText:l,onOpenConversation:d})},k.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(wr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(hs,{children:a.map((k,w)=>s.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:k,type:"earlier",getAvatarText:l,onOpenConversation:d})},k.conversation.tabKey))}):N?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):j?s.jsx(Bs,{icon:s.jsx(Zo,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):b?s.jsx(Bs,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Ut,{size:20})}),title:"No conversations yet",subtitle:yc,children:x&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:x,"aria-label":$t,title:$t,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:$t})]})}):s.jsx(Bs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[s.jsx("span",{children:"Hidden"}),s.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:u,children:"Restore all"})]}),s.jsx(hs,{className:"bg-bg-secondary/25",children:i.map((k,w)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] opacity-50 saturate-0 ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(k),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(rt(k))}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:rt(k)}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:us(k)}),s.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},k.tabKey))})]})]}),e==="chats"&&x&&N&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:x,"aria-label":$t,title:$t,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),s.jsx(Qc,{section:e,onSectionChange:S})]})}function Ah(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 Zc(e){const t=[e.workspace||"Workspace unknown"],r=ds(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Ah(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function an({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:d,onConfirm:f}){const[u,x]=o.useState(r);o.useEffect(()=>{x(r)},[r]);const m=uh(r),v=u.trim();return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!m||a||d(m)},disabled:!m||a,children:[s.jsx(xa,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:S=>x(S.target.value),onKeyDown:S=>{S.key!=="Enter"||!v||a||(S.preventDefault(),d(v))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!v||a||d(v)},disabled:!v||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(S=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(S.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Ns,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:S.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:S.path})]})]},S.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>f(v||r),disabled:!v&&!r||a,children:c})]})]})})}function Ga({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:f,argsValue:u,onArgsChange:x,showModelInput:m,modelValue:v,onModelChange:S,historyProviderNode:p,onConfirm:h,onCancel:j}){const b=n==null?void 0:n.find(N=>N.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:j,"aria-label":"Close launch confirmation",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:N=>i(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(N=>s.jsx("option",{value:N.key,children:N.label},N.key))}),(b==null?void 0:b.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:b.description})]}),p,r.map(N=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:N.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${N.value}`)),m&&S&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:v||"",onChange:N=>S(N.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),f&&x&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:N=>x(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:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:j,disabled:d,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:h,disabled:d,children:[s.jsx(ya,{size:14}),d?l:c]})]})]})})}function ei(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function os(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])i.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${ei(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(d=>d.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:ei(c),description:c,workspaceId:null,workspacePath:c}),n){const d=`saved:${n}`;if(i.some(f=>f.key===d))return{options:i,selectedKey:d}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Th(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Lh(e){return[Th(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Rh(e){return e.lastLaunchedAt?Jr(e.lastLaunchedAt):""}function el(e){return{metaText:Lh(e),updatedLabel:Rh(e)}}function An(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Ph({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var dt,mt,at,ut;const c=ar(),[l,d]=o.useState(!1),f=(((dt=e.detectedIdes)==null?void 0:dt.length)||0)>0,u=o.useMemo(()=>(e.workspaces||[]).map(Ce=>({id:Ce.id,path:Ce.path,label:Ce.label})),[e]),x=e.defaultWorkspaceId||null,[m,v]=o.useState(x||((mt=u[0])==null?void 0:mt.id)||""),[S,p]=o.useState(""),[h,j]=o.useState(""),[b,N]=o.useState([]),[T,y]=o.useState(!1),[C,k]=o.useState(""),[w,g]=o.useState(!1),[D,A]=o.useState(An(f,t.length,r.length)),I=o.useRef(null),[P,O]=o.useState(null),V=o.useRef("__home__"),[L,R]=o.useState("__home__"),[G,K]=o.useState(""),[E,W]=o.useState(""),[J,be]=o.useState(""),[xe,de]=o.useState([]),[ye,ge]=o.useState(()=>ht().textQuery),[ve,z]=o.useState(()=>ht().workspaceQuery),[F,Q]=o.useState(()=>ht().modelQuery),[ue,te]=o.useState(()=>ht().resumableOnly),[fe,re]=o.useState(()=>ht().sortMode),[pe,oe]=o.useState(!1),[le,ae]=o.useState(!1),Y=o.useRef(null),X=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const ne=m==="__custom__"?S.trim():((at=u.find(Ce=>Ce.id===m))==null?void 0:at.path)||"",M=m==="__custom__"&&!!ne&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),H=m!=="__custom__"&&((ut=u.find(Ce=>Ce.id===m))==null?void 0:ut.path)||"",ce=o.useMemo(()=>(e.recentLaunches||[]).map(Ce=>Ce.workspace),[e]),me=o.useCallback(async Ce=>{y(!0),k("");try{const $e=await a(Ce);j($e.path),p($e.path),N($e.directories)}catch($e){k($e instanceof Error?$e.message:"Could not load folder")}finally{y(!1)}},[a]),je=o.useCallback(()=>{var $e;v("__custom__"),g(!0);const Ce=sn(e.platform,tn(S.trim(),H,ce,e.defaultWorkspacePath,($e=u.find(Ue=>Ue.id===x))==null?void 0:$e.path,u.map(Ue=>Ue.path)));me(Ce)},[S,x,me,ce,H,e.platform,u]),_e=o.useCallback(Ce=>{if(Ce!=null&&Ce.workspaceId){v(Ce.workspaceId),p("");return}if(Ce!=null&&Ce.workspacePath){v("__custom__"),p(Ce.workspacePath);return}v(""),p("")},[]),Me=o.useCallback(Ce=>{if(v(Ce),Ce==="__custom__"){je();return}p("")},[je]),Be=o.useCallback(Ce=>{v("__custom__"),p(Ce)},[]),We=o.useCallback((Ce,$e)=>{I.current=$e,V.current=Ce.selectedWorkspaceKey||"__home__",R(Ce.selectedWorkspaceKey||"__home__"),K(Ce.initialArgs||""),W(Ce.initialModel||""),be(""),de([]);const Ue=Ce.providerType?`${e.id}:${Ce.providerType}`:null;if(vf(X.current,Ue)){const Ve=ht();ge(Ve.textQuery),z(Ve.workspaceQuery),Q(Ve.modelQuery),te(Ve.resumableOnly),re(Ve.sortMode)}X.current=Ue,O(Ce),Ce.providerType&&i&&(oe(!0),i(Ce.providerType).then(Ve=>de(Ve||[])).catch(Ve=>console.warn("Failed to load saved sessions",Ve)).finally(()=>oe(!1)))},[i,e.id]),Fe=o.useMemo(()=>vc(xe,{textQuery:ye,workspaceQuery:ve,modelQuery:F,resumableOnly:ue,sortMode:fe}),[F,ue,xe,fe,ye,ve]);o.useEffect(()=>{J&&(Fe.some(Ce=>Ce.providerSessionId===J)||be(""))},[Fe,J]);const nt=o.useCallback(()=>{I.current&&(ae(!0),I.current().finally(()=>{I.current=null,ae(!1),O(null)}))},[]),Ze=o.useCallback(()=>{I.current=null,O(null)},[]),it=o.useCallback(Ce=>{V.current=Ce,R(Ce)},[]);return o.useEffect(()=>{var Ce;Y.current!==e.id&&(Y.current=e.id,v(x||((Ce=u[0])==null?void 0:Ce.id)||"__custom__"),p(""),j(""),N([]),k(""),g(!1),ge(ht().textQuery),z(ht().workspaceQuery),Q(ht().modelQuery),te(ht().resumableOnly),re(ht().sortMode),X.current=null,A(An(f,t.length,r.length)))},[r.length,t.length,x,f,e.id,u]),o.useEffect(()=>{var Ce;m!=="__custom__"&&(m&&u.some($e=>$e.id===m)||v(x||((Ce=u[0])==null?void 0:Ce.id)||"__custom__"))},[x,m,u]),o.useEffect(()=>{D==="ide"&&f||D==="cli"&&t.length>0||D==="acp"&&r.length>0||A(An(f,t.length,r.length))},[D,r.length,t.length,f]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:f,workspaceRows:u,defaultWorkspaceId:x,workspaceChoice:m,customWorkspacePath:S,browseCurrentPath:h,browseDirectories:b,browseBusy:T,browseError:C,browseDialogOpen:w,activeLauncherKind:D,launchConfirm:P,launchConfirmWorkspaceKeyRef:V,launchConfirmWorkspaceKey:L,launchConfirmArgs:G,launchConfirmModel:E,launchConfirmResumeId:J,launchConfirmSavedSessions:xe,launchConfirmTextFilter:ye,launchConfirmWorkspaceFilter:ve,launchConfirmModelFilter:F,launchConfirmResumableOnly:ue,launchConfirmSortMode:fe,filteredLaunchConfirmSavedSessions:Fe,launchConfirmSessionsLoading:pe,launchConfirmBusy:le,resolvedWorkspacePath:ne,canCreateMissingWorkspace:M,openBrowseDialog:je,loadBrowsePath:me,handleWorkspaceChoiceChange:Me,chooseCustomWorkspacePath:Be,setCustomWorkspacePath:p,setBrowseDialogOpen:g,setActiveLauncherKind:A,openLaunchConfirm:We,handleConfirmLaunch:nt,closeLaunchConfirm:Ze,setWorkspaceSelectionFromOption:_e,setLaunchConfirmWorkspaceKeyAndSync:it,setLaunchConfirmArgs:K,setLaunchConfirmModel:W,setLaunchConfirmResumeId:be,setLaunchConfirmTextFilter:ge,setLaunchConfirmWorkspaceFilter:z,setLaunchConfirmModelFilter:Q,setLaunchConfirmResumableOnly:te,setLaunchConfirmSortMode:re}}function _h({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:d,section:f,showBottomNav:u,onBack:x,onSectionChange:m,onOpenConversation:v,onOpenRecent:S,onOpenMachineDetails:p,onMachineUpgrade:h,onLaunchDetectedIde:j,onAddWorkspace:b,onBrowseDirectory:N,onLaunchWorkspaceProvider:T,onListSavedSessions:y}){const C=L=>L==="ide"?"IDE":L==="cli"?"CLI":"ACP",k=r.slice(0,4),w=t.slice(0,3),g=Ph({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:y}),D=o.useMemo(()=>k.map(L=>{const{metaText:R,updatedLabel:G}=el(L);return{key:`recent-launch:${L.id}`,primary:L.label,secondary:R,updatedLabel:G,onClick:()=>{const{options:K,selectedKey:E}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspacePath:L.workspace});g.openLaunchConfirm({title:L.kind==="ide"?ss("restart-ide",L.label):L.providerSessionId?Da(L.label):ss("start-fresh",L.label),description:L.kind==="ide"?rs("restart-ide"):L.providerSessionId?Ea():rs("start-fresh"),confirmLabel:L.kind==="ide"?Is("restart-ide"):L.providerSessionId?Ur(!0):Is("start-fresh"),busyLabel:L.kind==="ide"?Ms("restart-ide"):L.providerSessionId?Pa(!0):Ms("start-fresh"),workspaceOptions:K,selectedWorkspaceKey:E,details:[{label:"Mode",value:C(L.kind)},...L.providerType?[{label:"Provider",value:L.providerType}]:[]]},async()=>{const W=K.find(J=>J.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(W),await S({...L,workspace:(W==null?void 0:W.workspacePath)??null})})}}}),[g,S,k]),A=o.useMemo(()=>w.map(L=>({key:`recent-chat:${L.conversation.tabKey}`,primary:rt(L.conversation),secondary:lf(L.conversation,{timestampLabel:L.timestamp?Wi(L.timestamp):null}),unread:L.unread,onClick:()=>v(L.conversation)})),[v,w]),I=g.showAllRecent?D:D.slice(0,4),P=D.length>0,O=A.length>0,V=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${V} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:x,type:"button","aria-label":"Back",children:s.jsx(xa,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:At(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[O&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:A.map(L=>s.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:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:L.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))})]}),P&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:I.map(L=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:L.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:L.primary}),L.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:L.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))}),D.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>g.setShowAllRecent(L=>!L),children:g.showAllRecent?"Show fewer":`Show ${D.length-4} more`})})]}),(g.hasIdeOptions||n.length>0||a.length>0)&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:s.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),s.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),s.jsx("select",{value:g.workspaceChoice,onChange:L=>g.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:g.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[g.workspaceRows.map(L=>s.jsxs("option",{value:L.id,children:[L.id===g.defaultWorkspaceId?"⭐ ":"",Zr(L.path,L.label)||L.path]},L.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),g.workspaceChoice==="__custom__"&&s.jsxs("div",{className:"flex flex-col gap-2.5",children:[s.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Ns,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),s.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:g.resolvedWorkspacePath||g.browseCurrentPath||"No folder selected yet."})]})]})}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:g.openBrowseDialog,children:"Select workspace…"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{g.resolvedWorkspacePath&&b(g.resolvedWorkspacePath)},disabled:!g.resolvedWorkspacePath||g.browseBusy,children:"Save as workspace"})]})]}),g.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[g.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.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:()=>g.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.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:()=>g.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.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:()=>g.setActiveLauncherKind("acp"),children:"ACP"})]}),g.activeLauncherKind&&s.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[s.jsx("div",{className:"text-xs font-bold text-text-secondary",children:g.activeLauncherKind==="ide"?"Choose an IDE":g.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:g.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(L=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:R,selectedKey:G}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.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 K=R.find(E=>E.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(K),j(L.type,{workspacePath:(K==null?void 0:K.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:L.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},L.type)):(g.activeLauncherKind==="cli"?n:a).map(L=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const R=g.activeLauncherKind==="cli"?"cli":"acp",{options:G,selectedKey:K}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${L.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${R.toUpperCase()}`,workspaceOptions:G,selectedWorkspaceKey:K,details:[{label:"Mode",value:R.toUpperCase()},{label:"Provider",value:L.displayName}],showArgsInput:!0,showModelInput:R==="acp",initialArgs:"",initialModel:"",providerType:L.type},async()=>{const E=G.find(W=>W.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(E),T(R,L.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.workspacePath)??null,args:g.launchConfirmArgs,model:g.launchConfirmModel,resumeSessionId:g.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[L.icon?`${L.icon} `:"",L.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},L.type))})]}),l.message&&s.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,g.canCreateMissingWorkspace&&s.jsx("div",{className:"mt-2",children:s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>b(g.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:h,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:p,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),g.browseDialogOpen&&s.jsx(an,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:g.browseCurrentPath,directories:g.browseDirectories,busy:g.browseBusy,error:g.browseError,confirmLabel:"Use this folder",onClose:()=>g.setBrowseDialogOpen(!1),onNavigate:L=>{g.loadBrowsePath(L)},onConfirm:L=>{g.chooseCustomWorkspacePath(L),g.setBrowseDialogOpen(!1)}}),g.launchConfirm&&s.jsx(Ga,{title:g.launchConfirm.title,description:g.launchConfirm.description,details:g.launchConfirm.details,workspaceOptions:g.launchConfirm.workspaceOptions,selectedWorkspaceKey:g.launchConfirmWorkspaceKey,onWorkspaceChange:g.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:g.launchConfirm.providerType?Ur(!!g.launchConfirmResumeId):g.launchConfirm.confirmLabel,busyLabel:g.launchConfirm.providerType?void 0:g.launchConfirm.busyLabel,busy:g.launchConfirmBusy,showArgsInput:g.launchConfirm.showArgsInput,argsValue:g.launchConfirmArgs,onArgsChange:g.setLaunchConfirmArgs,showModelInput:g.launchConfirm.showModelInput,modelValue:g.launchConfirmModel,onModelChange:g.setLaunchConfirmModel,historyProviderNode:g.launchConfirm.providerType&&(g.launchConfirmSessionsLoading||g.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),g.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:_a()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:g.launchConfirmTextFilter,onChange:L=>g.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:g.launchConfirmWorkspaceFilter,onChange:L=>g.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:g.launchConfirmModelFilter,onChange:L=>g.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsxs("select",{value:g.launchConfirmSortMode,onChange:L=>g.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:g.launchConfirmResumableOnly,onChange:L=>g.setLaunchConfirmResumableOnly(L.target.checked),disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:g.launchConfirmResumeId,onChange:L=>g.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:kf()}),g.filteredLaunchConfirmSavedSessions.map(L=>s.jsxs("option",{value:L.providerSessionId,disabled:!L.canResume,children:[L.title||L.providerSessionId," ",L.canResume?"":"(workspace missing)"]},L.providerSessionId))]}),!g.launchConfirmSessionsLoading&&g.launchConfirmSavedSessions.length>0&&g.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),g.launchConfirmResumeId&&(()=>{const L=g.filteredLaunchConfirmSavedSessions.find(G=>G.providerSessionId===g.launchConfirmResumeId);if(!L)return null;const R=Zc(L);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:R.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:R.providerSessionId}),s.jsx("div",{className:"mt-1",children:R.metaLine}),R.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:R.updatedLabel}),R.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:R.preview})]})})()]}),onConfirm:g.handleConfirmLaunch,onCancel:g.closeLaunchConfirm}),u&&s.jsx(Qc,{section:f,onSectionChange:m})]})}function Dh(e){var r;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":"Offline"}function Eh(e,t){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:ds(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,d,f,u;const a=Qs(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)||(Qs(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:((u=(f=(d=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:d.at)==null?void 0:f.call(d,-1))==null?void 0:u.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function $h(e,t){const r=new Map;for(const n of t){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((x,m)=>m.timestamp-x.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Jn(n),d=a.filter(x=>x.unread||x.requiresAction).length,f=Dh(n),u=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:At(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?df(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 Bh(e){return e==="chat"}function kr(e,t){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function Kh({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:x,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,setSelectedTabKey:S,setScreen:p,setSelectedMachineId:h,setSection:j,setMachineBackTarget:b,resetMachineAction:N}){const T=o.useRef(null),y=o.useCallback(C=>{if(!(C!=null&&C.sessionId))return;const k=Or(C,c),w=Math.max(Date.now(),es(C),k.lastUpdated||0);kr("mark_read:start",{tabKey:C.tabKey,sessionId:C.sessionId,displayPrimary:rt(C),inboxBucket:k.inboxBucket,unread:k.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:es(C),readAt:w}),l(fs(C)||C.routeId,"mark_session_seen",{sessionId:C.sessionId,seenAt:w}).then(g=>{kr("mark_read:result",{tabKey:C.tabKey,sessionId:C.sessionId,result:g})}).catch(g=>{kr("mark_read:error",{tabKey:C.tabKey,sessionId:C.sessionId,error:g instanceof Error?g.message:String(g)})})},[c,l]);return o.useEffect(()=>{var k;if(!n){Bh(i)&&p("inbox"),S(((k=e[0])==null?void 0:k.tabKey)||null),T.current=null;return}if(i!=="chat"){T.current=null;return}const C=`${n.tabKey}:${n.sessionId||""}`;T.current!==C&&(T.current=C,y(n))},[e,y,i,n,p,S]),o.useEffect(()=>{if(!d)return;const C=e.find(k=>k.tabKey===d);C&&(S(C.tabKey),p("chat"),f==null||f())},[e,f,d,p,S]),o.useEffect(()=>{if(!u)return;const C=t.find(k=>k.id===u);C&&(h(C.id),N(),j("machines"),b("inbox"),p("machine"),x==null||x())},[t,x,u,N,b,p,j,h]),o.useEffect(()=>{m&&(j(m),p("inbox"),v==null||v())},[v,m,p,j]),o.useEffect(()=>{const C=r.filter(k=>k.inboxBucket==="task_complete"||k.unread);C.length!==0&&kr("inbox_state",{screen:i,selectedTabKey:a,items:C.map(k=>{const w=Or(k.conversation,c);return{liveState:w,tabKey:k.conversation.tabKey,sessionId:k.conversation.sessionId,displayPrimary:rt(k.conversation),serverBucket:w.inboxBucket,computedBucket:k.inboxBucket,serverUnread:w.unread,computedUnread:k.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:es(k.conversation)}})})},[r,c,i,a]),{markConversationRead:y}}function Oh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ti(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 Hh({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[d,f]=o.useState(null),u=o.useCallback(()=>{i("idle"),l(""),f(null)},[]),x=o.useCallback(async(b,N,T)=>{var y;try{i("loading"),l(`Launching ${N}…`);const C={ideType:N,enableCdp:!0};(y=T==null?void 0:T.workspacePath)!=null&&y.trim()&&(C.workspace=T.workspacePath.trim()),await e(b,"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(b,N,T)=>{if(N.trim())try{i("loading"),l(T!=null&&T.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(b,"workspace_add",{path:N.trim(),createIfMissing:(T==null?void 0:T.createIfMissing)===!0});if(y!=null&&y.success){i("done"),l(T!=null&&T.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]),v=o.useCallback(async b=>{var N,T,y,C,k,w;try{i("loading"),l("Starting daemon upgrade…");const g=await e(b,"daemon_upgrade",{});if((N=g==null?void 0:g.result)!=null&&N.alreadyLatest){i("done"),l(`Already on v${((T=g==null?void 0:g.result)==null?void 0:T.version)||"latest"}.`);return}if((y=g==null?void 0:g.result)!=null&&y.upgraded||(C=g==null?void 0:g.result)!=null&&C.success){i("done"),l(`Upgrade to v${((k=g==null?void 0:g.result)==null?void 0:k.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((w=g==null?void 0:g.result)==null?void 0:w.error)||"Upgrade failed")}catch(g){i("error"),l(g instanceof Error?g.message:"Upgrade failed")}},[e]),S=o.useCallback(async(b,N,T,y)=>{var w,g,D;const C=Date.now(),k={machineId:b,kind:N,providerType:T,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 ${T}…`),f(k);const A={cliType:T};(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),(g=y==null?void 0:y.args)!=null&&g.trim()&&(A.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(D=y==null?void 0:y.model)!=null&&D.trim()&&(A.initialModel=y.model.trim());const I=await e(b,"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(`${T} launched`),t(Gt(O));return}if(I!=null&&I.success){i("loading"),l(`${T} 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(`${T} launch requested — waiting for session…`);return}f(null),i("error"),l(A instanceof Error?A.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),p=o.useCallback(async(b,N)=>{try{const T=await e(b,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),y=(T==null?void 0:T.result)??T;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(T){return console.error("Failed to list saved sessions on mobile:",T),[]}},[e]),h=o.useCallback(async(b,N)=>rn(e,b,N),[e]);o.useEffect(()=>{if(!d)return;const b=ti(d.workspacePath),N=r.find(y=>{var A,I,P,O;if(!y||y.type==="adhdev-daemon"||Oh(y.daemonId||y.id)!==d.machineId||(y.transport==="acp"?"acp":y.transport==="pty"?"cli":null)!==d.kind||String(y.agentType||y.type||"")!==d.providerType)return!1;const g=String(y.providerSessionId||"");if(d.resumeSessionId&&g)return g===d.resumeSessionId;if(b){const V=ti(y.workspace||y.runtimeWorkspaceLabel);return V?V===b:!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)>=d.startedAt-5e3});if(!N)return;const T=ic({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});T&&(f(null),i("done"),l(`${d.providerType} launched`),t(Gt(T)))},[n,r,t,d]),o.useEffect(()=>{if(!d)return;const b=window.setTimeout(()=>{f(N=>!N||N.startedAt!==d.startedAt?N:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(b)},[d]);const j=o.useCallback(async(b,N)=>{if(N.kind==="ide"&&N.providerType){await x(b,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await S(b,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[x,S]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:x,handleAddWorkspace:m,handleMachineUpgrade:v,handleLaunchWorkspaceProvider:S,handleListSavedSessions:p,handleBrowseDirectory:h,handleOpenRecent:j}}function Fh({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:d,setMachineBackTarget:f}){const u=o.useCallback(j=>{i(j.tabKey),c("chat"),n(j)},[n,c,i]),x=o.useCallback(j=>{const b=e.find(N=>N.routeId===j.routeId&&N.streamSource==="native");b&&(i(b.tabKey),c("chat"),n(b))},[e,n,c,i]),m=o.useCallback(()=>{n(t),c("inbox")},[n,t,c]),v=o.useCallback((j,b="inbox")=>{l(j),a(),d("machines"),f(b),c("machine")},[a,f,c,d,l]),S=o.useCallback(j=>{const b=fs(j);b&&v(b,"chat")},[v]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),h=o.useCallback(j=>{d(j),c("inbox")},[c,d]);return{openConversation:u,openNativeConversation:x,backFromConversation:m,openMachine:v,openConversationMachine:S,backFromMachine:p,changeMachineSection:h}}function Uh(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Sr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function zh({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:x,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,onOpenHistory:S,onOpenRemote:p,onStopCli:h,wsStatus:j,isConnected:b,onShowHiddenConversation:N,onShowAllHiddenConversations:T,onHideConversation:y,onOpenNewSession:C,liveSessionInboxState:k,setCliViewModeOverrides:w}){const[g,D]=o.useState(()=>{var H;return((H=e[0])==null?void 0:H.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"),K=As(),E="0.9.25",W=o.useMemo(()=>e.find(H=>H.tabKey===g)||e[0]||null,[e,g]),J=o.useMemo(()=>W?r.find(H=>H.id===W.routeId):void 0,[r,W]),be=o.useMemo(()=>!W||Xe(W)||!Qe(W)?null:Ls(W),[W]),xe=o.useMemo(()=>r.filter(H=>H.type==="adhdev-daemon").sort(wa),[r]),de=o.useMemo(()=>xe.find(H=>H.id===V)||null,[xe,V]),ye=nn({sendDaemonCommand:a,activeConv:W||void 0,setActionLogs:i,isStandalone:c}),ge=Hh({sendDaemonCommand:a,navigate:K,ides:r,conversations:e}),ve=o.useMemo(()=>e.map(H=>{const ce=A==="chat"&&(W==null?void 0:W.tabKey)===H.tabKey,me=Qr(H,k,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ce}),je=es(H),_e=hc(H);return{conversation:H,timestamp:je,preview:_e,unread:me.unread,requiresAction:me.requiresAction,isWorking:me.isWorking,inboxBucket:me.inboxBucket}}),[e,k,A,W]),{markConversationRead:z}=Kh({conversations:e,machineEntries:xe,items:ve,selectedConversation:W,selectedTabKey:g,screen:A,liveSessionInboxState:k,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:x,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,setSelectedTabKey:D,setScreen:I,setSelectedMachineId:L,setSection:O,setMachineBackTarget:G,resetMachineAction:ge.resetMachineAction}),F=Fh({conversations:e,selectedConversation:W,machineBackTarget:R,markConversationRead:z,resetMachineAction:ge.resetMachineAction,setSelectedTabKey:D,setScreen:I,setSelectedMachineId:L,setSection:O,setMachineBackTarget:G}),Q=o.useMemo(()=>Sr(ve.filter(H=>H.requiresAction)),[ve]),ue=o.useMemo(()=>Sr(ve.filter(H=>H.unread&&!H.requiresAction)),[ve]),te=o.useMemo(()=>Sr(ve.filter(H=>!H.unread&&!H.requiresAction&&H.isWorking)),[ve]),fe=o.useMemo(()=>Sr(ve.filter(H=>!H.unread&&!H.requiresAction&&!H.isWorking)),[ve]),re=o.useMemo(()=>de?ve.filter(H=>fs(H.conversation)===de.id):[],[ve,de]),pe=o.useMemo(()=>Eh(de,r),[r,de]),oe=(de==null?void 0:de.version)||null,le=!!de&&!!oe&&!0&&oe!==E,ae=o.useMemo(()=>(de==null?void 0:de.availableProviders)||[],[de]),Y=o.useMemo(()=>ae.filter(H=>H.category==="cli"&&H.installed!==!1).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[ae]),X=o.useMemo(()=>ae.filter(H=>H.category==="acp"&&H.installed!==!1).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[ae]),ne=o.useMemo(()=>$h(xe,ve),[ve,xe]),M=o.useCallback(async H=>{de&&await ge.handleOpenRecent(de.id,H)},[ge,de]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:A==="chat"&&W?s.jsx(Ch,{selectedConversation:W,isAcp:Xe(W),isStandalone:c,selectedIdeEntry:J,actionLogs:n,userName:l,isSendingChat:ye.isSendingChat,sendFeedbackMessage:ye.sendFeedbackMessage,isFocusingAgent:ye.isFocusingAgent,handleModalButton:ye.handleModalButton,handleRelaunch:ye.handleRelaunch,onBack:F.backFromConversation,onOpenNativeConversation:F.openNativeConversation,onOpenMachine:F.openConversationMachine,onHideConversation:y,onOpenHistory:S,onOpenRemote:p,onStopCli:h,cliViewMode:be,onSetCliViewMode:async H=>{await Fc({conversation:W,mode:H,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:w})},handleSendChat:ye.handleSendChat,handleFocusAgent:ye.handleFocusAgent}):A==="machine"&&de?s.jsx(_h,{selectedMachineEntry:de,selectedMachineConversations:re,selectedMachineRecentLaunches:pe,cliProviders:Y,acpProviders:X,selectedMachineNeedsUpgrade:le,appVersion:E,machineAction:ge.machineAction,isStandalone:c,section:P,showBottomNav:R==="inbox",onBack:F.backFromMachine,onSectionChange:F.changeMachineSection,onOpenConversation:F.openConversation,onOpenRecent:M,onOpenMachineDetails:()=>K(`/machines/${de.id}`),onMachineUpgrade:()=>ge.handleMachineUpgrade(de.id),onLaunchDetectedIde:(H,ce)=>ge.handleLaunchDetectedIde(de.id,H,ce),onAddWorkspace:(H,ce)=>ge.handleAddWorkspace(de.id,H,ce),onBrowseDirectory:H=>ge.handleBrowseDirectory(de.id,H),onLaunchWorkspaceProvider:(H,ce,me)=>ge.handleLaunchWorkspaceProvider(de.id,H,ce,me),onListSavedSessions:H=>ge.handleListSavedSessions(de.id,H)}):s.jsx(Mh,{section:P,attentionItems:Q,unreadItems:ue,workingItems:te,completedItems:fe,hiddenConversations:t,machineCards:ne,getAvatarText:Uh,onOpenConversation:F.openConversation,onShowConversation:N,onShowAllHidden:T,onOpenNewSession:C,onOpenMachine:F.openMachine,onOpenSettings:()=>K("/settings"),onSectionChange:O,wsStatus:j,isConnected:b,isStandalone:c})})}function Tn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Vh({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,d]=o.useState(!1),[f,u]=o.useState(null),x=o.useCallback(()=>{c.current=0,d(!1),u(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",x),window.addEventListener("drop",x),()=>{window.removeEventListener("dragend",x),window.removeEventListener("drop",x)}),[x]);const m=o.useCallback(h=>{h.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,d(!0))},[]),v=o.useCallback(h=>{if(!h.dataTransfer.types.includes("text/tab-key"))return;if(h.preventDefault(),!Tn(t,r)){u("merge");return}const j=h.currentTarget.getBoundingClientRect(),b=h.clientX-j.left,N=j.width/3;b<N?u("split-left"):b>N*2?u("split-right"):u("merge")},[t,r]),S=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,d(!1),u(null))},[]),p=o.useCallback(h=>{c.current=0,d(!1);const j=h.dataTransfer.getData("text/tab-key"),b=j?e.some(T=>T.tabKey===j):!1,N=f;if(u(null),i(),!!j){if(h.preventDefault(),N==="split-left"&&Tn(t,r)){r==null||r(j,"split-left");return}if(N==="split-right"&&Tn(t,r)){r==null||r(j,"split-right");return}if(b){a(j);return}n==null||n(j)}},[e,f,t,r,n,a,i]);return{dragOver:l,dropAction:f,resetDragState:x,handleDragEnter:m,handleDragOver:v,handleDragLeave:S,handleDrop:p}}function Gh(e,t){const r=new Set(t.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=t.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function qh({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(t??null),[l,d]=o.useState(r??[]),[f,u]=o.useState(null),x=o.useRef(null),m=o.useRef(null),v=o.useRef(n),S=o.useRef(a);o.useEffect(()=>{v.current=n},[n]),o.useEffect(()=>{S.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{d(k=>{const w=Gh(k,e);return w.length===k.length&&w.every((g,D)=>g===k[D])?k:w})},[e]);const p=o.useMemo(()=>{const k=f??l;if(k.length===0)return e;const w=new Map(k.map((g,D)=>[g,D]));return[...e].sort((g,D)=>{const A=w.get(g.tabKey)??999,I=w.get(D.tabKey)??999;return A-I})},[e,f,l]);o.useEffect(()=>{var w,g;if(p.length===0){i!==null&&(c(null),(w=v.current)==null||w.call(v,null));return}if(i&&p.some(D=>D.tabKey===i))return;const k=p[0].tabKey;k!==i&&(c(k),(g=v.current)==null||g.call(v,k))},[p,i]);const h=o.useMemo(()=>p.find(k=>k.tabKey===i),[p,i]),j=o.useCallback(k=>{var w;c(k),(w=v.current)==null||w.call(v,k)},[]),b=o.useCallback((k,w,g)=>{d(D=>{var O;const A=D.filter(V=>V!==k),I=A.indexOf(w);if(I<0)return D;const P=g==="left"?I:I+1;return A.splice(P,0,k),(O=S.current)==null||O.call(S,A),A}),u(null)},[]),N=o.useCallback((k,w,g)=>{const A=(l.length>0?l:e.map(O=>O.tabKey)).filter(O=>O!==k),I=A.indexOf(w);if(I<0)return;const P=g==="left"?I:I+1;A.splice(P,0,k),x.current=A,u(A)},[l,e]),T=o.useCallback(()=>{var w;const k=x.current;k&&(d(k),(w=S.current)==null||w.call(S,k))},[]),y=o.useCallback(()=>{x.current=null,u(null)},[]),C=o.useCallback(k=>{d(w=>{var D;const g=w.filter(A=>A!==k);return g.push(k),(D=S.current)==null||D.call(S,g),g})},[]);return{activeTabId:i,activeConv:h,sortedConversations:p,previewOrderRef:x,draggingTabRef:m,selectTab:j,handleTabReorder:b,updatePreviewOrder:N,commitPreviewOrder:T,clearPreviewOrder:y,moveTabToEnd:C,setDraggingTabKey:k=>{m.current=k}}}function Yh({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),s.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function qa({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:i}){if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!r&&!n,l=n&&!!i,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",f=n?yc:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:f}),l&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:i,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:$t,"aria-label":$t,children:[s.jsx(Di,{size:14}),s.jsx("span",{children:$t})]})}),c&&s.jsx(Jc,{}),c&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const tl="adhdev-tab-shortcuts";function sl(){try{return JSON.parse(localStorage.getItem(tl)||"{}")}catch{return{}}}function rl({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>sl()),[l,d]=o.useState(null),f=o.useCallback(x=>{const m=[];return x.metaKey&&m.push(a?"⌘":"Meta"),x.ctrlKey&&m.push("Ctrl"),x.altKey&&m.push(a?"⌥":"Alt"),x.shiftKey&&m.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(m.push(x.key.length===1?x.key.toUpperCase():x.key),m.join("+"))},[a]),u=o.useCallback(x=>{c(x);try{localStorage.setItem(tl,JSON.stringify(x))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const x=m=>{if(m.preventDefault(),m.stopPropagation(),m.key==="Escape"){d(null);return}const v=f(m);if(!v)return;const S={...i};for(const[p,h]of Object.entries(S))h===v&&delete S[p];S[l]=v,u(S),d(null)};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[e,l,i,u,f]),o.useEffect(()=>{if(!e)return;const x=m=>{if(!(!m.ctrlKey&&!m.metaKey&&!m.altKey)){for(const[v,S]of Object.entries(i))if(t.includes(v)&&f(m)===S){m.preventDefault(),r(),n(v);return}}};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[e,i,t,r,n,f]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const Xh=o.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:d,onSelectTab:f,onConversationActivated:u,onPreviewReorder:x,onReorderTab:m,onCommitPreviewOrder:v,onClearPreviewOrder:S,onDragStateReset:p,onDragTabKeyChange:h,onReceiveTab:j,onOpenContextMenu:b,longPressTimer:N,isGroupActive:T}){const y=Ts(t),C=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",k=y.isReconnecting,w=o.useCallback(R=>{l.current=t.tabKey,h(t.tabKey),R.dataTransfer.setData("text/tab-key",t.tabKey),R.dataTransfer.effectAllowed="move"},[t.tabKey,l,h]),g=o.useCallback(()=>{l.current=null,h(null),v(),S(),p()},[l,h,v,S,p]),D=o.useCallback(R=>{const G=l.current;if(!(!G||G===t.tabKey)&&R.dataTransfer.types.includes("text/tab-key")){R.preventDefault(),R.stopPropagation();const K=R.currentTarget.getBoundingClientRect(),E=R.clientX<K.left+K.width/2?"left":"right";x(G,t.tabKey,E)}},[t.tabKey,l,x]),A=o.useCallback(R=>{R.preventDefault(),R.stopPropagation();const G=R.dataTransfer.getData("text/tab-key");if(G&&G!==t.tabKey){const K=R.currentTarget.getBoundingClientRect(),E=R.clientX<K.left+K.width/2?"left":"right";c.includes(G)?m(G,t.tabKey,E):j&&j(G)}S()},[t.tabKey,c,m,j,S]),I=o.useCallback(R=>{R.stopPropagation(),d(),f(t.tabKey),u(t)},[t,u,d,f]),P=o.useCallback(R=>{R.preventDefault(),b(R.clientX,R.clientY,t.tabKey)},[t.tabKey,b]),O=o.useCallback(R=>{const G=R.touches[0];N.current=setTimeout(()=>{b(G.clientX,G.clientY,t.tabKey)},600)},[t.tabKey,N,b]),V=o.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),L=["adhdev-dockview-tab",C,r&&"is-active",T&&"is-group-active",k&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:L,draggable:!0,onDragStart:w,onDragEnd:g,onDragOver:D,onDrop:A,onClick:I,onContextMenu:P,onTouchStart:O,onTouchEnd:V,onTouchMove:V,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?s.jsx("div",{className:"tab-spinner"}):y.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):k?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:rt(t),children:rt(t)}),s.jsx("span",{className:"adhdev-dockview-tab-meta",children:k?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(t)}):y.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ts(t),s.jsx("span",{className:"connecting-dots"})]}):ts(t)})]}),i&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function Jh({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:x,onDragStateReset:m,onDragTabKeyChange:v,onReceiveTab:S,onHideTab:p,isGroupActive:h,allowTabShortcuts:j=!0}){const[b,N]=o.useState(null),T=o.useRef(null),y=o.useRef(null),C=o.useMemo(()=>e.map(P=>P.tabKey),[e]);rr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:k,tabShortcuts:w,shortcutListening:g,setShortcutListening:D,saveShortcuts:A}=rl({enabled:j,sortedTabKeys:e.map(P=>P.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!b)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)},[b]),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 s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref: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=>s.jsx(Xh,{conv:P,isActive:t===P.tabKey,isDraggedTab:a.current===P.tabKey,isTaskCompleteUnread:n.has(P.tabKey),shortcut:j?w[P.tabKey]:void 0,conversationKeys:C,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:x,onDragStateReset:m,onDragTabKeyChange:v,onReceiveTab:S,onOpenContextMenu:I,longPressTimer:T,isGroupActive:h},P.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:b.x,top:b.y},children:[j&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:P=>{P.stopPropagation(),D(b.tabKey),N(null)},children:["⌨ ",w[b.tabKey]?`Change shortcut (${w[b.tabKey]})`:"Set shortcut"]}),w[b.tabKey]&&s.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const P={...w};delete P[b.tabKey],A(P),N(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[j&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{p(b.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),j&&g&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>D(null),children:s.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:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",k?"⌘+1":"Ctrl+1",", ",k?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Qh({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:d,groupIndex:f,onFocus:u,isSplitMode:x,numGroups:m,onMoveTab:v,onReceiveTab:S,style:p,onActiveTabChange:h,initialActiveTabId:j,initialTabOrder:b,onTabOrderChange:N,onHideTab:T,isFocused:y,allowTabShortcuts:C=!0,onOpenNewSession:k,liveSessionInboxState:w}){const{sendCommand:g}=wt(),D=o.useRef(null),{activeTabId:A,activeConv:I,sortedConversations:P,draggingTabRef:O,selectTab:V,handleTabReorder:L,updatePreviewOrder:R,commitPreviewOrder:G,clearPreviewOrder:K,moveTabToEnd:E,setDraggingTabKey:W}=qh({conversations:e,initialActiveTabId:j,initialTabOrder:b,onActiveTabChange:h,onTabOrderChange:N}),J=nn({sendDaemonCommand:a,activeConv:I,setActionLogs:i,isStandalone:c}),{dragOver:be,dropAction:xe,resetDragState:de,handleDragEnter:ye,handleDragOver:ge,handleDragLeave:ve,handleDrop:z}=Vh({conversations:e,numGroups:m,onMoveTab:v,onReceiveTab:S,onOwnTabDrop:E,onClearPreviewOrder:K}),F=I&&!Xe(I)&&Ls(I)==="terminal",Q=o.useMemo(()=>I?t.find(re=>re.id===I.routeId):void 0,[t,I]),ue=o.useMemo(()=>I?n.filter(re=>re.routeId===I.tabKey):[],[n,I]),te=o.useMemo(()=>new Set(P.filter(re=>wu(re,w,{isOpenConversation:re.tabKey===A})).map(re=>re.tabKey)),[A,w,P]);rr("PaneGroup",{groupIndex:f,conversationCount:e.length,activeTabId:A,dragOver:be});const fe=o.useCallback(re=>{re.streamSource==="agent-stream"&&re.agentType&&g(re.routeId,Xc(),{agentType:re.agentType,...re.sessionId&&{targetSessionId:re.sessionId}}).catch(()=>{})},[g]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...p,outline:be?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(Jh,{conversations:P,activeTabId:A,groupIndex:f,numGroups:m,unreadTabKeys:te,draggingTabRef:O,onFocus:u,onSelectTab:V,onConversationActivated:fe,onPreviewReorder:R,onReorderTab:L,onCommitPreviewOrder:G,onClearPreviewOrder:K,onDragStateReset:de,onDragTabKeyChange:W,onMoveTab:v,onReceiveTab:S,onHideTab:T,isGroupActive:y??!1,allowTabShortcuts:C}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ye,onDragOver:ge,onDragLeave:ve,onDrop:z,children:[be&&s.jsx(Yh,{dropAction:xe,canSplit:!!(m<4&&v)}),I?s.jsx(Va,{activeConv:I,clearToken:r[I.tabKey]||0,isCliTerminal:!!F,ideEntry:Q,terminalRef:D,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:ue,userName:d,isInputActive:!x||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(qa,{conversationsCount:e.length,isSplitMode:x,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:k})})]})]})}function Zh({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:f,isStandalone:u,hasRegisteredMachines:x,userName:m,focusedGroup:v,focusGroup:S,moveTabToGroup:p,splitTabRelative:h,closeGroup:j,handleResizeStart:b,groupActiveTabIds:N,setGroupActiveTab:T,groupTabOrders:y,setGroupTabOrder:C,toggleHiddenTab:k,onOpenNewSession:w,allowTabShortcuts:g=!0,liveSessionInboxState:D}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((A,I)=>{const P=t&&n.length===r?`${n[I]}%`:void 0;return s.jsxs(kt.Fragment,{children:[t&&I>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:O=>b(I-1,O),onDoubleClick:()=>j(I),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(Qh,{style:t?{flexBasis:P??`${100/r}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:A,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:f,isStandalone:u,hasRegisteredMachines:x,userName:m,groupIndex:I,isFocused:t&&v===I,onFocus:()=>S(I),isSplitMode:t,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?h(O,I,"left"):V==="split-right"&&r<4&&h(O,I,"right")},onReceiveTab:O=>p(O,I),onActiveTabChange:O=>T(I,O),initialActiveTabId:N[I],initialTabOrder:y[I],onTabOrderChange:O=>C(I,O),onHideTab:k,onOpenNewSession:w,allowTabShortcuts:g,liveSessionInboxState:D})]},I)})})}function nl({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?ot.onScreenshot("ide-page",(u,x)=>{if(u!==e)return;const m=new FileReader;m.onload=()=>i(m.result),m.readAsDataURL(x)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var u;return e?((u=ot.onStatus)==null?void 0:u.call(ot,(x,m)=>{x===e&&m!=null&&m.screenshotUsage&&l(m.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,t]),o.useEffect(()=>{const f=e?ot.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&t?f.startScreenshots(t):f.stopScreenshots(t),()=>{f.stopScreenshots(t)}},[n,r,t,e]);const d=o.useCallback(async(f,u)=>{const x=e?ot.get(e):null;return!x||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):x.sendInput(f,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:d}}const al="adhdev-dashboard-action-shortcuts",ex=1200,tx={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function sx(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function et(e,t){switch(e){case"openShortcutHelp":return"?";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return t?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return t?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return t?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return t?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return t?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return t?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return t?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return t?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return t?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return t?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function ol(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:et("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:et("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:et("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:et("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:et("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:et("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:et("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:et("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:et("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:et("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:et("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:et("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:et("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:et("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:et("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:et("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:et("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:et("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:et("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:et("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:et("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:et("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:et("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:et("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:et("toggleCliView",e)}]}function la(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Gr(e){const t=Object.fromEntries(ol(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(al)||"{}"),n={...t,...r};for(const[a,i]of Object.entries(tx))n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function il(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function rx({enabled:e=!0,onTrigger:t}){const r=sx(),[n,a]=o.useState(()=>Gr(r)),[i,c]=o.useState(null),[l,d]=o.useState([]),f=o.useRef({parts:[],timer:null}),u=o.useCallback(p=>{const h=[];return p.metaKey&&h.push(r?"⌘":"Meta"),p.ctrlKey&&h.push("Ctrl"),p.altKey&&h.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&h.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(h.push(il(p.key)),h.join("+"))},[r]),x=o.useCallback(p=>{a(p);try{localStorage.setItem(al,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=Gr(r),h=Object.entries(n),j=Object.entries(p);h.length===j.length&&h.every(([b,N])=>p[b]===N)||x(p)},[n,r,x]);const m=o.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),v=o.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},ex))},[]);o.useEffect(()=>{if(!i)return;const p=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){c(null),d([]);return}const j=u(h);if(!j)return;const N=!(h.metaKey||h.ctrlKey||h.altKey)&&/^[A-Z0-9]$/.test(j);if(l.length===0&&N){d([j]);return}const y=[...l,j].slice(0,2).join(" "),C={...n};for(const[k,w]of Object.entries(C))w===y&&delete C[k];C[i]=y,x(C),c(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,u,x,i,l]),o.useEffect(()=>{if(!e||i)return;const p=h=>{if(h.defaultPrevented)return;const j=u(h);if(!j)return;const b=h.metaKey||h.ctrlKey||h.altKey;if(la(h.target)&&!b)return;const N=f.current.parts,T=b?[j]:[...N.slice(-1),j].slice(-2),y=T.join(" "),C=T[T.length-1],k=Object.entries(n).filter(([,I])=>!!I),w=k.find(([,I])=>I===y);if(w){h.preventDefault(),m(),t(w[0]);return}if(k.some(([,I])=>I.startsWith(`${y} `))){h.preventDefault(),f.current.parts=T,v();return}const D=k.find(([,I])=>I===C);if(D){h.preventDefault(),m(),t(D[0]);return}if(k.some(([,I])=>I.startsWith(`${C} `))){h.preventDefault(),f.current.parts=[C],v();return}m()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,v,e,u,t,m,i]),o.useEffect(()=>()=>m(),[m]);const S=o.useMemo(()=>ol(r),[r]);return{isMac:r,actionDefinitions:S,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:x}}function nx({isTabInPopout:e,isTabFloating:t,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}function cl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function si({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!cl(n):!0}function ax({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:cl(r)}const ll=o.createContext(null);function on(){const e=o.useContext(ll);if(!e)throw new Error("DashboardDockviewContext missing");return e}function _r(e){return rt(e)||e.tabKey}function ox(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function ri(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Ln(e){var r,n,a,i,c;const t=e==null?void 0:e.defaultView;if(t)try{t.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=t.requestAnimationFrame)==null||c.call(t,()=>{var l,d;try{t.focus(),(d=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||d.call(l)}catch{}})}catch{}}function Nr(e,t){e.classList.remove(Un.className,zn.className),e.classList.add(t==="light"?Un.className:zn.className)}function ni(e){return e?Array.from(new Set(e.groups.map(t=>{var r,n;return(n=(r=t.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(t=>!!t&&t!==window))):[]}function ix(e){const[,t]=o.useState(0);o.useEffect(()=>{const r=()=>t(a=>a+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const a of n)a.dispose()}},[e.api,e.containerApi])}function cx(e,t,r){var c;const n=[t];let a;for(const l of n){let d;for(const f of l){const u=e.addPanel({id:f.tabKey,component:"conversation",title:_r(f),params:{kind:"conversation",tabKey:f.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return r??((c=t[0])==null?void 0:c.tabKey)??null}function ai(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])Lt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==_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 oi(e,t,r){var d,f;const n=r?ox(r):null;for(const u of[...e.panels])Lt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=_t(t,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=gc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((f=e.panels.find(u=>!Lt(u.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function lx({params:e,api:t}){var x;const r=on(),n=o.useRef(null),[a,i]=o.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=nn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(t.isActive);const m=[t.onDidActiveChange(v=>i(v.isActive)),t.onDidActiveGroupChange(v=>{if(!t.isActive&&!v.isActive){i(!1);return}i(t.isActive)})];return()=>{for(const v of m)v.dispose()}},[t]);const d=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 s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(qa,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const u=!Xe(c)&&Ls(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Va,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:u,ideEntry:d,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((x=r.scrollToBottomRequest)==null?void 0:x.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:a})})}function dx({params:e}){var d;const t=on(),r=o.useMemo(()=>_t([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>t.ides.find(f=>f.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=nl({doId:a,targetSessionId:r?rc(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Oi,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:l})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function ux(){const e=on();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(qa,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function mx(e){var v,S;ix(e);const t=on(),r=o.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=_t([...t.conversationsByTabKey.values()],e.params.routeId),h=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,j=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${h?" is-active":""}${j?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,i=e.api.isGroupActive,c=Qr(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,d=c.isConnecting,f=c.isGenerating,u=c.isWaiting,x=c.unread,m=t.tabShortcuts[n.tabKey];return s.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 h;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((h=p.target)==null?void 0:h.ownerDocument)??document})},children:[x&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?s.jsx("div",{className:"tab-spinner"}):u?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):d?s.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:rt(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ts(n)}):s.jsx("span",{children:ts(n)})})]}),m&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:m,children:m})]})}function fx({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:d,userName:f,toggleHiddenTab:u,actionShortcuts:x,registerActionHandlers:m,onActiveTabChange:v,onOpenNewSession:S,onRequestScrollToBottom:p,requestedActiveTabKey:h,requestedRemoteIdeId:j,onRequestedActiveTabConsumed:b,scrollToBottomRequest:N,liveSessionInboxState:T,layoutProfile:y}){var ft,Tt,yt;const{theme:C}=Ka(),{sendCommand:k}=wt(),w=o.useRef(null),g=o.useRef(null),D=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),[K,E]=o.useState(!1),[W,J]=o.useState(0),be=o.useRef(null),xe=o.useRef(typeof window>"u"?{}:Fp(y)),de=o.useMemo(()=>new Map(e.map(B=>[B.tabKey,B])),[e]),ye=o.useMemo(()=>{const B=w.current;return B?B.groups.some($=>{try{const U=$.model.location.type;return U!=="floating"&&U!=="popout"?!1:$.panels.some(q=>de.has(q.id))}catch{return!1}}):!1},[de,W,e]),ge=o.useCallback(()=>{var B;(B=w.current)==null||B.focus()},[]),ve=o.useCallback((B,$)=>{p==null||p(B,$)},[p]),z=o.useCallback(B=>{const $=document,U=B.document;for(const Ne of $.querySelectorAll('link[rel="stylesheet"]')){const se=U.createElement("link");se.rel="stylesheet",se.href=Ne.href,Ne.crossOrigin&&(se.crossOrigin=Ne.crossOrigin),U.head.appendChild(se)}for(const Ne of $.querySelectorAll("style")){const se=U.createElement("style");se.textContent=Ne.textContent,U.head.appendChild(se)}const q=[];for(const Ne of $.styleSheets)try{for(const se of Ne.cssRules)se instanceof CSSStyleRule&&(se.selectorText===":root"||se.selectorText==="html")&&q.push(se.cssText)}catch{}if(q.length>0){const Ne=U.createElement("style");Ne.textContent=q.join(`
|
|
43
|
+
`),U.head.appendChild(Ne)}const ie=$.documentElement.getAttribute("data-theme");ie&&U.documentElement.setAttribute("data-theme",ie),U.documentElement.style.colorScheme=ie==="light"?"light":"dark",U.body.className=$.body.className;const ke=$.documentElement.getAttribute("style");ke&&U.documentElement.setAttribute("style",ke);const Ie=U.getElementById("dv-popout-window");Ie instanceof HTMLElement&&(Ie.classList.add("adhdev-dockview"),Nr(Ie,C))},[C]),F=o.useCallback(()=>{var $;const B=w.current;if(B)for(const U of B.groups)try{const q=($=U.element)==null?void 0:$.ownerDocument;if(!q||q===document)continue;const ie=q.getElementById("dv-popout-window");ie instanceof HTMLElement&&(ie.classList.add("adhdev-dockview"),Nr(ie,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 Ie=document.documentElement.getAttribute("style");Ie?q.documentElement.setAttribute("style",Ie):q.documentElement.removeAttribute("style")}catch{}},[C]),Q=o.useCallback(()=>{var $;const B=w.current;if(B)for(const U of B.groups)try{const q=($=U.element)==null?void 0:$.ownerDocument;if(!q||q===document)continue;const ie=q.getElementById("dv-popout-window");if(!(ie instanceof HTMLElement))continue;ie.classList.add("adhdev-dockview"),Nr(ie,C),ie.classList.toggle("is-showing-dockview-overlay",K),ie.classList.toggle("is-dragging-dockview",R)}catch{}},[R,K,C]),ue=o.useCallback(B=>{const $=w.current;if(!$)return;const U=$.getPanel(B);U&&$.addPopoutGroup(U,{popoutUrl:"/popout.html",onDidOpen:({window:q})=>{z(q),X();const ie=de.get(B);q.document.title=ie?`${rt(ie)} — ADHDev`:"ADHDev — Popout"}})},[de,z]),te=o.useCallback(B=>{const $=w.current,U=$==null?void 0:$.getPanel(B);if(!$||!U)return;const q=$.groups.filter(ie=>{var ke;try{return((ke=ie.element)==null?void 0:ke.ownerDocument)===document}catch{return!0}});q.length>0?U.api.moveTo({group:q[0],position:"center"}):U.api.moveTo({position:"center"}),U.api.setActive()},[]),fe=o.useCallback(B=>{var q;const $=w.current;if(!$)return!1;const U=$.getPanel(B);if(!U)return!1;try{return((q=U.group.element)==null?void 0:q.ownerDocument)!==document}catch{return!1}},[]),re=o.useCallback(B=>{fe(B)&&te(B),u(B)},[fe,te,u]),pe=o.useCallback(B=>{const $=w.current,U=$==null?void 0:$.getPanel(B);!$||!U||$.addFloatingGroup(U,{width:600,height:500})},[]),oe=o.useCallback(B=>{var U;const $=(U=w.current)==null?void 0:U.getPanel(B);if(!$)return!1;try{return $.group.model.location.type==="floating"}catch{return!1}},[]),le=o.useCallback(()=>{var $,U;const B=(U=($=w.current)==null?void 0:$.activePanel)==null?void 0:U.id;return!B||Lt(B)?null:de.has(B)?B:null},[de]),ae=o.useCallback(B=>{const $=w.current,U=$==null?void 0:$.getPanel(B);if(!$||!U)return;const q=$.groups.filter(ie=>{try{return ie.model.location.type==="grid"}catch{return!0}});q.length>0?U.api.moveTo({group:q[0],position:"center"}):U.api.moveTo({position:"center"}),U.api.setActive()},[]),Y=o.useCallback(()=>{var ke;const B=w.current;if(!B)return;const U=B.groups.filter(Ie=>{var Ne;try{return((Ne=Ie.element)==null?void 0:Ne.ownerDocument)===document&&Ie.model.location.type==="grid"}catch{return!1}})[0]||null,q=[...B.panels];for(const Ie of q){const Ne=(ke=Ie.group.element)==null?void 0:ke.ownerDocument,se=Ie.group.model.location.type;Ne===document&&se==="grid"||(U&&U.id!==Ie.group.id?Ie.api.moveTo({group:U,position:"center"}):Ie.api.moveTo({position:"center"}))}const ie=B.activePanel;ie&&(ie.group.model.openPanel(ie),ie.api.setActive()),Ln(document)},[]),X=o.useCallback(()=>{var $,U;const B=w.current;if(B)for(const q of B.groups){const ie=($=q.element)==null?void 0:$.ownerDocument;if(!ie||ie===document)continue;const ke=ie.getElementById("dv-popout-window");if(!(ke instanceof HTMLElement))continue;let Ie=null,Ne=ie.title||"ADHDev",se="Popout workspace";const we=q.activePanel;if(we)if(Ie=we.id,Lt(we.id)){const Pe=((U=we.params)==null?void 0:U.routeId)||we.id.slice(7),_=_t([...de.values()],Pe);Ne=gc(_),se=_!=null&&_.machineName?`Remote view · ${_.machineName}`:"Remote view"}else{const Pe=de.get(we.id);Ne=Pe?rt(Pe):we.title||we.id,se=Pe?ts(Pe):"Dockview panel"}ie.title=`${Ne} — ADHDev`;const Ke=Array.from(ie.querySelectorAll("#adhdev-popout-header"));for(const Pe of Ke)Pe.remove();const He=ie.createElement("div");He.id="adhdev-popout-header",ie.body.appendChild(He),He.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(";")),He.innerHTML=`
|
|
44
44
|
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
45
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;">${
|
|
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;">${
|
|
46
|
+
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${ri(Ne)}</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;">${ri(se)}</div>
|
|
48
48
|
</div>
|
|
49
49
|
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
50
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
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
52
|
</div>
|
|
53
|
-
`,Se.style.top="52px",Se.style.height="calc(100% - 52px)";const Ye=Ue.querySelector("[data-adhdev-popout-focus]");Ye&&(Ye.onclick=()=>{window.focus()});const Ve=Ue.querySelector("[data-adhdev-popout-dock]");Ve&&(Ve.disabled=!Ie,Ve.style.opacity=Ie?"1":"0.5",Ve.style.cursor=Ie?"pointer":"default",Ve.onclick=()=>{var Pe;Ie&&te(Ie),(Pe=ie.defaultView)==null||Pe.focus()})}},[de,te]),ae=o.useCallback($=>{var q;const O=v.current,U=O==null?void 0:O.getPanel($);if(!(!O||!U)){U.group.model.openPanel(U),U.api.setActive(),ve($,"dockview-shortcut");try{const ie=U.group.model.location;ie.type==="popout"?ie.getWindow().focus():Ln((q=U.group.element)==null?void 0:q.ownerDocument)}catch{}}},[ve]),A=o.useCallback($=>{const O=v.current,U=O==null?void 0:O.activePanel,q=(O==null?void 0:O.activeGroup)||(U==null?void 0:U.group);if(!O||!U||!q)return;const ie=q.panels||[];if(ie.length<=1)return;const Se=ie.findIndex(se=>se.id===U.id);if(Se<0)return;const Ie=(Se+$+ie.length)%ie.length,Ce=ie[Ie];Ce&&(Ce.group.model.openPanel(Ce),Ce.api.setActive(),Lt(Ce.id)||ve(Ce.id,"dockview-shortcut"))},[ve]),H=o.useCallback($=>{var Ye;const O=v.current,U=(O==null?void 0:O.activeGroup)||((Ye=O==null?void 0:O.activePanel)==null?void 0:Ye.group);if(!O||!U)return;const q=O.groups||[],ie=q.find(Ve=>Ve.id===U.id);if(!ie)return;const Se=ie.element.getBoundingClientRect(),Ie=Se.left+Se.width/2,Ce=Se.top+Se.height/2,se=(Ve,Pe,_,ee)=>Math.max(0,Math.min(Pe,ee)-Math.max(Ve,_)),ke=Ve=>{const Pe=Ve.element.getBoundingClientRect(),_=Pe.left+Pe.width/2,ee=Pe.top+Pe.height/2;let pe=0,Re=0,Ne=0,Me=!1;if($==="left"?(Me=_<Ie,pe=Math.max(0,Se.left-Pe.right),Re=Math.abs(ee-Ce),Ne=se(Se.top,Se.bottom,Pe.top,Pe.bottom)):$==="right"?(Me=_>Ie,pe=Math.max(0,Pe.left-Se.right),Re=Math.abs(ee-Ce),Ne=se(Se.top,Se.bottom,Pe.top,Pe.bottom)):$==="above"?(Me=ee<Ce,pe=Math.max(0,Se.top-Pe.bottom),Re=Math.abs(_-Ie),Ne=se(Se.left,Se.right,Pe.left,Pe.right)):(Me=ee>Ce,pe=Math.max(0,Pe.top-Se.bottom),Re=Math.abs(_-Ie),Ne=se(Se.left,Se.right,Pe.left,Pe.right)),!Me)return Number.POSITIVE_INFINITY;const Te=Ne>0?0:120;return pe*3+Re+Te};let Oe=null,Ue=Number.POSITIVE_INFINITY;for(const Ve of q){if(Ve.id===ie.id)continue;const Pe=ke(Ve);Number.isFinite(Pe)&&(Pe>=Ue||(Ue=Pe,Oe=Ve))}return Oe||void 0},[]),ce=o.useCallback($=>{var q;const O=H($);if(!O)return;const U=O.activePanel||O.panels[0];U&&(O.model.openPanel(U),U.api.setActive(),Lt(U.id)||ve(U.id,"dockview-focus"),Ln((q=O.element)==null?void 0:q.ownerDocument))},[H,ve]),me=o.useCallback(($,O)=>{const U=v.current,q=U==null?void 0:U.activePanel,ie=(U==null?void 0:U.activeGroup)||(q==null?void 0:q.group);if(!U||!q||!ie)return;let Se=H($);!Se&&(O!=null&&O.createGroupIfMissing)&&(Se=U.addGroup({referenceGroup:ie,direction:$})),Se&&(q.api.moveTo({group:Se,position:"center"}),q.group.model.openPanel(q),q.api.setActive(),Lt(q.id)||ve(q.id,O!=null&&O.createGroupIfMissing?"dockview-split":"dockview-move"))},[H,ve]),{isMac:we,tabShortcuts:_e,shortcutListening:Ae,setShortcutListening:Ke,saveShortcuts:Fe}=Zc({sortedTabKeys:e.map($=>$.tabKey),onFocus:ge,onSelectTab:ae}),ze=o.useCallback(()=>{var U;const $=v.current;if(!$)return;const O=$.activePanel;if(O){if(Lt(O.id)){const q=((U=O.params)==null?void 0:U.routeId)||O.id.slice(7),ie=_t(e,q);ie!=null&&ie.tabKey&&Ke(ie.tabKey);return}de.has(O.id)&&Ke(O.id)}},[de,ae,Ke,e]),ot=o.useCallback($=>{const O=[];return $.metaKey&&O.push(we?"⌘":"Meta"),$.ctrlKey&&O.push("Ctrl"),$.altKey&&O.push(we?"⌥":"Alt"),$.shiftKey&&$.key.length!==1&&O.push(we?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes($.key)?null:(O.push(rl($.key)),O.join("+"))},[we]),it=o.useCallback($=>{var O,U;switch($){case"splitActiveTabRight":me("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":me("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const q=le();q&&xe(q);return}case"popoutActiveTab":{const q=le();q&&ue(q);return}case"dockActiveTab":{const q=le();if(!q)return;fe(q)?te(q):re(q)&&oe(q);return}case"focusLeftPane":ce("left");return;case"focusRightPane":ce("right");return;case"focusUpPane":ce("above");return;case"focusDownPane":ce("below");return;case"moveActiveTabToLeftPane":me("left");return;case"moveActiveTabToRightPane":me("right");return;case"moveActiveTabToUpPane":me("above");return;case"moveActiveTabToDownPane":me("below");return;case"selectPreviousGroupTab":A(-1);return;case"selectNextGroupTab":A(1);return;case"setActiveTabShortcut":ze();return;case"hideCurrentTab":{const q=(U=(O=v.current)==null?void 0:O.activePanel)==null?void 0:U.id;q&&!Lt(q)&&ne(q);return}default:return}},[A,oe,ce,xe,le,ne,re,fe,te,me,ue,ze]);o.useEffect(()=>{if(!V)return;const $=V.sourceDocument,O=$.defaultView??window,U=q=>{const ie=$.querySelector("[data-dockview-tab-context-menu]");ie&&ie.contains(q.target)||L(null)};return O.addEventListener("mousedown",U,!0),O!==window&&window.addEventListener("mousedown",()=>L(null),!0),()=>{O.removeEventListener("mousedown",U,!0),O!==window&&window.removeEventListener("mousedown",()=>L(null),!0)}},[V]);const dt=o.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:de,hasDetachedConversationPanels:ye,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:S,liveSessionInboxState:T,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:ne,userName:f,scrollToBottomRequest:N,tabShortcuts:_e,openTabContextMenu:({x:$,y:O,tabKey:U,sourceDocument:q})=>L({x:$,y:O,tabKey:U,sourceDocument:q??document}),popoutTab:ue,moveTabBackToMain:te,isTabInPopout:fe,floatTab:xe,isTabFloating:re}),[n,t,de,ye,r,c,l,S,T,a,i,ne,f,N,_e,ue,te,fe,xe,re]),ut=V?Gh({isTabInPopout:fe(V.tabKey),isTabFloating:re(V.tabKey),tabShortcut:_e[V.tabKey],actionShortcuts:h}):[],mt=o.useCallback($=>{var q;const O=v.current;if((((q=O==null?void 0:O.activePanel)==null?void 0:q.id)??null)===$.id){$.group.model.openPanel($);return}$.group.model.openPanel($),$.api.setActive()},[]),Xe=o.useCallback(($,O="requested-tab")=>{if(!$)return!1;const U=v.current;if(!U)return!1;const q=U.getPanel($);return q?(mt(q),ve($,O),b==null||b(),!0):!1},[mt,b,ve]),rt=o.useCallback(()=>{if(I.current)return!1;const $=Xe(P.current,"stored-layout-restore");return $&&(I.current=!0),$},[Xe]),je=o.useCallback(()=>{var O;const $=v.current;$&&Lp(y,{activeTabId:((O=$.activePanel)==null?void 0:O.id)??null,layout:$.toJSON()})},[y]),Ee=o.useCallback(()=>{Pp(y,he.current)},[y]),Be=o.useCallback($=>{var q,ie,Se,Ie;const O=v.current;if(!O)return{kind:"grid"};const U=O.toJSON();for(const Ce of U.floatingGroups||[])if((ie=(q=Ce.data)==null?void 0:q.views)!=null&&ie.includes($)&&Ce.position)return{kind:"floating",position:Ce.position};for(const Ce of U.popoutGroups||[])if((Ie=(Se=Ce.data)==null?void 0:Se.views)!=null&&Ie.includes($))return{kind:"popout",position:Ce.position,popoutUrl:Ce.url};return{kind:"grid"}},[]),nt=o.useCallback($=>{const O=v.current;if(!O)return;const U=O.getPanel($),q=he.current[$];if(!U||!q||q.kind==="grid")return;if(U.group.model.location.type===q.kind){delete he.current[$],Ee();return}if(q.kind==="floating"){O.addFloatingGroup(U,{x:q.position.left??24,y:q.position.top??24,width:q.position.width,height:q.position.height}),delete he.current[$],Ee();return}delete he.current[$],Ee()},[Ee]);o.useEffect(()=>(m==null||m({setShortcutForActiveTab:ze,restoreHiddenTabToSavedLocation:nt,activateConversationTab:ae,resetAllPanelsToMain:Y,activatePreviousTabInGroup:()=>A(-1),activateNextTabInGroup:()=>A(1),floatActiveTab:()=>{const $=le();$&&xe($)},popoutActiveTab:()=>{const $=le();$&&ue($)},dockActiveTab:()=>{const $=le();$&&(fe($)?te($):re($)&&oe($))},splitActiveTabRight:()=>me("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>me("below",{createGroupIfMissing:!0}),focusLeftPane:()=>ce("left"),focusRightPane:()=>ce("right"),focusUpPane:()=>ce("above"),focusDownPane:()=>ce("below"),moveActiveTabToLeftPane:()=>me("left"),moveActiveTabToRightPane:()=>me("right"),moveActiveTabToUpPane:()=>me("above"),moveActiveTabToDownPane:()=>me("below")}),()=>m==null?void 0:m(null)),[A,oe,xe,ce,le,re,fe,me,te,ue,m,Y,nt,ae,ze]);const st=o.useCallback(()=>{const $=g.current;if(!$)return;const O=$.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const U of O)U.setAttribute("data-adhdev-force-hidden","true")},[]),yt=o.useCallback(()=>{const $=g.current;if(!$)return;const O=$.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const U of O)U.removeAttribute("data-adhdev-force-hidden")},[]),Z=o.useCallback(()=>{const $=g.current;if(!$)return;const O=$.querySelectorAll(".dv-drop-target-container");for(const ie of O)ie.remove();const U=$.querySelectorAll(".dv-drop-target-dropzone");for(const ie of U)ie.remove();const q=$.querySelectorAll(".dv-drop-target");for(const ie of q)ie.classList.remove("dv-drop-target")},[]),Le=o.useCallback(()=>{G(!1),E(!1),yt(),st(),Z(),!(typeof window>"u")&&(be.current!=null&&window.clearTimeout(be.current),window.requestAnimationFrame(()=>{st(),Z()}),be.current=window.setTimeout(()=>{st(),Z(),be.current=null},80))},[yt,st,Z]),De=o.useCallback($=>{var U;v.current=$.api;const O=Tp(y);if(P.current=(O==null?void 0:O.activeTabId)??null,O!=null&&O.layout&&$.api.fromJSON(O.layout,{reuseExistingPanels:!1}),M.current=Jo({hasStoredLayout:!!(O!=null&&O.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:r}),M.current||(ei($.api,e),ti($.api,e,j)),$.api.totalPanels===0&&e.length>0){const q=Jh($.api,e,x);if(q){const ie=$.api.getPanel(q);ie&&mt(ie)}}else!M.current&&!Xe(x)&&rt();D.current=!0,$.api.onDidActivePanelChange(q=>{var Se;if(P.current=(q==null?void 0:q.id)??null,I.current=!0,X(),q&&Lt(q.id)){const Ie=((Se=q.params)==null?void 0:Se.routeId)||q.id.slice(7),Ce=_t(e,Ie);w((Ce==null?void 0:Ce.tabKey)??null),je();return}if(w((q==null?void 0:q.id)??null),je(),!q)return;const ie=de.get(q.id);(ie==null?void 0:ie.streamSource)==="agent-stream"&&ie.agentType&&k(ie.routeId,Vc(),{agentType:ie.agentType,...ie.sessionId&&{targetSessionId:ie.sessionId}}).catch(()=>{})}),$.api.onDidLayoutChange(()=>{je(),X(),J(q=>q+1)}),$.api.onWillDragPanel(()=>{G(!0),E(!1),st()}),$.api.onWillDragGroup(()=>{G(!0),E(!1),st()}),$.api.onWillShowOverlay(()=>{yt(),E(!0)}),$.api.onDidMovePanel(Le),$.api.onDidDrop(Le),$.api.onDidAddGroup(q=>{requestAnimationFrame(()=>{var ie,Se;try{const Ie=(ie=q.element)==null?void 0:ie.ownerDocument;if(!Ie||Ie===document)return;(Se=Ie.getElementById("dv-popout-window"))==null||Se.classList.add("adhdev-dockview");const Ce=document.documentElement.getAttribute("data-theme");Ce&&Ie.documentElement.setAttribute("data-theme",Ce),Ie.body.className=document.body.className;const se=document.documentElement.getAttribute("style");se&&Ie.documentElement.setAttribute("style",se)}catch{}X(),J(Ie=>Ie+1)})}),w(((U=$.api.activePanel)==null?void 0:U.id)??null)},[mt,Xe,Le,yt,de,r,u,y,st,w,je,x,j,k,X,e]);o.useLayoutEffect(()=>{const $=v.current;if(!$||!D.current||M.current&&Jo({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:r}))return;M.current&&(M.current=!1);const O=K.current,U=new Set(O),q=e.map(Oe=>Oe.tabKey),ie=new Set(q),Se=qh({previousVisibleConversationCount:O.length,visibleConversationCount:e.length,ides:r});let Ie=!1;for(const Oe of O)ie.has(Oe)||Se||(he.current[Oe]=Be(Oe),Ie=!0);Ie&&Ee(),Se||(ei($,e),ti($,e,j));const Ce=q.filter(Oe=>!U.has(Oe));let se=!1;for(const Oe of Ce){const Ue=$.getPanel(Oe),Ye=he.current[Oe];if(!Ue||!Ye||Ye.kind==="grid")continue;if(Ue.group.model.location.type===Ye.kind){delete he.current[Oe],se=!0;continue}if(Ye.kind==="floating"){$.addFloatingGroup(Ue,{x:Ye.position.left??24,y:Ye.position.top??24,width:Ye.position.width,height:Ye.position.height}),delete he.current[Oe],se=!0;continue}}if(se&&Ee(),K.current=q,x&&Xe(x))return;!$.activePanel&&$.panels[0]&&mt($.panels[0]),!!($.activePanel&&$.getPanel($.activePanel.id))||rt()},[mt,Xe,rt,r,u,Ee,Be,x,j,e]),o.useEffect(()=>{D.current&&Xe(x)},[Xe,x]),o.useEffect(()=>{if(!R||typeof window>"u")return;const $=()=>Le();return window.addEventListener("pointerup",$),window.addEventListener("mouseup",$),window.addEventListener("dragend",$),()=>{window.removeEventListener("pointerup",$),window.removeEventListener("mouseup",$),window.removeEventListener("dragend",$)}},[Le,R]),o.useEffect(()=>()=>{typeof window>"u"||be.current!=null&&window.clearTimeout(be.current)},[]),o.useEffect(()=>{const $=U=>{const q=U.target;if(!q)return;const ie=q.querySelector("[data-tab-key]")||q.closest("[data-tab-key]");if(ie){const Se=ie.getAttribute("data-tab-key");if(Se&&U.dataTransfer){const Ie=q.closest(".dv-tab")||ie.closest(".dv-tab")||ie;U.dataTransfer.effectAllowed="move",U.dataTransfer.setData("text/tab-key",Se),Ie instanceof HTMLElement&&U.dataTransfer.setDragImage(Ie,Math.max(12,Math.round(Ie.clientWidth/2)),Math.max(10,Math.round(Ie.clientHeight/2)))}}};window.addEventListener("dragstart",$);const O=Zo(v.current);for(const U of O)U.addEventListener("dragstart",$);return()=>{window.removeEventListener("dragstart",$);for(const U of O)U.removeEventListener("dragstart",$)}},[W]),o.useEffect(()=>{var O;const $=(O=g.current)==null?void 0:O.querySelector(".adhdev-dockview");$ instanceof HTMLElement&&Nr($,C),F(),X(),Q()},[X,Q,F,C]),o.useEffect(()=>{X(),Q()},[X,Q]),o.useEffect(()=>{const $=O=>{if(O.defaultPrevented||Ae)return;const U=ot(O);if(!U)return;const q=O.metaKey||O.ctrlKey||O.altKey;la(O.target)&&!q||Gr(we).setActiveTabShortcut!==U||(O.preventDefault(),O.stopPropagation(),ze())};return window.addEventListener("keydown",$,!0),()=>window.removeEventListener("keydown",$,!0)},[ot,we,Ae,ze]),o.useEffect(()=>{const $=g.current;if(!$)return;const O=U=>{var Ce,se;if(!U.isTrusted)return;const q=(se=(Ce=U.target)==null?void 0:Ce.closest)==null?void 0:se.call(Ce,".dv-scrollable");if(!q)return;U.preventDefault(),U.stopPropagation();const ie=Math.abs(U.deltaX),Se=Math.abs(U.deltaY),Ie=ie>Se?U.deltaX:U.deltaY;q.dispatchEvent(new WheelEvent("wheel",{deltaY:Ie,deltaMode:U.deltaMode,bubbles:!1,cancelable:!0}))};return $.addEventListener("wheel",O,{passive:!1,capture:!0}),()=>$.removeEventListener("wheel",O,{capture:!0})},[]),o.useEffect(()=>{const $=Zo(v.current);if($.length===0)return;const O=$.map(U=>{let q=[],ie=null;const Se=()=>{ie!=null&&U.clearTimeout(ie),ie=null,q=[]},Ie=()=>{ie!=null&&U.clearTimeout(ie),ie=U.setTimeout(()=>{ie=null,q=[]},1200)},Ce=ke=>{if(!ke.ctrlKey&&!ke.metaKey&&!ke.altKey)return;const Oe=ot(ke);if(!Oe)return;const Ue=Qc();for(const[Ye,Ve]of Object.entries(Ue))if(e.some(Pe=>Pe.tabKey===Ye)&&Ve===Oe){ke.preventDefault(),ae(Ye);return}},se=ke=>{if(ke.defaultPrevented||Ae)return;const Oe=ot(ke);if(!Oe)return;const Ue=ke.metaKey||ke.ctrlKey||ke.altKey;if(la(ke.target)&&!Ue)return;const Ye=Gr(we),Ve=Object.entries(Ye).filter(([Te,pt])=>!!pt&&(Te==="splitActiveTabRight"||Te==="splitActiveTabDown"||Te==="floatActiveTab"||Te==="popoutActiveTab"||Te==="dockActiveTab"||Te==="focusLeftPane"||Te==="focusRightPane"||Te==="focusUpPane"||Te==="focusDownPane"||Te==="moveActiveTabToLeftPane"||Te==="moveActiveTabToRightPane"||Te==="moveActiveTabToUpPane"||Te==="moveActiveTabToDownPane"||Te==="selectPreviousGroupTab"||Te==="selectNextGroupTab"||Te==="setActiveTabShortcut"||Te==="hideCurrentTab")),Pe=Ue?[Oe]:[...q.slice(-1),Oe].slice(-2),_=Pe.join(" "),ee=Pe[Pe.length-1],pe=Ve.find(([,Te])=>Te===_);if(pe){ke.preventDefault(),Se(),it(pe[0]);return}if(Ve.some(([,Te])=>Te.startsWith(`${_} `))){ke.preventDefault(),q=Pe,Ie();return}const Ne=Ve.find(([,Te])=>Te===ee);if(Ne){ke.preventDefault(),Se(),it(Ne[0]);return}if(Ve.some(([,Te])=>Te.startsWith(`${ee} `))){ke.preventDefault(),q=[ee],Ie();return}Se()};return U.addEventListener("keydown",Ce),U.addEventListener("keydown",se),()=>{Se(),U.removeEventListener("keydown",Ce),U.removeEventListener("keydown",se)}});return()=>{for(const U of O)U()}},[ot,we,W,ae,Ae,it,e]);const et=C==="light"?Un:zn,Tt=((vt=(He=(ft=v.current)==null?void 0:ft.activePanel)==null?void 0:He.group.element)==null?void 0:vt.ownerDocument)??document;return s.jsxs(al.Provider,{value:dt,children:[s.jsx("div",{ref:g,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Jl,{className:`h-full min-h-0 min-w-0 adhdev-dockview${R?" is-dragging-dockview":""}${B?" is-showing-dockview-overlay":""}`,components:{conversation:Qh,remote:Zh},defaultTabComponent:tx,watermarkComponent:ex,onReady:De,singleTabMode:"default",tabAnimation:"smooth",theme:et,popoutUrl:"/popout.html"})}),V&&zs.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:V.x,top:V.y},children:ut.map($=>{if($.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},$.id);let O=s.jsx(zd,{size:13,className:"shrink-0 opacity-70"}),U=()=>{};switch($.id){case"dockInWindow":case"dockBackToGrid":O=s.jsx(Gd,{size:13,className:"shrink-0 opacity-70"}),U=()=>{oe(V.tabKey),L(null)};break;case"moveBackToMain":O=s.jsx(Ud,{size:13,className:"shrink-0 opacity-70"}),U=()=>{te(V.tabKey),L(null)};break;case"floatAsPanel":O=s.jsx(Vd,{size:13,className:"shrink-0 opacity-70"}),U=()=>{xe(V.tabKey),L(null)};break;case"openInNewWindow":O=s.jsx(Fd,{size:13,className:"shrink-0 opacity-70"}),U=()=>{ue(V.tabKey),L(null)};break;case"setShortcut":U=q=>{q.stopPropagation(),Ke(V.tabKey),L(null)};break;case"removeShortcut":O=s.jsx(wt,{size:13,className:"shrink-0 opacity-70"}),U=()=>{const q={..._e};delete q[V.tabKey],Fe(q),L(null)};break;case"hideTab":O=s.jsx(Ai,{size:13,className:"shrink-0 opacity-70"}),U=()=>{ne(V.tabKey),L(null)};break}return s.jsxs("button",{className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${$.tone==="muted"?"text-text-muted":""}`,onClick:U,children:[O,s.jsx("span",{className:"flex-1 min-w-0",children:$.label}),$.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:$.shortcut}):null]},$.id)})}),V.sourceDocument.body),Ae&&zs.createPortal(s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>Ke(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:$=>$.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",we?"⌘+1":"Ctrl+1",", ",we?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),Tt.body)]})}const ol="adhdev-recent-launch-args-v1",rx=8;function nx(e){return String(e||"").trim().replace(/\s+/g," ")}function il(e,t){return`${e.trim()}::${t.trim()}`}function cl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(ol)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function ax(e){if(!(typeof window>"u"))try{window.localStorage.setItem(ol,JSON.stringify(e))}catch{}}function ll(e,t){var i;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((i=cl().byKey[il(r,n)])==null?void 0:i.items)||[]}function dl(e,t,r){var d;const n=String(e||"").trim(),a=String(t||"").trim(),i=nx(r);if(!n||!a||!i)return;const c=cl(),l=il(n,a),u=((d=c.byKey[l])==null?void 0:d.items)||[],f=[i,...u.filter(h=>h!==i)].slice(0,rx);c.byKey[l]={items:f},ax(c)}function ul(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Dr({title:e,description:t,action:r,children:n,className:a="",contentClassName:i=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),r?s.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?s.jsx("div",{className:t||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function ml({busy:e,savedSessionsLoading:t,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?Yc(n):null;return s.jsxs(Dr,{title:"Saved history",description:Ra(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:a,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:i,children:pf()})]}),children:[l?s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:l.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:l.providerSessionId}),s.jsx("div",{className:"mt-1",children:l.metaLine}),l.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:l.updatedLabel}),l.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:l.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:c,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted",children:"Start fresh, or open saved history when you want continuity."}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function Rn(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>a.category==="cli"&&a.installed!==!1)?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>a.category==="acp"&&a.installed!==!1)?"acp":null}function Cr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ox({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:c,onListSavedSessions:l}){var st,yt;const u=nr(),f=o.useMemo(()=>[...e].sort(wa),[e]),[d,h]=o.useState(((st=f[0])==null?void 0:st.id)||""),m=o.useMemo(()=>f.find(Z=>Z.id===d)||f[0],[d,f]),w=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(""),[j,b]=o.useState(""),[N,T]=o.useState(Rn(f[0])),[y,C]=o.useState(""),[k,v]=o.useState(""),[g,D]=o.useState([]),[M,I]=o.useState(""),[P,K]=o.useState([]),[V,L]=o.useState(!1),[R,G]=o.useState(!1),[B,E]=o.useState(""),[W,J]=o.useState(!1),[be,he]=o.useState(()=>ht()),[de,ye]=o.useState(null),[ge,ve]=o.useState(!1),[z,F]=o.useState(""),[Q,ue]=o.useState(!1),[te,fe]=o.useState(""),[ne,xe]=o.useState([]),[re,le]=o.useState(!1),[oe,Y]=o.useState(""),[X,ae]=o.useState(!1),A=o.useRef(null),H=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 ce=o.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(Z=>Z.category==="cli"&&Z.installed!==!1),[m]),me=o.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(Z=>Z.category==="acp"&&Z.installed!==!1),[m]),we=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]),_e=o.useMemo(()=>N==="cli"?ce.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"CLI provider"})):N==="acp"?me.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"ACP provider"})):we,[me,N,ce,we]);o.useEffect(()=>{var Le;if(!m)return;if(A.current!==m.id){A.current=m.id,x(S||((Le=w[0])==null?void 0:Le.id)||"__home__"),b(""),T(Rn(m)),C(""),v(""),I(""),K([]),G(!1),E(""),he(ht()),F("");return}x(De=>{var et;return De==="__custom__"||De==="__home__"||w.some(Tt=>Tt.id===De)?De:S||((et=w[0])==null?void 0:et.id)||"__home__"}),T(De=>De==="ide"&&we.length>0||De==="cli"&&ce.length>0||De==="acp"&&me.length>0?De:Rn(m))},[me.length,ce.length,S,we.length,m,w]),o.useEffect(()=>{var Z;N&&(_e.some(Le=>Le.id===y)||C(((Z=_e[0])==null?void 0:Z.id)||""))},[N,_e,y]);const Ae=o.useCallback(async(Z,Le)=>{const De=H.current+1;return H.current=De,L(!0),E(""),l(Z,Le).then(et=>{H.current===De&&K(et)}).catch(et=>{H.current===De&&(K([]),E(et instanceof Error?et.message:"Could not load saved sessions"))}).finally(()=>{H.current===De&&(L(!1),G(!0))})},[l]),Ke=o.useCallback((Z,Le)=>{D(ll(Z,Le))},[]);o.useEffect(()=>{H.current+=1,I(""),he(ht()),!m||!y||N==="ide"?D([]):Ke(m.id,y),G(!1),K([]),E(""),L(!1)},[N,Ke,Ae,m,y]),o.useEffect(()=>{if(!M)return;const Z=P.find(Le=>Le.providerSessionId===M);Z!=null&&Z.canResume||I("")},[P,M]);const Fe=p==="__custom__"?j.trim():p==="__home__"?"":((yt=w.find(Z=>Z.id===p))==null?void 0:yt.path)||"",ze=o.useMemo(()=>m?t.filter(Z=>Z.id!==m.id&&Z.daemonId===m.id).map(Z=>Z.workspace):[],[t,m]),ot=o.useMemo(()=>((m==null?void 0:m.recentLaunches)||[]).map(Z=>Z.workspace),[m]),it=o.useCallback(Z=>{const Le=String(Z.workspace||"").trim();if(!Le)return;const De=w.find(et=>Cr(et.path)===Cr(Le));if(De){x(De.id),b("");return}x("__custom__"),b(Le)},[w]),dt=o.useCallback(Z=>{const Le=String(Z.workspace||"").trim();if(!Le)return{workspaceId:null,workspacePath:null};const De=w.find(et=>Cr(et.path)===Cr(Le));return De?{workspaceId:De.id,workspacePath:null}:{workspaceId:null,workspacePath:Le}},[w]),ut=o.useMemo(()=>P.find(Z=>Z.providerSessionId===M)||null,[P,M]),mt=o.useMemo(()=>{var Le;if(N!=="cli"||!m||!y)return null;const Z=((Le=ce.find(De=>De.type===y))==null?void 0:Le.displayName)||y;return{routeId:m.id,daemonId:m.id,providerSessionId:M||void 0,transport:"pty",mode:"chat",agentName:Z,agentType:y,status:"idle",title:Z,messages:[],ideType:y,workspaceName:Fe,displayPrimary:Z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${m.id}:${y}`,machineName:Mt(m,{fallbackId:m.id})}},[N,ce,Fe,m,M,y]),Xe=o.useCallback(()=>{var Le;if(!m)return;x("__custom__"),ue(!0),Y("");const Z=sn(m.platform,tn(j.trim(),Fe,ze,ot,m.defaultWorkspacePath,(Le=w.find(De=>De.id===S))==null?void 0:Le.path,w.map(De=>De.path)));le(!0),n(m.id,Z).then(De=>{fe(De.path),b(De.path),xe(De.directories)}).catch(De=>{Y(De instanceof Error?De.message:"Could not load folder")}).finally(()=>le(!1))},[j,S,ot,ze,n,Fe,m,w]),rt=o.useCallback(Z=>{m&&(le(!0),Y(""),n(m.id,Z).then(Le=>{fe(Le.path),b(Le.path),xe(Le.directories)}).catch(Le=>{Y(Le instanceof Error?Le.message:"Could not load folder")}).finally(()=>le(!1)))},[n,m]),je=o.useCallback(async()=>{if(!m||!Fe)return;ae(!0),F("");const Z=await a(m.id,Fe);if(ae(!1),!Z.ok){F(Z.error||"Could not save workspace");return}F("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,Fe,m]),Ee=o.useCallback(async()=>{if(!m||!N||!y)return;ve(!0),F("");const Z=k.trim()?k.trim().split(/\s+/).filter(Boolean):[],Le=N==="ide"?await i(m.id,y,{workspacePath:Fe||null}):await c(m.id,N,y,{workspaceId:p!=="__home__"&&p!=="__custom__"?p:null,workspacePath:p==="__custom__"&&Fe||null,resumeSessionId:N==="cli"&&M?M:null,cliArgs:Z});if(ve(!1),!Le.ok){F(Le.error||"Could not start session");return}N!=="ide"&&k.trim()&&(dl(m.id,y,k),Ke(m.id,y)),r()},[N,k,Ke,r,i,c,Fe,m,M,y,p]),Be=N?bc(N,N==="cli"&&!!M):"Start",nt=N?gc(N,N==="cli"&&!!M):"Starting…";return m?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(wt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[s.jsx(Dr,{title:"Machine",children:s.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:ge,children:f.map(Z=>s.jsx("option",{value:Z.id,children:Mt(Z,{fallbackId:Z.id})},Z.id))})}),s.jsxs(Dr,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Xe,disabled:ge,children:"Browse…"}),children:[s.jsxs("select",{value:p,onChange:Z=>{const Le=Z.target.value;x(Le),Le==="__custom__"?Xe():F("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ge,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),w.map(Z=>s.jsxs("option",{value:Z.id,children:[Z.id===S?"⭐ ":"",Zr(Z.path,Z.label)||Z.path]},Z.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:p==="__home__"?"Launch without a workspace.":Fe||"Select a workspace folder."}),p==="__custom__"&&Fe&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Xe,disabled:ge,children:[s.jsx(Ss,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:je,disabled:ge||X,children:X?"Saving…":"Save workspace"})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:ce.length>0},{id:"ide",label:"IDE",enabled:we.length>0},{id:"acp",label:"ACP",enabled:me.length>0}].map(Z=>s.jsx("button",{type:"button",className:`btn btn-sm ${N===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>T(Z.id),disabled:!Z.enabled||ge,children:Z.label},Z.id))})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:N==="ide"?"Choose IDE":N==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[_e.map(Z=>s.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:ge,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.meta})]},Z.id)),_e.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),N!=="ide"&&s.jsxs(Dr,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:k,onChange:Z=>v(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:ge}),g.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:g.map(Z=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>v(Z),disabled:ge,title:Z,children:Z},Z))})]}),N==="cli"&&s.jsx(ml,{busy:ge,savedSessionsLoading:V,savedSessionsError:B,selectedSession:ut,onRefresh:()=>{!m||!y||Ae(m.id,y)},onOpenHistory:()=>{!m||!y||(J(!0),ul({hasLoadedInitialResults:R,isLoading:V})&&Ae(m.id,y))},onClearSelection:()=>I("")}),z&&s.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})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:r,disabled:ge,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:Ee,disabled:ge||!N||!y||p==="__custom__"&&!Fe,children:[s.jsx(ya,{size:14}),ge?nt:Be]})]})]})}),Q&&s.jsx(an,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:te,directories:ne,busy:re,error:oe,onClose:()=>ue(!1),onNavigate:rt,onConfirm:Z=>{b(Z),fe(Z),x("__custom__"),ue(!1)}}),W&&mt&&s.jsx(Da,{activeConv:mt,ides:[],isCreatingChat:!1,isRefreshingHistory:V,savedSessions:P,isSavedSessionsLoading:V,isResumingSavedSessionId:de,savedHistoryFilters:be,onSavedHistoryFiltersChange:he,onClose:()=>J(!1),onNewChat:()=>{I(""),J(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!m||!y||Ae(m.id,y)},onResumeSavedSession:Z=>{if(!m||!y||de||!Z.canResume)return;const Le=dt(Z);I(Z.providerSessionId),it(Z),ye(Z.providerSessionId),J(!1),ve(!0),F(""),c(m.id,"cli",y,{workspaceId:Le.workspaceId,workspacePath:Le.workspacePath,resumeSessionId:Z.providerSessionId}).then(De=>{if(!De.ok){F(De.error||"Could not resume session");return}r()}).finally(()=>{ve(!1),ye(De=>De===Z.providerSessionId?null:De)})}})]}):null}function ix({isMobile:e,showMobileChatMode:t,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),[w,S]=o.useState("quickstart"),[p,x]=o.useState("workspace"),j=o.useMemo(()=>!t&&!e,[t,e]),b=o.useCallback(v=>{a(v),v&&c(!1)},[]),N=o.useCallback(v=>{c(v),v&&a(!1)},[]),T=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)},[]),k=o.useCallback(()=>{d(!1)},[]);return o.useEffect(()=>{if(!j){m(!1);return}m(!0);const v=window.setTimeout(()=>{m(!1)},1e4);return()=>window.clearTimeout(v)},[j]),{inboxOpen:n,hiddenOpen:i,shortcutHelpOpen:l,newSessionOpen:f,guideNudgeVisible:h,guideTab:w,shortcutSection:p,isDesktopDashboard:j,setGuideTab:S,setShortcutSection:x,handleInboxOpenChange:b,handleHiddenOpenChange:N,handleOpenShortcutHelp:T,closeShortcutHelp:y,openNewSession:C,closeNewSession:k}}function cx(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 lx(e){return e instanceof Error?e.message:String(e||"")}function dx(e){const t=lx(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function ux({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetActiveCliViewMode:f,mobileChatConversations:d,hiddenConversations:h,ides:m,actionLogs:w,sendDaemonCommand:S,setActionLogs:p,setCliViewModeOverrides:x,isStandalone:j,initialDataLoaded:b,userName:N,requestedMobileTabKey:T,onRequestedMobileTabConsumed:y,requestedMachineId:C,onRequestedMachineConsumed:k,requestedMobileSection:v,onRequestedMobileSectionConsumed:g,containerRef:D,isSplitMode:M,numGroups:I,groupSizes:P,groupedConvs:K,clearedTabs:V,focusedGroup:L,focusGroup:R,moveTabToGroup:G,splitTabRelative:B,closeGroup:E,handleResizeStart:W,groupActiveTabIds:J,setGroupActiveTab:be,groupTabOrders:he,setGroupTabOrder:de,toggleHiddenTab:ye,visibleConversations:ge,requestedDesktopTabKey:ve,onRequestedDesktopTabConsumed:z,onDesktopActiveTabChange:F,onRequestScrollToBottom:Q,onHideConversation:ue,onShowHiddenConversation:te,onShowAllHiddenConversations:fe,scrollToBottomRequest:ne,machineEntries:xe,layoutProfile:re,onBrowseMachineDirectory:le,onSaveMachineWorkspace:oe,onLaunchMachineIde:Y,onLaunchMachineProvider:X,onListMachineSavedSessions:ae,notifications:A,notificationUnreadCount:H,liveSessionInboxState:ce,onMarkNotificationRead:me,onMarkNotificationUnread:we,onDeleteNotification:_e}){const Ae=St.useRef(null),{inboxOpen:Ke,hiddenOpen:Fe,shortcutHelpOpen:ze,newSessionOpen:ot,guideNudgeVisible:it,guideTab:dt,shortcutSection:ut,isDesktopDashboard:mt,setGuideTab:Xe,setShortcutSection:rt,handleInboxOpenChange:je,handleHiddenOpenChange:Ee,handleOpenShortcutHelp:Be,closeShortcutHelp:nt,openNewSession:st,closeNewSession:yt}=ix({isMobile:t,showMobileChatMode:e,visibleConversationCount:ge.length}),Z=St.useCallback(se=>{var ke;zs.flushSync(()=>{te(se)}),(ke=Ae.current)==null||ke.restoreHiddenTabToSavedLocation(se.tabKey)},[te]),Le=St.useCallback(se=>{var Oe;const ke=d.find(Ue=>Zn(Ue,se))||h.find(Ue=>Zn(Ue,se));ke&&(h.some(Ue=>Ue.tabKey===ke.tabKey)&&Z(ke),F(ke.tabKey),(Oe=Ae.current)==null||Oe.activateConversationTab(ke.tabKey),Q(ke.tabKey,"notification-open")),me(se.id),je(!1)},[Z,h,d,F,me,Q]),De=St.useCallback(()=>{var ke;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((ke=Ae.current)==null||ke.resetAllPanelsToMain(),Ee(!1))},[Ee]),et=St.useCallback(async se=>{var Ve;if(!r)return;const ke=(Ve=r.modalButtons)==null?void 0:Ve[se];if(!ke)return;const Oe=Js(r);if(!Oe)return;const Ue=ke.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Ye=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Ue);try{await S(Oe,"resolve_action",{button:ke,action:Ye?"approve":"reject",buttonIndex:se,...js(r)})}catch(Pe){dx(Pe)||console.error("[Shortcut approval] Failed:",Pe)}},[r,S]),{isMac:Tt,actionDefinitions:ft,actionShortcuts:He,shortcutListening:vt,shortcutListeningDraft:$,setShortcutListening:O,setShortcutListeningDraft:U,saveShortcuts:q}=Vh({enabled:mt&&!ze,onTrigger:se=>{var ke,Oe,Ue,Ye,Ve,Pe,_,ee,pe,Re,Ne,Me,Te,pt,ct,Ut;if(se==="openShortcutHelp"){Be();return}if(se==="hideCurrentTab"){r&&ue(r);return}if(se==="toggleHiddenTabs"){Ee(!Fe);return}if(se==="openHistoryForActiveTab"){r&&!qe(r)&&i(r);return}if(se==="openRemoteForActiveTab"){r&&!Je(r)&&!qe(r)&&c(r);return}if(se==="splitActiveTabRight"){(ke=Ae.current)==null||ke.splitActiveTabRight();return}if(se==="splitActiveTabDown"){(Oe=Ae.current)==null||Oe.splitActiveTabDown();return}if(se==="floatActiveTab"){(Ue=Ae.current)==null||Ue.floatActiveTab();return}if(se==="popoutActiveTab"){(Ye=Ae.current)==null||Ye.popoutActiveTab();return}if(se==="dockActiveTab"){(Ve=Ae.current)==null||Ve.dockActiveTab();return}if(se==="focusLeftPane"){(Pe=Ae.current)==null||Pe.focusLeftPane();return}if(se==="focusRightPane"){(_=Ae.current)==null||_.focusRightPane();return}if(se==="focusUpPane"){(ee=Ae.current)==null||ee.focusUpPane();return}if(se==="focusDownPane"){(pe=Ae.current)==null||pe.focusDownPane();return}if(se==="moveActiveTabToLeftPane"){(Re=Ae.current)==null||Re.moveActiveTabToLeftPane();return}if(se==="moveActiveTabToRightPane"){(Ne=Ae.current)==null||Ne.moveActiveTabToRightPane();return}if(se==="moveActiveTabToUpPane"){(Me=Ae.current)==null||Me.moveActiveTabToUpPane();return}if(se==="moveActiveTabToDownPane"){(Te=Ae.current)==null||Te.moveActiveTabToDownPane();return}if(se==="triggerPrimaryApprovalAction"){et(0);return}if(se==="triggerSecondaryApprovalAction"){et(1);return}if(se==="triggerTertiaryApprovalAction"){et(2);return}if(se==="setActiveTabShortcut"){(pt=Ae.current)==null||pt.setShortcutForActiveTab();return}if(se==="selectPreviousGroupTab"){(ct=Ae.current)==null||ct.activatePreviousTabInGroup();return}if(se==="selectNextGroupTab"){(Ut=Ae.current)==null||Ut.activateNextTabInGroup();return}!r||!Je(r)||qe(r)||se==="toggleCliView"&&f(u==="chat"?"terminal":"chat")}}),ie=St.useCallback(()=>{nt(),O(null),U([])},[nt,O,U]),Se=St.useMemo(()=>ut==="all"?ft:ft.filter(se=>cx(se)===ut),[ft,ut]),Ie=St.useCallback(()=>{const se=Object.fromEntries(ft.map(ke=>[ke.id,""]));q(se)},[ft,q]),Ce=St.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const se=Object.fromEntries(ft.map(ke=>[ke.id,ke.defaultShortcut]));q(se)},[ft,q]);return St.useEffect(()=>{const se=ke=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?ke.metaKey&&ke.key.toLowerCase()==="w":ke.ctrlKey&&ke.key.toLowerCase()==="w")&&(ke.preventDefault(),r&&ue&&ue(r))};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[r,ue]),St.useEffect(()=>{if(!ze||vt)return;const se=ke=>{ke.key==="Escape"&&(ke.preventDefault(),ie())};return window.addEventListener("keydown",se,!0),()=>window.removeEventListener("keydown",se,!0)},[ie,ze,vt]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(cf,{activeConv:r,wsStatus:n,isConnected:a,conversations:ge,hiddenConversations:h,onOpenHistory:i,onHideConversation:ue,onShowConversation:Z,onShowAllHidden:fe,onResetPanelsToMain:De,notifications:A,notificationUnreadCount:H,onOpenNotification:Le,onMarkNotificationRead:me,onMarkNotificationUnread:we,onDeleteNotification:_e,inboxOpen:Ke,onInboxOpenChange:je,hiddenOpen:Fe,onHiddenOpenChange:Ee,onOpenNewSession:t?void 0:st,actionShortcuts:He,onOpenRemote:()=>{!r||Je(r)||qe(r)||c(r)},onStopCli:l,activeCliViewMode:u,onSetCliViewMode:f}),e?s.jsx(_h,{conversations:d,hiddenConversations:h,ides:m,actionLogs:w,sendDaemonCommand:S,setActionLogs:p,setCliViewModeOverrides:x,isStandalone:j,userName:N,requestedActiveTabKey:T,onRequestedActiveTabConsumed:y,requestedMachineId:C,onRequestedMachineConsumed:k,requestedMobileSection:v,onRequestedMobileSectionConsumed:g,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowHiddenConversation:Z,onShowAllHiddenConversations:fe,onOpenNewSession:st,liveSessionInboxState:ce}):t?s.jsx(Hh,{containerRef:D,isSplitMode:M,numGroups:I,groupSizes:P,groupedConvs:K,clearedTabs:V,ides:m,actionLogs:w,sendDaemonCommand:S,setActionLogs:p,isStandalone:j,hasRegisteredMachines:xe.length>0,userName:N,focusedGroup:L,focusGroup:R,moveTabToGroup:G,splitTabRelative:B,closeGroup:E,handleResizeStart:W,groupActiveTabIds:J,setGroupActiveTab:be,groupTabOrders:he,setGroupTabOrder:de,toggleHiddenTab:ye,onOpenNewSession:st,allowTabShortcuts:!1,liveSessionInboxState:ce}):s.jsx(sx,{visibleConversations:ge,clearedTabs:V,ides:m,actionLogs:w,sendDaemonCommand:S,setActionLogs:p,isStandalone:j,hasRegisteredMachines:xe.length>0,initialDataLoaded:b,userName:N,toggleHiddenTab:ye,actionShortcuts:He,registerActionHandlers:se=>{Ae.current=se},onActiveTabChange:F,requestedActiveTabKey:ve,onRequestedActiveTabConsumed:z,onRequestScrollToBottom:Q,scrollToBottomRequest:ne,onOpenNewSession:st,liveSessionInboxState:ce,layoutProfile:re}),ot&&s.jsx(ox,{machines:xe,ides:m,onClose:yt,onBrowseDirectory:le,onSaveWorkspace:oe,onLaunchIde:Y,onLaunchProvider:X,onListSavedSessions:ae}),ze&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:ie,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:se=>se.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:ie,"aria-label":"Close dashboard guide",children:s.jsx(wt,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(se=>s.jsx("button",{type:"button",className:`btn btn-sm ${dt===se.id?"btn-primary":"btn-secondary"}`,onClick:()=>Xe(se.id),children:se.label},se.id))}),dt==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Tt?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),dt==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),dt==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(se=>s.jsx("button",{type:"button",className:`btn btn-sm ${ut===se.id?"btn-primary":"btn-secondary"}`,onClick:()=>rt(se.id),children:se.label},se.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ie,children:"Disable all"}),s.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:Ce,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Se.map(se=>s.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:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:se.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:se.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:se.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:vt===se.id?$.length>0?`${$.join(" ")} ...`:"Listening...":He[se.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{O(se.id),U([])},children:vt===se.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const ke={...He};ke[se.id]="",q(ke)},children:"Disable"})]})]})},se.id))}),s.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&&s.jsxs("button",{type:"button",onClick:Be,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 ${it?"gap-2 px-2.5":"justify-center w-10 px-0"}`,style:{boxShadow:"0 6px 18px rgba(0,0,0,0.12)"},title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"inline-flex items-center justify-center w-5 h-5 rounded-full bg-bg-secondary text-[11px] font-semibold text-text-primary shrink-0",children:"?"}),it&&s.jsx("span",{children:"Guide"})]})]})}const Pn=[{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 mx({onClose:e}){const[t,r]=o.useState(0),n=Pn[t],a=t===Pn.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:i=>{i.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(wt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Pn.map((i,c)=>s.jsx("div",{style:{width:c===t?24:8,height:8,borderRadius:4,background:c===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:n.icon})," ",n.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
|
|
53
|
+
`,ke.style.top="52px",ke.style.height="calc(100% - 52px)";const Ye=He.querySelector("[data-adhdev-popout-focus]");Ye&&(Ye.onclick=()=>{window.focus()});const ze=He.querySelector("[data-adhdev-popout-dock]");ze&&(ze.disabled=!Ie,ze.style.opacity=Ie?"1":"0.5",ze.style.cursor=Ie?"pointer":"default",ze.onclick=()=>{var Pe;Ie&&te(Ie),(Pe=ie.defaultView)==null||Pe.focus()})}},[de,te]),ne=o.useCallback(B=>{var q;const $=w.current,U=$==null?void 0:$.getPanel(B);if(!(!$||!U)){U.group.model.openPanel(U),U.api.setActive(),ve(B,"dockview-shortcut");try{const ie=U.group.model.location;ie.type==="popout"?ie.getWindow().focus():Ln((q=U.group.element)==null?void 0:q.ownerDocument)}catch{}}},[ve]),M=o.useCallback(B=>{const $=w.current,U=$==null?void 0:$.activePanel,q=($==null?void 0:$.activeGroup)||(U==null?void 0:U.group);if(!$||!U||!q)return;const ie=q.panels||[];if(ie.length<=1)return;const ke=ie.findIndex(se=>se.id===U.id);if(ke<0)return;const Ie=(ke+B+ie.length)%ie.length,Ne=ie[Ie];Ne&&(Ne.group.model.openPanel(Ne),Ne.api.setActive(),Lt(Ne.id)||ve(Ne.id,"dockview-shortcut"))},[ve]),H=o.useCallback(B=>{var Ye;const $=w.current,U=($==null?void 0:$.activeGroup)||((Ye=$==null?void 0:$.activePanel)==null?void 0:Ye.group);if(!$||!U)return;const q=$.groups||[],ie=q.find(ze=>ze.id===U.id);if(!ie)return;const ke=ie.element.getBoundingClientRect(),Ie=ke.left+ke.width/2,Ne=ke.top+ke.height/2,se=(ze,Pe,_,ee)=>Math.max(0,Math.min(Pe,ee)-Math.max(ze,_)),we=ze=>{const Pe=ze.element.getBoundingClientRect(),_=Pe.left+Pe.width/2,ee=Pe.top+Pe.height/2;let he=0,Re=0,Se=0,Ae=!1;if(B==="left"?(Ae=_<Ie,he=Math.max(0,ke.left-Pe.right),Re=Math.abs(ee-Ne),Se=se(ke.top,ke.bottom,Pe.top,Pe.bottom)):B==="right"?(Ae=_>Ie,he=Math.max(0,Pe.left-ke.right),Re=Math.abs(ee-Ne),Se=se(ke.top,ke.bottom,Pe.top,Pe.bottom)):B==="above"?(Ae=ee<Ne,he=Math.max(0,ke.top-Pe.bottom),Re=Math.abs(_-Ie),Se=se(ke.left,ke.right,Pe.left,Pe.right)):(Ae=ee>Ne,he=Math.max(0,Pe.top-ke.bottom),Re=Math.abs(_-Ie),Se=se(ke.left,ke.right,Pe.left,Pe.right)),!Ae)return Number.POSITIVE_INFINITY;const Te=Se>0?0:120;return he*3+Re+Te};let Ke=null,He=Number.POSITIVE_INFINITY;for(const ze of q){if(ze.id===ie.id)continue;const Pe=we(ze);Number.isFinite(Pe)&&(Pe>=He||(He=Pe,Ke=ze))}return Ke||void 0},[]),ce=o.useCallback(B=>{var q;const $=H(B);if(!$)return;const U=$.activePanel||$.panels[0];U&&($.model.openPanel(U),U.api.setActive(),Lt(U.id)||ve(U.id,"dockview-focus"),Ln((q=$.element)==null?void 0:q.ownerDocument))},[H,ve]),me=o.useCallback((B,$)=>{const U=w.current,q=U==null?void 0:U.activePanel,ie=(U==null?void 0:U.activeGroup)||(q==null?void 0:q.group);if(!U||!q||!ie)return;let ke=H(B);!ke&&($!=null&&$.createGroupIfMissing)&&(ke=U.addGroup({referenceGroup:ie,direction:B})),ke&&(q.api.moveTo({group:ke,position:"center"}),q.group.model.openPanel(q),q.api.setActive(),Lt(q.id)||ve(q.id,$!=null&&$.createGroupIfMissing?"dockview-split":"dockview-move"))},[H,ve]),{isMac:je,tabShortcuts:_e,shortcutListening:Me,setShortcutListening:Be,saveShortcuts:We}=rl({sortedTabKeys:e.map(B=>B.tabKey),onFocus:ge,onSelectTab:ne}),Fe=o.useCallback(()=>{var U;const B=w.current;if(!B)return;const $=B.activePanel;if($){if(Lt($.id)){const q=((U=$.params)==null?void 0:U.routeId)||$.id.slice(7),ie=_t(e,q);ie!=null&&ie.tabKey&&Be(ie.tabKey);return}de.has($.id)&&Be($.id)}},[de,ne,Be,e]),nt=o.useCallback(B=>{const $=[];return B.metaKey&&$.push(je?"⌘":"Meta"),B.ctrlKey&&$.push("Ctrl"),B.altKey&&$.push(je?"⌥":"Alt"),B.shiftKey&&B.key.length!==1&&$.push(je?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(B.key)?null:($.push(il(B.key)),$.join("+"))},[je]),Ze=o.useCallback(B=>{var $,U;switch(B){case"splitActiveTabRight":me("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":me("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const q=le();q&&pe(q);return}case"popoutActiveTab":{const q=le();q&&ue(q);return}case"dockActiveTab":{const q=le();if(!q)return;fe(q)?te(q):oe(q)&&ae(q);return}case"focusLeftPane":ce("left");return;case"focusRightPane":ce("right");return;case"focusUpPane":ce("above");return;case"focusDownPane":ce("below");return;case"moveActiveTabToLeftPane":me("left");return;case"moveActiveTabToRightPane":me("right");return;case"moveActiveTabToUpPane":me("above");return;case"moveActiveTabToDownPane":me("below");return;case"selectPreviousGroupTab":M(-1);return;case"selectNextGroupTab":M(1);return;case"setActiveTabShortcut":Fe();return;case"hideCurrentTab":{const q=(U=($=w.current)==null?void 0:$.activePanel)==null?void 0:U.id;q&&!Lt(q)&&re(q);return}default:return}},[M,ae,ce,pe,le,re,oe,fe,te,me,ue,Fe]);o.useEffect(()=>{if(!V)return;const B=V.sourceDocument,$=B.defaultView??window,U=q=>{const ie=B.querySelector("[data-dockview-tab-context-menu]");ie&&ie.contains(q.target)||L(null)};return $.addEventListener("mousedown",U,!0),$!==window&&window.addEventListener("mousedown",()=>L(null),!0),()=>{$.removeEventListener("mousedown",U,!0),$!==window&&window.removeEventListener("mousedown",()=>L(null),!0)}},[V]);const it=o.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:de,hasDetachedConversationPanels:ye,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:S,liveSessionInboxState:T,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:re,userName:f,scrollToBottomRequest:N,tabShortcuts:_e,openTabContextMenu:({x:B,y:$,tabKey:U,sourceDocument:q})=>L({x:B,y:$,tabKey:U,sourceDocument:q??document}),popoutTab:ue,moveTabBackToMain:te,isTabInPopout:fe,floatTab:pe,isTabFloating:oe}),[n,t,de,ye,r,c,l,S,T,a,i,re,f,N,_e,ue,te,fe,pe,oe]),dt=V?nx({isTabInPopout:fe(V.tabKey),isTabFloating:oe(V.tabKey),tabShortcut:_e[V.tabKey],actionShortcuts:x}):[],mt=o.useCallback(B=>{var q;const $=w.current;if((((q=$==null?void 0:$.activePanel)==null?void 0:q.id)??null)===B.id){B.group.model.openPanel(B);return}B.group.model.openPanel(B),B.api.setActive()},[]),at=o.useCallback((B,$="requested-tab")=>{if(!B)return!1;const U=w.current;if(!U)return!1;const q=U.getPanel(B);return q?(mt(q),ve(B,$),b==null||b(),!0):!1},[mt,b,ve]),ut=o.useCallback(()=>{if(I.current)return!1;const B=at(P.current,"stored-layout-restore");return B&&(I.current=!0),B},[at]),Ce=o.useCallback(()=>{var $;const B=w.current;B&&Hp(y,{activeTabId:(($=B.activePanel)==null?void 0:$.id)??null,layout:B.toJSON()})},[y]),$e=o.useCallback(()=>{Up(y,xe.current)},[y]),Ue=o.useCallback(B=>{var q,ie,ke,Ie;const $=w.current;if(!$)return{kind:"grid"};const U=$.toJSON();for(const Ne of U.floatingGroups||[])if((ie=(q=Ne.data)==null?void 0:q.views)!=null&&ie.includes(B)&&Ne.position)return{kind:"floating",position:Ne.position};for(const Ne of U.popoutGroups||[])if((Ie=(ke=Ne.data)==null?void 0:ke.views)!=null&&Ie.includes(B))return{kind:"popout",position:Ne.position,popoutUrl:Ne.url};return{kind:"grid"}},[]),Ve=o.useCallback(B=>{const $=w.current;if(!$)return;const U=$.getPanel(B),q=xe.current[B];if(!U||!q||q.kind==="grid")return;if(U.group.model.location.type===q.kind){delete xe.current[B],$e();return}if(q.kind==="floating"){$.addFloatingGroup(U,{x:q.position.left??24,y:q.position.top??24,width:q.position.width,height:q.position.height}),delete xe.current[B],$e();return}delete xe.current[B],$e()},[$e]);o.useEffect(()=>(m==null||m({setShortcutForActiveTab:Fe,restoreHiddenTabToSavedLocation:Ve,activateConversationTab:ne,resetAllPanelsToMain:Y,activatePreviousTabInGroup:()=>M(-1),activateNextTabInGroup:()=>M(1),floatActiveTab:()=>{const B=le();B&&pe(B)},popoutActiveTab:()=>{const B=le();B&&ue(B)},dockActiveTab:()=>{const B=le();B&&(fe(B)?te(B):oe(B)&&ae(B))},splitActiveTabRight:()=>me("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>me("below",{createGroupIfMissing:!0}),focusLeftPane:()=>ce("left"),focusRightPane:()=>ce("right"),focusUpPane:()=>ce("above"),focusDownPane:()=>ce("below"),moveActiveTabToLeftPane:()=>me("left"),moveActiveTabToRightPane:()=>me("right"),moveActiveTabToUpPane:()=>me("above"),moveActiveTabToDownPane:()=>me("below")}),()=>m==null?void 0:m(null)),[M,ae,pe,ce,le,oe,fe,me,te,ue,m,Y,Ve,ne,Fe]);const qe=o.useCallback(()=>{const B=g.current;if(!B)return;const $=B.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const U of $)U.setAttribute("data-adhdev-force-hidden","true")},[]),Je=o.useCallback(()=>{const B=g.current;if(!B)return;const $=B.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const U of $)U.removeAttribute("data-adhdev-force-hidden")},[]),Z=o.useCallback(()=>{const B=g.current;if(!B)return;const $=B.querySelectorAll(".dv-drop-target-container");for(const ie of $)ie.remove();const U=B.querySelectorAll(".dv-drop-target-dropzone");for(const ie of U)ie.remove();const q=B.querySelectorAll(".dv-drop-target");for(const ie of q)ie.classList.remove("dv-drop-target")},[]),Le=o.useCallback(()=>{G(!1),E(!1),Je(),qe(),Z(),!(typeof window>"u")&&(be.current!=null&&window.clearTimeout(be.current),window.requestAnimationFrame(()=>{qe(),Z()}),be.current=window.setTimeout(()=>{qe(),Z(),be.current=null},80))},[Je,qe,Z]),De=o.useCallback(B=>{var U;w.current=B.api;const $=Wp(y);if(P.current=($==null?void 0:$.activeTabId)??null,$!=null&&$.layout&&B.api.fromJSON($.layout,{reuseExistingPanels:!1}),A.current=si({hasStoredLayout:!!($!=null&&$.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),A.current||(ai(B.api,e),oi(B.api,e,j)),B.api.totalPanels===0&&e.length>0){const q=cx(B.api,e,h);if(q){const ie=B.api.getPanel(q);ie&&mt(ie)}}else!A.current&&!at(h)&&ut();D.current=!0,B.api.onDidActivePanelChange(q=>{var ke;if(P.current=(q==null?void 0:q.id)??null,I.current=!0,X(),q&&Lt(q.id)){const Ie=((ke=q.params)==null?void 0:ke.routeId)||q.id.slice(7),Ne=_t(e,Ie);v((Ne==null?void 0:Ne.tabKey)??null),Ce();return}if(v((q==null?void 0:q.id)??null),Ce(),!q)return;const ie=de.get(q.id);(ie==null?void 0:ie.streamSource)==="agent-stream"&&ie.agentType&&k(ie.routeId,Xc(),{agentType:ie.agentType,...ie.sessionId&&{targetSessionId:ie.sessionId}}).catch(()=>{})}),B.api.onDidLayoutChange(()=>{Ce(),X(),J(q=>q+1)}),B.api.onWillDragPanel(()=>{G(!0),E(!1),qe()}),B.api.onWillDragGroup(()=>{G(!0),E(!1),qe()}),B.api.onWillShowOverlay(()=>{Je(),E(!0)}),B.api.onDidMovePanel(Le),B.api.onDidDrop(Le),B.api.onDidAddGroup(q=>{requestAnimationFrame(()=>{var ie,ke;try{const Ie=(ie=q.element)==null?void 0:ie.ownerDocument;if(!Ie||Ie===document)return;(ke=Ie.getElementById("dv-popout-window"))==null||ke.classList.add("adhdev-dockview");const Ne=document.documentElement.getAttribute("data-theme");Ne&&Ie.documentElement.setAttribute("data-theme",Ne),Ie.body.className=document.body.className;const se=document.documentElement.getAttribute("style");se&&Ie.documentElement.setAttribute("style",se)}catch{}X(),J(Ie=>Ie+1)})}),v(((U=B.api.activePanel)==null?void 0:U.id)??null)},[mt,at,Le,Je,de,r,d,y,qe,v,Ce,h,j,k,X,e]);o.useLayoutEffect(()=>{const B=w.current;if(!B||!D.current||A.current&&si({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;A.current&&(A.current=!1);const $=O.current,U=new Set($),q=e.map(Ke=>Ke.tabKey),ie=new Set(q),ke=ax({previousVisibleConversationCount:$.length,visibleConversationCount:e.length,ides:r});let Ie=!1;for(const Ke of $)ie.has(Ke)||ke||(xe.current[Ke]=Ue(Ke),Ie=!0);Ie&&$e(),ke||(ai(B,e),oi(B,e,j));const Ne=q.filter(Ke=>!U.has(Ke));let se=!1;for(const Ke of Ne){const He=B.getPanel(Ke),Ye=xe.current[Ke];if(!He||!Ye||Ye.kind==="grid")continue;if(He.group.model.location.type===Ye.kind){delete xe.current[Ke],se=!0;continue}if(Ye.kind==="floating"){B.addFloatingGroup(He,{x:Ye.position.left??24,y:Ye.position.top??24,width:Ye.position.width,height:Ye.position.height}),delete xe.current[Ke],se=!0;continue}}if(se&&$e(),O.current=q,h&&at(h))return;!B.activePanel&&B.panels[0]&&mt(B.panels[0]),!!(B.activePanel&&B.getPanel(B.activePanel.id))||ut()},[mt,at,ut,r,d,$e,Ue,h,j,e]),o.useEffect(()=>{D.current&&at(h)},[at,h]),o.useEffect(()=>{if(!R||typeof window>"u")return;const B=()=>Le();return window.addEventListener("pointerup",B),window.addEventListener("mouseup",B),window.addEventListener("dragend",B),()=>{window.removeEventListener("pointerup",B),window.removeEventListener("mouseup",B),window.removeEventListener("dragend",B)}},[Le,R]),o.useEffect(()=>()=>{typeof window>"u"||be.current!=null&&window.clearTimeout(be.current)},[]),o.useEffect(()=>{const B=U=>{const q=U.target;if(!q)return;const ie=q.querySelector("[data-tab-key]")||q.closest("[data-tab-key]");if(ie){const ke=ie.getAttribute("data-tab-key");if(ke&&U.dataTransfer){const Ie=q.closest(".dv-tab")||ie.closest(".dv-tab")||ie;U.dataTransfer.effectAllowed="move",U.dataTransfer.setData("text/tab-key",ke),Ie instanceof HTMLElement&&U.dataTransfer.setDragImage(Ie,Math.max(12,Math.round(Ie.clientWidth/2)),Math.max(10,Math.round(Ie.clientHeight/2)))}}};window.addEventListener("dragstart",B);const $=ni(w.current);for(const U of $)U.addEventListener("dragstart",B);return()=>{window.removeEventListener("dragstart",B);for(const U of $)U.removeEventListener("dragstart",B)}},[W]),o.useEffect(()=>{var $;const B=($=g.current)==null?void 0:$.querySelector(".adhdev-dockview");B instanceof HTMLElement&&Nr(B,C),F(),X(),Q()},[X,Q,F,C]),o.useEffect(()=>{X(),Q()},[X,Q]),o.useEffect(()=>{const B=$=>{if($.defaultPrevented||Me)return;const U=nt($);if(!U)return;const q=$.metaKey||$.ctrlKey||$.altKey;la($.target)&&!q||Gr(je).setActiveTabShortcut!==U||($.preventDefault(),$.stopPropagation(),Fe())};return window.addEventListener("keydown",B,!0),()=>window.removeEventListener("keydown",B,!0)},[nt,je,Me,Fe]),o.useEffect(()=>{const B=g.current;if(!B)return;const $=U=>{var Ne,se;if(!U.isTrusted)return;const q=(se=(Ne=U.target)==null?void 0:Ne.closest)==null?void 0:se.call(Ne,".dv-scrollable");if(!q)return;U.preventDefault(),U.stopPropagation();const ie=Math.abs(U.deltaX),ke=Math.abs(U.deltaY),Ie=ie>ke?U.deltaX:U.deltaY;q.dispatchEvent(new WheelEvent("wheel",{deltaY:Ie,deltaMode:U.deltaMode,bubbles:!1,cancelable:!0}))};return B.addEventListener("wheel",$,{passive:!1,capture:!0}),()=>B.removeEventListener("wheel",$,{capture:!0})},[]),o.useEffect(()=>{const B=ni(w.current);if(B.length===0)return;const $=B.map(U=>{let q=[],ie=null;const ke=()=>{ie!=null&&U.clearTimeout(ie),ie=null,q=[]},Ie=()=>{ie!=null&&U.clearTimeout(ie),ie=U.setTimeout(()=>{ie=null,q=[]},1200)},Ne=we=>{if(!we.ctrlKey&&!we.metaKey&&!we.altKey)return;const Ke=nt(we);if(!Ke)return;const He=sl();for(const[Ye,ze]of Object.entries(He))if(e.some(Pe=>Pe.tabKey===Ye)&&ze===Ke){we.preventDefault(),ne(Ye);return}},se=we=>{if(we.defaultPrevented||Me)return;const Ke=nt(we);if(!Ke)return;const He=we.metaKey||we.ctrlKey||we.altKey;if(la(we.target)&&!He)return;const Ye=Gr(je),ze=Object.entries(Ye).filter(([Te,pt])=>!!pt&&(Te==="splitActiveTabRight"||Te==="splitActiveTabDown"||Te==="floatActiveTab"||Te==="popoutActiveTab"||Te==="dockActiveTab"||Te==="focusLeftPane"||Te==="focusRightPane"||Te==="focusUpPane"||Te==="focusDownPane"||Te==="moveActiveTabToLeftPane"||Te==="moveActiveTabToRightPane"||Te==="moveActiveTabToUpPane"||Te==="moveActiveTabToDownPane"||Te==="selectPreviousGroupTab"||Te==="selectNextGroupTab"||Te==="setActiveTabShortcut"||Te==="hideCurrentTab")),Pe=He?[Ke]:[...q.slice(-1),Ke].slice(-2),_=Pe.join(" "),ee=Pe[Pe.length-1],he=ze.find(([,Te])=>Te===_);if(he){we.preventDefault(),ke(),Ze(he[0]);return}if(ze.some(([,Te])=>Te.startsWith(`${_} `))){we.preventDefault(),q=Pe,Ie();return}const Se=ze.find(([,Te])=>Te===ee);if(Se){we.preventDefault(),ke(),Ze(Se[0]);return}if(ze.some(([,Te])=>Te.startsWith(`${ee} `))){we.preventDefault(),q=[ee],Ie();return}ke()};return U.addEventListener("keydown",Ne),U.addEventListener("keydown",se),()=>{ke(),U.removeEventListener("keydown",Ne),U.removeEventListener("keydown",se)}});return()=>{for(const U of $)U()}},[nt,je,W,ne,Me,Ze,e]);const st=C==="light"?Un:zn,Ct=((yt=(Tt=(ft=w.current)==null?void 0:ft.activePanel)==null?void 0:Tt.group.element)==null?void 0:yt.ownerDocument)??document;return s.jsxs(ll.Provider,{value:it,children:[s.jsx("div",{ref:g,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(nd,{className:`h-full min-h-0 min-w-0 adhdev-dockview${R?" is-dragging-dockview":""}${K?" is-showing-dockview-overlay":""}`,components:{conversation:lx,remote:dx},defaultTabComponent:mx,watermarkComponent:ux,onReady:De,singleTabMode:"default",tabAnimation:"smooth",theme:st,popoutUrl:"/popout.html"})}),V&&qs.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:V.x,top:V.y},children:dt.map(B=>{if(B.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},B.id);let $=s.jsx(Qd,{size:13,className:"shrink-0 opacity-70"}),U=()=>{};switch(B.id){case"dockInWindow":case"dockBackToGrid":$=s.jsx(eu,{size:13,className:"shrink-0 opacity-70"}),U=()=>{ae(V.tabKey),L(null)};break;case"moveBackToMain":$=s.jsx(Jd,{size:13,className:"shrink-0 opacity-70"}),U=()=>{te(V.tabKey),L(null)};break;case"floatAsPanel":$=s.jsx(Zd,{size:13,className:"shrink-0 opacity-70"}),U=()=>{pe(V.tabKey),L(null)};break;case"openInNewWindow":$=s.jsx(Xd,{size:13,className:"shrink-0 opacity-70"}),U=()=>{ue(V.tabKey),L(null)};break;case"setShortcut":U=q=>{q.stopPropagation(),Be(V.tabKey),L(null)};break;case"removeShortcut":$=s.jsx(vt,{size:13,className:"shrink-0 opacity-70"}),U=()=>{const q={..._e};delete q[V.tabKey],We(q),L(null)};break;case"hideTab":$=s.jsx(Pi,{size:13,className:"shrink-0 opacity-70"}),U=()=>{re(V.tabKey),L(null)};break}return s.jsxs("button",{className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${B.tone==="muted"?"text-text-muted":""}`,onClick:U,children:[$,s.jsx("span",{className:"flex-1 min-w-0",children:B.label}),B.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:B.shortcut}):null]},B.id)})}),V.sourceDocument.body),Me&&qs.createPortal(s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>Be(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:B=>B.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",je?"⌘+1":"Ctrl+1",", ",je?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),Ct.body)]})}const dl="adhdev-recent-launch-args-v1",px=8;function hx(e){return String(e||"").trim().replace(/\s+/g," ")}function ul(e,t){return`${e.trim()}::${t.trim()}`}function ml(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(dl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function xx(e){if(!(typeof window>"u"))try{window.localStorage.setItem(dl,JSON.stringify(e))}catch{}}function fl(e,t){var i;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((i=ml().byKey[ul(r,n)])==null?void 0:i.items)||[]}function pl(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),i=hx(r);if(!n||!a||!i)return;const c=ml(),l=ul(n,a),d=((u=c.byKey[l])==null?void 0:u.items)||[],f=[i,...d.filter(x=>x!==i)].slice(0,px);c.byKey[l]={items:f},xx(c)}function hl(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Dr({title:e,description:t,action:r,children:n,className:a="",contentClassName:i=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),r?s.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?s.jsx("div",{className:t||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function xl({busy:e,savedSessionsLoading:t,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?Zc(n):null;return s.jsxs(Dr,{title:"Saved history",description:_a(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:a,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:i,children:Nf()})]}),children:[l?s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:l.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:l.providerSessionId}),s.jsx("div",{className:"mt-1",children:l.metaLine}),l.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:l.updatedLabel}),l.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:l.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:c,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted",children:"Start fresh, or open saved history when you want continuity."}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function Rn(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>a.category==="cli"&&a.installed!==!1)?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>a.category==="acp"&&a.installed!==!1)?"acp":null}function Cr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function bx({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:c,onListSavedSessions:l}){var qe,Je;const d=ar(),f=o.useMemo(()=>[...e].sort(wa),[e]),[u,x]=o.useState(((qe=f[0])==null?void 0:qe.id)||""),m=o.useMemo(()=>f.find(Z=>Z.id===u)||f[0],[u,f]),v=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,h]=o.useState(""),[j,b]=o.useState(""),[N,T]=o.useState(Rn(f[0])),[y,C]=o.useState(""),[k,w]=o.useState(""),[g,D]=o.useState([]),[A,I]=o.useState(""),[P,O]=o.useState([]),[V,L]=o.useState(!1),[R,G]=o.useState(!1),[K,E]=o.useState(""),[W,J]=o.useState(!1),[be,xe]=o.useState(()=>ht()),[de,ye]=o.useState(null),[ge,ve]=o.useState(!1),[z,F]=o.useState(""),[Q,ue]=o.useState(!1),[te,fe]=o.useState(""),[re,pe]=o.useState([]),[oe,le]=o.useState(!1),[ae,Y]=o.useState(""),[X,ne]=o.useState(!1),M=o.useRef(null),H=o.useRef(0);o.useEffect(()=>{var Z;!u&&((Z=f[0])!=null&&Z.id)&&x(f[0].id)},[u,f]),o.useEffect(()=>{!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||d(m.id,{minFreshMs:3e4}).catch(()=>{})},[d,m]);const ce=o.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(Z=>Z.category==="cli"&&Z.installed!==!1),[m]),me=o.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(Z=>Z.category==="acp"&&Z.installed!==!1),[m]),je=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]),_e=o.useMemo(()=>N==="cli"?ce.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"CLI provider"})):N==="acp"?me.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"ACP provider"})):je,[me,N,ce,je]);o.useEffect(()=>{var Le;if(!m)return;if(M.current!==m.id){M.current=m.id,h(S||((Le=v[0])==null?void 0:Le.id)||"__home__"),b(""),T(Rn(m)),C(""),w(""),I(""),O([]),G(!1),E(""),xe(ht()),F("");return}h(De=>{var st;return De==="__custom__"||De==="__home__"||v.some(Ct=>Ct.id===De)?De:S||((st=v[0])==null?void 0:st.id)||"__home__"}),T(De=>De==="ide"&&je.length>0||De==="cli"&&ce.length>0||De==="acp"&&me.length>0?De:Rn(m))},[me.length,ce.length,S,je.length,m,v]),o.useEffect(()=>{var Z;N&&(_e.some(Le=>Le.id===y)||C(((Z=_e[0])==null?void 0:Z.id)||""))},[N,_e,y]);const Me=o.useCallback(async(Z,Le)=>{const De=H.current+1;return H.current=De,L(!0),E(""),l(Z,Le).then(st=>{H.current===De&&O(st)}).catch(st=>{H.current===De&&(O([]),E(st instanceof Error?st.message:"Could not load saved sessions"))}).finally(()=>{H.current===De&&(L(!1),G(!0))})},[l]),Be=o.useCallback((Z,Le)=>{D(fl(Z,Le))},[]);o.useEffect(()=>{H.current+=1,I(""),xe(ht()),!m||!y||N==="ide"?D([]):Be(m.id,y),G(!1),O([]),E(""),L(!1)},[N,Be,Me,m,y]),o.useEffect(()=>{if(!A)return;const Z=P.find(Le=>Le.providerSessionId===A);Z!=null&&Z.canResume||I("")},[P,A]);const We=p==="__custom__"?j.trim():p==="__home__"?"":((Je=v.find(Z=>Z.id===p))==null?void 0:Je.path)||"",Fe=o.useMemo(()=>m?t.filter(Z=>Z.id!==m.id&&Z.daemonId===m.id).map(Z=>Z.workspace):[],[t,m]),nt=o.useMemo(()=>((m==null?void 0:m.recentLaunches)||[]).map(Z=>Z.workspace),[m]),Ze=o.useCallback(Z=>{const Le=String(Z.workspace||"").trim();if(!Le)return;const De=v.find(st=>Cr(st.path)===Cr(Le));if(De){h(De.id),b("");return}h("__custom__"),b(Le)},[v]),it=o.useCallback(Z=>{const Le=String(Z.workspace||"").trim();if(!Le)return{workspaceId:null,workspacePath:null};const De=v.find(st=>Cr(st.path)===Cr(Le));return De?{workspaceId:De.id,workspacePath:null}:{workspaceId:null,workspacePath:Le}},[v]),dt=o.useMemo(()=>P.find(Z=>Z.providerSessionId===A)||null,[P,A]),mt=o.useMemo(()=>{var Le;if(N!=="cli"||!m||!y)return null;const Z=((Le=ce.find(De=>De.type===y))==null?void 0:Le.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:We,displayPrimary:Z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${m.id}:${y}`,machineName:At(m,{fallbackId:m.id})}},[N,ce,We,m,A,y]),at=o.useCallback(()=>{var Le;if(!m)return;h("__custom__"),ue(!0),Y("");const Z=sn(m.platform,tn(j.trim(),We,Fe,nt,m.defaultWorkspacePath,(Le=v.find(De=>De.id===S))==null?void 0:Le.path,v.map(De=>De.path)));le(!0),n(m.id,Z).then(De=>{fe(De.path),b(De.path),pe(De.directories)}).catch(De=>{Y(De instanceof Error?De.message:"Could not load folder")}).finally(()=>le(!1))},[j,S,nt,Fe,n,We,m,v]),ut=o.useCallback(Z=>{m&&(le(!0),Y(""),n(m.id,Z).then(Le=>{fe(Le.path),b(Le.path),pe(Le.directories)}).catch(Le=>{Y(Le instanceof Error?Le.message:"Could not load folder")}).finally(()=>le(!1)))},[n,m]),Ce=o.useCallback(async()=>{if(!m||!We)return;ne(!0),F("");const Z=await a(m.id,We);if(ne(!1),!Z.ok){F(Z.error||"Could not save workspace");return}F("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,We,m]),$e=o.useCallback(async()=>{if(!m||!N||!y)return;ve(!0),F("");const Z=k.trim()?k.trim().split(/\s+/).filter(Boolean):[],Le=N==="ide"?await i(m.id,y,{workspacePath:We||null}):await c(m.id,N,y,{workspaceId:p!=="__home__"&&p!=="__custom__"?p:null,workspacePath:p==="__custom__"&&We||null,resumeSessionId:N==="cli"&&A?A:null,cliArgs:Z});if(ve(!1),!Le.ok){F(Le.error||"Could not start session");return}N!=="ide"&&k.trim()&&(pl(m.id,y,k),Be(m.id,y)),r()},[N,k,Be,r,i,c,We,m,A,y,p]),Ue=N?wc(N,N==="cli"&&!!A):"Start",Ve=N?jc(N,N==="cli"&&!!A):"Starting…";return m?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[s.jsx(Dr,{title:"Machine",children:s.jsx("select",{value:m.id,onChange:Z=>x(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:ge,children:f.map(Z=>s.jsx("option",{value:Z.id,children:At(Z,{fallbackId:Z.id})},Z.id))})}),s.jsxs(Dr,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:at,disabled:ge,children:"Browse…"}),children:[s.jsxs("select",{value:p,onChange:Z=>{const Le=Z.target.value;h(Le),Le==="__custom__"?at():F("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ge,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),v.map(Z=>s.jsxs("option",{value:Z.id,children:[Z.id===S?"⭐ ":"",Zr(Z.path,Z.label)||Z.path]},Z.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:p==="__home__"?"Launch without a workspace.":We||"Select a workspace folder."}),p==="__custom__"&&We&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:at,disabled:ge,children:[s.jsx(Ns,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ce,disabled:ge||X,children:X?"Saving…":"Save workspace"})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:ce.length>0},{id:"ide",label:"IDE",enabled:je.length>0},{id:"acp",label:"ACP",enabled:me.length>0}].map(Z=>s.jsx("button",{type:"button",className:`btn btn-sm ${N===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>T(Z.id),disabled:!Z.enabled||ge,children:Z.label},Z.id))})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:N==="ide"?"Choose IDE":N==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[_e.map(Z=>s.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:ge,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.meta})]},Z.id)),_e.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),N!=="ide"&&s.jsxs(Dr,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:k,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:ge}),g.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:g.map(Z=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>w(Z),disabled:ge,title:Z,children:Z},Z))})]}),N==="cli"&&s.jsx(xl,{busy:ge,savedSessionsLoading:V,savedSessionsError:K,selectedSession:dt,onRefresh:()=>{!m||!y||Me(m.id,y)},onOpenHistory:()=>{!m||!y||(J(!0),hl({hasLoadedInitialResults:R,isLoading:V})&&Me(m.id,y))},onClearSelection:()=>I("")}),z&&s.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})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:r,disabled:ge,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:$e,disabled:ge||!N||!y||p==="__custom__"&&!We,children:[s.jsx(ya,{size:14}),ge?Ve:Ue]})]})]})}),Q&&s.jsx(an,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:te,directories:re,busy:oe,error:ae,onClose:()=>ue(!1),onNavigate:ut,onConfirm:Z=>{b(Z),fe(Z),h("__custom__"),ue(!1)}}),W&&mt&&s.jsx($a,{activeConv:mt,ides:[],isCreatingChat:!1,isRefreshingHistory:V,savedSessions:P,isSavedSessionsLoading:V,isResumingSavedSessionId:de,savedHistoryFilters:be,onSavedHistoryFiltersChange:xe,onClose:()=>J(!1),onNewChat:()=>{I(""),J(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!m||!y||Me(m.id,y)},onResumeSavedSession:Z=>{if(!m||!y||de||!Z.canResume)return;const Le=it(Z);I(Z.providerSessionId),Ze(Z),ye(Z.providerSessionId),J(!1),ve(!0),F(""),c(m.id,"cli",y,{workspaceId:Le.workspaceId,workspacePath:Le.workspacePath,resumeSessionId:Z.providerSessionId}).then(De=>{if(!De.ok){F(De.error||"Could not resume session");return}r()}).finally(()=>{ve(!1),ye(De=>De===Z.providerSessionId?null:De)})}})]}):null}function gx({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=o.useState(!1),[i,c]=o.useState(!1),[l,d]=o.useState(!1),[f,u]=o.useState(!1),[x,m]=o.useState(!1),[v,S]=o.useState("quickstart"),[p,h]=o.useState("workspace"),j=o.useMemo(()=>!t&&!e,[t,e]),b=o.useCallback(w=>{a(w),w&&c(!1)},[]),N=o.useCallback(w=>{c(w),w&&a(!1)},[]),T=o.useCallback(()=>{S(r===0?"quickstart":"shortcuts"),h("workspace"),d(!0),a(!1),c(!1)},[r]),y=o.useCallback(()=>{d(!1)},[]),C=o.useCallback(()=>{u(!0)},[]),k=o.useCallback(()=>{u(!1)},[]);return o.useEffect(()=>{if(!j){m(!1);return}m(!0);const w=window.setTimeout(()=>{m(!1)},1e4);return()=>window.clearTimeout(w)},[j]),{inboxOpen:n,hiddenOpen:i,shortcutHelpOpen:l,newSessionOpen:f,guideNudgeVisible:x,guideTab:v,shortcutSection:p,isDesktopDashboard:j,setGuideTab:S,setShortcutSection:h,handleInboxOpenChange:b,handleHiddenOpenChange:N,handleOpenShortcutHelp:T,closeShortcutHelp:y,openNewSession:C,closeNewSession:k}}function yx(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 vx(e){return e instanceof Error?e.message:String(e||"")}function wx(e){const t=vx(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function jx({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:d,onSetActiveCliViewMode:f,mobileChatConversations:u,hiddenConversations:x,ides:m,actionLogs:v,sendDaemonCommand:S,setActionLogs:p,setCliViewModeOverrides:h,isStandalone:j,initialDataLoaded:b,userName:N,requestedMobileTabKey:T,onRequestedMobileTabConsumed:y,requestedMachineId:C,onRequestedMachineConsumed:k,requestedMobileSection:w,onRequestedMobileSectionConsumed:g,containerRef:D,isSplitMode:A,numGroups:I,groupSizes:P,groupedConvs:O,clearedTabs:V,focusedGroup:L,focusGroup:R,moveTabToGroup:G,splitTabRelative:K,closeGroup:E,handleResizeStart:W,groupActiveTabIds:J,setGroupActiveTab:be,groupTabOrders:xe,setGroupTabOrder:de,toggleHiddenTab:ye,visibleConversations:ge,requestedDesktopTabKey:ve,onRequestedDesktopTabConsumed:z,onDesktopActiveTabChange:F,onRequestScrollToBottom:Q,onHideConversation:ue,onShowHiddenConversation:te,onShowAllHiddenConversations:fe,scrollToBottomRequest:re,machineEntries:pe,layoutProfile:oe,onBrowseMachineDirectory:le,onSaveMachineWorkspace:ae,onLaunchMachineIde:Y,onLaunchMachineProvider:X,onListMachineSavedSessions:ne,notifications:M,notificationUnreadCount:H,liveSessionInboxState:ce,onMarkNotificationRead:me,onMarkNotificationUnread:je,onDeleteNotification:_e}){const Me=kt.useRef(null),{inboxOpen:Be,hiddenOpen:We,shortcutHelpOpen:Fe,newSessionOpen:nt,guideNudgeVisible:Ze,guideTab:it,shortcutSection:dt,isDesktopDashboard:mt,setGuideTab:at,setShortcutSection:ut,handleInboxOpenChange:Ce,handleHiddenOpenChange:$e,handleOpenShortcutHelp:Ue,closeShortcutHelp:Ve,openNewSession:qe,closeNewSession:Je}=gx({isMobile:t,showMobileChatMode:e,visibleConversationCount:ge.length}),Z=kt.useCallback(se=>{var we;qs.flushSync(()=>{te(se)}),(we=Me.current)==null||we.restoreHiddenTabToSavedLocation(se.tabKey)},[te]),Le=kt.useCallback(se=>{var Ke;const we=u.find(He=>Zn(He,se))||x.find(He=>Zn(He,se));we&&(x.some(He=>He.tabKey===we.tabKey)&&Z(we),F(we.tabKey),(Ke=Me.current)==null||Ke.activateConversationTab(we.tabKey),Q(we.tabKey,"notification-open")),me(se.id),Ce(!1)},[Z,x,u,F,me,Q]),De=kt.useCallback(()=>{var we;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((we=Me.current)==null||we.resetAllPanelsToMain(),$e(!1))},[$e]),st=kt.useCallback(async se=>{var ze;if(!r)return;const we=(ze=r.modalButtons)==null?void 0:ze[se];if(!we)return;const Ke=Zs(r);if(!Ke)return;const He=we.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Ye=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(He);try{await S(Ke,"resolve_action",{button:we,action:Ye?"approve":"reject",buttonIndex:se,...js(r)})}catch(Pe){wx(Pe)||console.error("[Shortcut approval] Failed:",Pe)}},[r,S]),{isMac:Ct,actionDefinitions:ft,actionShortcuts:Tt,shortcutListening:yt,shortcutListeningDraft:B,setShortcutListening:$,setShortcutListeningDraft:U,saveShortcuts:q}=rx({enabled:mt&&!Fe,onTrigger:se=>{var we,Ke,He,Ye,ze,Pe,_,ee,he,Re,Se,Ae,Te,pt,ct,Ot;if(se==="openShortcutHelp"){Ue();return}if(se==="hideCurrentTab"){r&&ue(r);return}if(se==="toggleHiddenTabs"){$e(!We);return}if(se==="openHistoryForActiveTab"){r&&!Xe(r)&&i(r);return}if(se==="openRemoteForActiveTab"){r&&!Qe(r)&&!Xe(r)&&c(r);return}if(se==="splitActiveTabRight"){(we=Me.current)==null||we.splitActiveTabRight();return}if(se==="splitActiveTabDown"){(Ke=Me.current)==null||Ke.splitActiveTabDown();return}if(se==="floatActiveTab"){(He=Me.current)==null||He.floatActiveTab();return}if(se==="popoutActiveTab"){(Ye=Me.current)==null||Ye.popoutActiveTab();return}if(se==="dockActiveTab"){(ze=Me.current)==null||ze.dockActiveTab();return}if(se==="focusLeftPane"){(Pe=Me.current)==null||Pe.focusLeftPane();return}if(se==="focusRightPane"){(_=Me.current)==null||_.focusRightPane();return}if(se==="focusUpPane"){(ee=Me.current)==null||ee.focusUpPane();return}if(se==="focusDownPane"){(he=Me.current)==null||he.focusDownPane();return}if(se==="moveActiveTabToLeftPane"){(Re=Me.current)==null||Re.moveActiveTabToLeftPane();return}if(se==="moveActiveTabToRightPane"){(Se=Me.current)==null||Se.moveActiveTabToRightPane();return}if(se==="moveActiveTabToUpPane"){(Ae=Me.current)==null||Ae.moveActiveTabToUpPane();return}if(se==="moveActiveTabToDownPane"){(Te=Me.current)==null||Te.moveActiveTabToDownPane();return}if(se==="triggerPrimaryApprovalAction"){st(0);return}if(se==="triggerSecondaryApprovalAction"){st(1);return}if(se==="triggerTertiaryApprovalAction"){st(2);return}if(se==="setActiveTabShortcut"){(pt=Me.current)==null||pt.setShortcutForActiveTab();return}if(se==="selectPreviousGroupTab"){(ct=Me.current)==null||ct.activatePreviousTabInGroup();return}if(se==="selectNextGroupTab"){(Ot=Me.current)==null||Ot.activateNextTabInGroup();return}!r||!Qe(r)||Xe(r)||se==="toggleCliView"&&f(d==="chat"?"terminal":"chat")}}),ie=kt.useCallback(()=>{Ve(),$(null),U([])},[Ve,$,U]),ke=kt.useMemo(()=>dt==="all"?ft:ft.filter(se=>yx(se)===dt),[ft,dt]),Ie=kt.useCallback(()=>{const se=Object.fromEntries(ft.map(we=>[we.id,""]));q(se)},[ft,q]),Ne=kt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const se=Object.fromEntries(ft.map(we=>[we.id,we.defaultShortcut]));q(se)},[ft,q]);return kt.useEffect(()=>{const se=we=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?we.metaKey&&we.key.toLowerCase()==="w":we.ctrlKey&&we.key.toLowerCase()==="w")&&(we.preventDefault(),r&&ue&&ue(r))};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[r,ue]),kt.useEffect(()=>{if(!Fe||yt)return;const se=we=>{we.key==="Escape"&&(we.preventDefault(),ie())};return window.addEventListener("keydown",se,!0),()=>window.removeEventListener("keydown",se,!0)},[ie,Fe,yt]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(yf,{activeConv:r,wsStatus:n,isConnected:a,conversations:ge,hiddenConversations:x,onOpenHistory:i,onHideConversation:ue,onShowConversation:Z,onShowAllHidden:fe,onResetPanelsToMain:De,notifications:M,notificationUnreadCount:H,onOpenNotification:Le,onMarkNotificationRead:me,onMarkNotificationUnread:je,onDeleteNotification:_e,inboxOpen:Be,onInboxOpenChange:Ce,hiddenOpen:We,onHiddenOpenChange:$e,onOpenNewSession:t?void 0:qe,actionShortcuts:Tt,onOpenRemote:()=>{!r||Qe(r)||Xe(r)||c(r)},onStopCli:l,activeCliViewMode:d,onSetCliViewMode:f}),e?s.jsx(zh,{conversations:u,hiddenConversations:x,ides:m,actionLogs:v,sendDaemonCommand:S,setActionLogs:p,setCliViewModeOverrides:h,isStandalone:j,userName:N,requestedActiveTabKey:T,onRequestedActiveTabConsumed:y,requestedMachineId:C,onRequestedMachineConsumed:k,requestedMobileSection:w,onRequestedMobileSectionConsumed:g,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowHiddenConversation:Z,onShowAllHiddenConversations:fe,onOpenNewSession:qe,liveSessionInboxState:ce}):t?s.jsx(Zh,{containerRef:D,isSplitMode:A,numGroups:I,groupSizes:P,groupedConvs:O,clearedTabs:V,ides:m,actionLogs:v,sendDaemonCommand:S,setActionLogs:p,isStandalone:j,hasRegisteredMachines:pe.length>0,userName:N,focusedGroup:L,focusGroup:R,moveTabToGroup:G,splitTabRelative:K,closeGroup:E,handleResizeStart:W,groupActiveTabIds:J,setGroupActiveTab:be,groupTabOrders:xe,setGroupTabOrder:de,toggleHiddenTab:ye,onOpenNewSession:qe,allowTabShortcuts:!1,liveSessionInboxState:ce}):s.jsx(fx,{visibleConversations:ge,clearedTabs:V,ides:m,actionLogs:v,sendDaemonCommand:S,setActionLogs:p,isStandalone:j,hasRegisteredMachines:pe.length>0,initialDataLoaded:b,userName:N,toggleHiddenTab:ye,actionShortcuts:Tt,registerActionHandlers:se=>{Me.current=se},onActiveTabChange:F,requestedActiveTabKey:ve,onRequestedActiveTabConsumed:z,onRequestScrollToBottom:Q,scrollToBottomRequest:re,onOpenNewSession:qe,liveSessionInboxState:ce,layoutProfile:oe}),nt&&s.jsx(bx,{machines:pe,ides:m,onClose:Je,onBrowseDirectory:le,onSaveWorkspace:ae,onLaunchIde:Y,onLaunchProvider:X,onListSavedSessions:ne}),Fe&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:ie,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:se=>se.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:ie,"aria-label":"Close dashboard guide",children:s.jsx(vt,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(se=>s.jsx("button",{type:"button",className:`btn btn-sm ${it===se.id?"btn-primary":"btn-secondary"}`,onClick:()=>at(se.id),children:se.label},se.id))}),it==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Ct?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),it==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),it==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(se=>s.jsx("button",{type:"button",className:`btn btn-sm ${dt===se.id?"btn-primary":"btn-secondary"}`,onClick:()=>ut(se.id),children:se.label},se.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ie,children:"Disable all"}),s.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:Ne,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:ke.map(se=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${yt===se.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:se.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:se.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:se.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:yt===se.id?B.length>0?`${B.join(" ")} ...`:"Listening...":Tt[se.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{$(se.id),U([])},children:yt===se.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const we={...Tt};we[se.id]="",q(we)},children:"Disable"})]})]})},se.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Ct?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&s.jsxs("button",{type:"button",onClick:Ue,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 ${Ze?"gap-2 px-2.5":"justify-center w-10 px-0"}`,style:{boxShadow:"0 6px 18px rgba(0,0,0,0.12)"},title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"inline-flex items-center justify-center w-5 h-5 rounded-full bg-bg-secondary text-[11px] font-semibold text-text-primary shrink-0",children:"?"}),Ze&&s.jsx("span",{children:"Guide"})]})]})}const Pn=[{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 kx({onClose:e}){const[t,r]=o.useState(0),n=Pn[t],a=t===Pn.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:i=>{i.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(vt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Pn.map((i,c)=>s.jsx("div",{style:{width:c===t?24:8,height:8,borderRadius:4,background:c===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:n.icon})," ",n.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
|
|
54
54
|
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
55
55
|
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
56
|
-
`})]})}function fx({hasExtensions:e,ideName:t,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:t}),n.map(i=>{const c=r===i.tabKey,l=i.status==="waiting_approval",u=i.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${c?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(i.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"0 0 6px var(--accent-primary)":"none"}}),i.title,l&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},i.tabKey)})]}):null}function px({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,c]=o.useState(()=>a||"native"),l=o.useMemo(()=>vc(t),[t]),u=o.useMemo(()=>e?Ea(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]),w=o.useMemo(()=>d.map(p=>({tabKey:p.tabKey,title:fc(p)||n,status:p.status})),[d,n]),S=o.useCallback(p=>{if(p)return u.find(x=>Zn(x,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[u]);return{activeChatTab:i,setActiveChatTab:c,activeConv:m,conversations:u,extensionTabs:w,hasExtensions:w.length>0,resolveConversationByTarget:S}}function hx({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:i,setActionLogs:c,isStandalone:l,userName:u,onOpenHistory:f,onConversationChange:d,onClose:h}){const[m,w]=o.useState("split"),[S,p]=o.useState(()=>Vt(e)?"native":e.tabKey),x=o.useRef(null),j=o.useMemo(()=>t||r.find(R=>R.id===e.routeId),[e.routeId,t,r]),b=o.useMemo(()=>Ze((j==null?void 0:j.type)||""),[j==null?void 0:j.type]),{conversations:N,extensionTabs:T,hasExtensions:y}=px({ideData:j,allIdes:r,connectionStates:n,ideName:b||"IDE",preferredTabKey:Vt(e)?void 0:e.tabKey}),C=o.useMemo(()=>j?_t(N,j.id):null,[j,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 k=o.useMemo(()=>S==="native"?N.find(R=>R.streamSource==="native")||e:N.find(R=>R.tabKey===S)||e,[e,N,S]),v=_c(k),g=o.useMemo(()=>v.status||v.modalMessage||v.modalButtons?{...k,...v.status?{status:v.status}:{},...v.modalMessage!==void 0?{modalMessage:v.modalMessage}:{},...v.modalButtons!==void 0?{modalButtons:v.modalButtons}:{}}:k,[k,v]),D=sr(g),M=nn({sendDaemonCommand:i,activeConv:g,setActionLogs:c,isStandalone:l}),{connScreenshot:I,screenshotUsage:P,handleRemoteAction:K}=el({doId:D,targetSessionId:Qi(g),connState:g.connectionState||"new",viewMode:m}),V=o.useMemo(()=>a.filter(R=>R.routeId===g.tabKey),[a,g.tabKey]);o.useEffect(()=>{d==null||d(g)},[g,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 s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:h,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:L,children:[s.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Ct,{size:16})}),s.jsx("span",{className:"truncate",children:Sa(k)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(R=>{const G=m===R;return s.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:()=>w(R),title:R==="split"?"Split view":"Remote only",children:R==="split"?s.jsx(Ld,{size:15}):s.jsx(Ct,{size:15})},R)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>f(k),title:"Chat History",children:[s.jsx(ba,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${m==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[m!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${m==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(fx,{hasExtensions:y,ideName:b||"IDE",activeChatTab:S,extensionTabs:T,onSelectTab:p}),s.jsx($i,{activeConv:g,onModalButton:M.handleModalButton}),s.jsx(na,{activeConv:g,ideEntry:j,showMetaChips:!1,handleSendChat:M.handleSendChat,isSendingChat:M.isSendingChat,sendFeedbackMessage:M.sendFeedbackMessage,handleFocusAgent:M.handleFocusAgent,isFocusingAgent:M.isFocusingAgent,actionLogs:V,userName:u})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${m==="split"?"order-1 md:order-2":""}`,children:s.jsx(Di,{addLog:()=>{},connState:g.connectionState||"new",connScreenshot:I,screenshotUsage:P,transportType:g.transport,onAction:K})})]})]})})}function xx({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=ef(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[s.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",i,"?"]}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:t?"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.":"This provider does not support graceful stop. Force Stop will end the runtime immediately."})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),s.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Force Stop"}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function bx({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(nf,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(Da,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),t.conversation&&s.jsx(hx,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),r.open&&r.targetConv&&(Je(r.targetConv)||qe(r.targetConv))&&s.jsx(xx,{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}),s.jsx(yc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&s.jsx(mx,{onClose:i.onClose})]})}function gx({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:i}){return e.length===0?null:s.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(er,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[r?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(c=>{const l=Mt(c,{fallbackId:c.id}),u=n[c.id],f=c.version||c.daemonVersion||"unknown",d=c.versionUpdateRequired===!0;return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:l}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",f]}),d&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:d?"Update now":"Upgrade"})]},c.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:s.jsx(wt,{size:16})})]})}function yx(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function vx(e){const t=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:r===e.autoReadKey?r:null}:r===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:r}:{shouldSchedule:!0,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!r,nextPendingKey:null}}function wx(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&t&&t!==r),autoReadKey:i,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function jx(e){const t=e.machine;return typeof(t==null?void 0:t.cpus)!="number"||typeof(t==null?void 0:t.totalMem)!="number"||typeof(t==null?void 0:t.arch)!="string"||typeof(t==null?void 0:t.release)!="string"}function kx(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>jx(t)).map(t=>t.id)}}function Sx(){var Qa,Za,eo,to;const{sendCommand:e}=jt(),t=nr(),r=Pc(),n=pa(),a=As(),[i,c]=Ql(),l=i.get("activeTab"),u=((Qa=n.state)==null?void 0:Qa.openRemoteForTabKey)||null,f=((Za=n.state)==null?void 0:Za.openMachineId)||null,d=((eo=n.state)==null?void 0:eo.mobileSection)||null,h=lc(),m=h.ides||[],w=h.initialLoaded??!0,{updateRouteChats:S,setToasts:p}=h,[x,j]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),b=h.toasts||[],N=h.wsStatus||"connected",T=h.isConnected??!0,y=h.connectionStates||{},C=h.showReconnected||!1,{layoutProfile:k,groupAssignments:v,updateGroupAssignments:g,focusedGroup:D,updateFocusedGroup:M,focusGroup:I,groupActiveTabIds:P,updateGroupActiveTabIds:K,setGroupActiveTab:V,groupTabOrders:L,updateGroupTabOrders:R,setGroupTabOrder:G,groupSizes:B,updateGroupSizes:E,isMobile:W,hasHydratedStoredLayout:J,hydrateStoredLayout:be,focusConversationTab:he}=Ep(),[de,ye]=o.useState(()=>Oa());o.useEffect(()=>ep(ye),[]);const ge=o.useMemo(()=>yx({isMobile:W,mobileViewMode:de}),[W,de]),[ve,z]=o.useState([]),[F,Q]=o.useState({}),[ue,te]=o.useState({});tr("Dashboard",{ideCount:m.length,toastCount:b.length,focusedGroup:D,groupCount:Object.keys(v).length,actionLogCount:ve.length});const fe=o.useMemo(()=>m.filter(We=>We.type==="adhdev-daemon").sort(wa),[m]),ne=fe[0],xe=!!ne;o.useEffect(()=>{const{metadataDaemonIds:We,runtimeDaemonIds:kt}=kx(fe);for(const Dt of We)t(Dt,{minFreshMs:3e4}).catch(()=>{});for(const Dt of kt)r(Dt,{minFreshMs:3e4}).catch(()=>{})},[t,r,fe]);const re=(ne==null?void 0:ne.terminalBackend)||null,le=ne?Mt(ne,{fallbackId:ne.id}):null,oe=(ne==null?void 0:ne.id)||null,Y=o.useMemo(()=>up(m,F),[m,F]),{hiddenTabs:X,hideTarget:ae,toggleTarget:A,showTarget:H,showAllTabs:ce}=dp(),{conversations:me,visibleConversations:we,visibleTabKeys:_e,resolveConversationBySessionId:Ae,resolveConversationByTarget:Ke}=wp({ides:Y,connectionStates:y,clearedTabs:ue,hiddenTabs:X}),Fe=o.useMemo(()=>new Map(me.map(We=>[We.tabKey,We])),[me]);Hm(we,ge),o.useEffect(()=>{Object.keys(F).length!==0&&Q(We=>mp(We,m))},[m,F]);const ze=o.useMemo(()=>fu(m),[m]),{notifications:ot,unreadCount:it}=Jp({conversations:me,liveSessionInboxState:ze}),{handleMarkDashboardNotificationRead:dt,handleMarkDashboardNotificationUnread:ut,handleDeleteDashboardNotification:mt}=Qp({notifications:ot,sendDaemonCommand:e}),Xe=o.useRef(null),rt=o.useRef(null),je=o.useRef(null),Ee=o.useRef(null),Be=o.useRef(null),{containerRef:nt,normalizedGroupAssignments:st,numGroups:yt,isSplitMode:Z,groupedConvs:Le,moveTabToGroup:De,closeGroup:et,handleResizeStart:Tt,splitTabRelative:ft}=Fp({groupAssignments:v,updateGroupAssignments:g,updateFocusedGroup:M,updateGroupActiveTabIds:K,updateGroupTabOrders:R,groupSizes:B,updateGroupSizes:E,isMobile:W,visibleConversations:we,visibleTabKeys:_e}),{activeConv:He,openDesktopConversation:vt,requestScrollToBottom:$,scrollToBottomRequest:O,setDesktopActiveTab:U}=ch({isMobile:W,conversations:me,visibleConversations:we,groupActiveTabIds:P,focusedGroup:D,groupedConvs:Le,setSearchParams:c});o.useEffect(()=>{const We=()=>{je.current&&(clearTimeout(je.current),je.current=null),Ee.current&&(clearTimeout(Ee.current),Ee.current=null),Be.current&&(document.removeEventListener("visibilitychange",Be.current),Be.current=null),rt.current=null};if(W){We(),Xe.current=null;return}if(!(He!=null&&He.sessionId)){We(),Xe.current=null;return}const kt=Or(He,ze),Dt=wx({tabKey:He.tabKey,historySessionId:rr(He)||"",lastMessageHash:He.lastMessageHash||"",lastMessageAt:Number(He.lastMessageAt||0),timestamp:es(He),liveState:kt}),ir=Dt.autoReadKey,cr=vx({autoReadKey:ir,shouldMarkSeen:Dt.shouldMarkSeen,completedKey:Xe.current,pendingKey:rt.current});if(!Dt.shouldMarkSeen){cr.shouldCancelPending&&We(),Xe.current=ir;return}if(!cr.shouldSchedule)return;cr.shouldCancelPending&&We();const so=()=>{if(document.visibilityState!=="visible"||Xe.current===ir)return;Xe.current=ir,rt.current=null,je.current=null,Ee.current=null,Be.current&&(document.removeEventListener("visibilitychange",Be.current),Be.current=null);const lr=Dt.readAt;e(He.daemonId||He.routeId,"mark_session_seen",{sessionId:He.sessionId,seenAt:lr}).catch(()=>{})};if(rt.current=cr.nextPendingKey,document.visibilityState==="visible"){je.current=setTimeout(so,1500);const lr=()=>{document.visibilityState!=="visible"&&je.current&&(clearTimeout(je.current),je.current=null)};Be.current=lr,document.addEventListener("visibilitychange",lr);return}const ro=()=>{document.visibilityState==="visible"&&(Ee.current&&clearTimeout(Ee.current),Ee.current=setTimeout(so,800),Be.current&&(document.removeEventListener("visibilitychange",Be.current),Be.current=null))};Be.current=ro,document.addEventListener("visibilitychange",ro)},[He,W,ze,e]),o.useEffect(()=>()=>{je.current&&clearTimeout(je.current),Ee.current&&clearTimeout(Ee.current),Be.current&&document.removeEventListener("visibilitychange",Be.current)},[]);const{requestedDesktopTabKey:q,requestedMobileTabKey:ie,consumeRequestedActiveTab:Se}=jp({isMobile:W,urlActiveTab:l,resolveConversationBySessionId:Ae,setSearchParams:c}),{remoteDialogConv:Ie,remoteDialogIdeEntry:Ce,remoteDialogActiveConv:se,setRemoteDialogActiveConv:ke,openRemoteDialog:Oe,closeRemoteDialog:Ue,cliStopDialogOpen:Ye,cliStopTargetConv:Ve,requestCliStop:Pe,cancelCliStop:_,confirmCliStop:ee}=uh({isMobile:W,location:n,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:q,conversations:me,ides:m,resolveConversationByTarget:Ke,activeConv:He,sendDaemonCommand:e}),{historyModalOpen:pe,openHistoryModal:Re,closeHistoryModal:Ne,historyTargetConv:Me,isSavedSessionHistoryTarget:Te,isHistoryCreatingChat:pt,isHistoryRefreshingHistory:ct,handleHistorySwitchSession:Ut,handleHistoryNewChat:yl,handleHistoryRefresh:vl,savedHistorySessions:wl,savedHistoryFilters:jl,setSavedHistoryFilters:kl,isSavedHistoryLoading:Sl,resumingSavedHistorySessionId:Nl,handleRefreshSavedHistory:Cl,handleResumeSavedHistorySession:Il}=lh({activeConv:He,remoteDialogConv:Ie,remoteDialogActiveConv:se,ides:m,sendDaemonCommand:e,updateRouteChats:S,setToasts:p,setClearedTabs:te,setSearchParams:c}),Al=o.useMemo(()=>we,[we]),or=W&&de==="chat",Ml=o.useMemo(()=>me.filter(We=>Wa(X,We)),[me,X]),Ya=o.useCallback(We=>{const kt=new URLSearchParams(i);kt.set("activeTab",We),c(kt,{replace:!0})},[i,c]),{trackPendingLaunch:Tl}=nh({ides:m,conversations:me,onOpenSession:Ya}),{handleBrowseMachineDirectory:Ll,handleSaveMachineWorkspace:Rl,handleLaunchMachineIde:Pl,handleLaunchMachineProvider:_l,handleListMachineSavedSessions:Dl,setActiveCliViewMode:El}=ah({sendDaemonCommand:e,trackPendingLaunch:Tl,onOpenSession:Ya,activeConv:He,ides:m,setCliViewModeOverrides:Q});fp({visibleConversations:we,clearedTabs:ue,setClearedTabs:te,setActionLogs:z}),kp({ides:m,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Ke});const{isRefreshingHistory:$l,handleRefreshHistory:Bl}=Uc({sendDaemonCommand:e,activeConv:He,chats:(to=m.find(We=>We.id===(He==null?void 0:He.routeId)))==null?void 0:to.chats,updateRouteChats:S,setToasts:p,setClearedTabs:te});Bp({urlActiveTab:W&&!or?l:null,conversations:me,resolveConversationBySessionId:Ae,normalizedGroupAssignments:st,hasHydratedStoredLayout:W&&!or?J:!0,hydrateStoredLayout:W&&!or?be:()=>{},focusConversationTab:he,setSearchParams:c,historyModalOpen:pe,activeConv:He,isRefreshingHistory:$l,ides:m,handleRefreshHistory:Bl});const Kl=o.useMemo(()=>!He||!Je(He)||qe(He)?null:Ts(He),[He]),{versionMismatchDaemons:Ol,hasRequiredVersionDaemons:Xa,appVersion:Wl,versionBannerDismissed:Hl,setVersionBannerDismissed:Fl,upgradingDaemons:Ul,handleBannerUpgrade:zl}=Up({ides:m,sendDaemonCommand:e}),Ja=o.useCallback(We=>{H(We),vt(We)},[vt,H]),Vl=o.useCallback(We=>{ae(We)},[ae]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[s.jsx(af,{terminalBackend:re,isStandalone:xe,machineLabel:le,machineKey:oe}),(!Hl||Xa)&&s.jsx(gx,{daemons:Ol,targetVersion:Wl,required:Xa,upgradingDaemons:Ul,onUpgrade:zl,onDismiss:()=>Fl(!0)}),s.jsx(ux,{showMobileChatMode:or,isMobile:W,activeConv:He,wsStatus:N,isConnected:T,onOpenHistory:We=>{We&&ke(We),Re()},onOpenRemote:Oe,onStopCli:Pe,activeCliViewMode:Kl,onSetActiveCliViewMode:El,mobileChatConversations:Al,ides:m,actionLogs:ve,sendDaemonCommand:e,setActionLogs:z,setCliViewModeOverrides:Q,isStandalone:xe,initialDataLoaded:w,userName:h.userName,requestedMobileTabKey:ie,onRequestedMobileTabConsumed:Se,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:nt,isSplitMode:Z,numGroups:yt,groupSizes:B,groupedConvs:Le,clearedTabs:ue,focusedGroup:D,focusGroup:I,moveTabToGroup:De,splitTabRelative:ft,closeGroup:et,handleResizeStart:Tt,groupActiveTabIds:P,setGroupActiveTab:V,groupTabOrders:L,setGroupTabOrder:G,toggleHiddenTab:We=>A(Fe.get(We)||{tabKey:We}),visibleConversations:we,hiddenConversations:Ml,requestedDesktopTabKey:q,onRequestedDesktopTabConsumed:Se,onDesktopActiveTabChange:U,onRequestScrollToBottom:$,onHideConversation:Vl,onShowHiddenConversation:Ja,onShowAllHiddenConversations:ce,scrollToBottomRequest:O,machineEntries:fe,layoutProfile:k,onBrowseMachineDirectory:Ll,onSaveMachineWorkspace:Rl,onLaunchMachineIde:Pl,onLaunchMachineProvider:_l,onListMachineSavedSessions:Dl,notifications:ot,notificationUnreadCount:it,liveSessionInboxState:ze,onMarkNotificationRead:dt,onMarkNotificationUnread:ut,onDeleteNotification:mt}),s.jsx("style",{children:`
|
|
56
|
+
`})]})}function Sx({hasExtensions:e,ideName:t,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:t}),n.map(i=>{const c=r===i.tabKey,l=i.status==="waiting_approval",d=i.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${c?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(i.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),i.title,l&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},i.tabKey)})]}):null}function Nx({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,c]=o.useState(()=>a||"native"),l=o.useMemo(()=>Sc(t),[t]),d=o.useMemo(()=>e?Ba(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),f=o.useMemo(()=>d.find(p=>p.streamSource==="native"),[d]),u=o.useMemo(()=>d.filter(p=>p.streamSource==="agent-stream"),[d]),x=o.useMemo(()=>e?_t(d,e.id):null,[d,e]);o.useEffect(()=>{a&&c(a)},[a]),o.useEffect(()=>{if(a||!x)return;const p=x.streamSource==="native"?"native":x.tabKey;!p||i===p||i==="native"&&c(p)},[i,x,a]),o.useEffect(()=>{var p;i!=="native"&&(u.some(h=>h.tabKey===i)||c(((p=u[0])==null?void 0:p.tabKey)||"native"))},[i,u]),o.useEffect(()=>{i==="native"&&(f||u[0]&&c(u[0].tabKey))},[i,f,u]);const m=o.useMemo(()=>i==="native"&&f?f:u.find(p=>p.tabKey===i)||x||f||u[0],[i,f,x,u]),v=o.useMemo(()=>u.map(p=>({tabKey:p.tabKey,title:bc(p)||n,status:p.status})),[u,n]),S=o.useCallback(p=>{if(p)return d.find(h=>Zn(h,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[d]);return{activeChatTab:i,setActiveChatTab:c,activeConv:m,conversations:d,extensionTabs:v,hasExtensions:v.length>0,resolveConversationByTarget:S}}function Cx({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:i,setActionLogs:c,isStandalone:l,userName:d,onOpenHistory:f,onConversationChange:u,onClose:x}){const[m,v]=o.useState("split"),[S,p]=o.useState(()=>Vt(e)?"native":e.tabKey),h=o.useRef(null),j=o.useMemo(()=>t||r.find(R=>R.id===e.routeId),[e.routeId,t,r]),b=o.useMemo(()=>tt((j==null?void 0:j.type)||""),[j==null?void 0:j.type]),{conversations:N,extensionTabs:T,hasExtensions:y}=Nx({ideData:j,allIdes:r,connectionStates:n,ideName:b||"IDE",preferredTabKey:Vt(e)?void 0:e.tabKey}),C=o.useMemo(()=>j?_t(N,j.id):null,[j,N]);o.useEffect(()=>{const R=h.current,G={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(h.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 k=o.useMemo(()=>S==="native"?N.find(R=>R.streamSource==="native")||e:N.find(R=>R.tabKey===S)||e,[e,N,S]),w=Bc(k),g=o.useMemo(()=>w.status||w.modalMessage||w.modalButtons?{...k,...w.status?{status:w.status}:{},...w.modalMessage!==void 0?{modalMessage:w.modalMessage}:{},...w.modalButtons!==void 0?{modalButtons:w.modalButtons}:{}}:k,[k,w]),D=Rs(g),A=nn({sendDaemonCommand:i,activeConv:g,setActionLogs:c,isStandalone:l}),{connScreenshot:I,screenshotUsage:P,handleRemoteAction:O}=nl({doId:D,targetSessionId:rc(g),connState:g.connectionState||"new",viewMode:m}),V=o.useMemo(()=>a.filter(R=>R.routeId===g.tabKey),[a,g.tabKey]);o.useEffect(()=>{u==null||u(g)},[g,u]),o.useEffect(()=>{const R=G=>{G.key==="Escape"&&x()};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[x]);const L=o.useCallback(R=>{R.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:x,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:L,children:[s.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Nt,{size:16})}),s.jsx("span",{className:"truncate",children:Sa(k)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:x,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(R=>{const G=m===R;return s.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:()=>v(R),title:R==="split"?"Split view":"Remote only",children:R==="split"?s.jsx(Bd,{size:15}):s.jsx(Nt,{size:15})},R)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>f(k),title:"Chat History",children:[s.jsx(ba,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:x,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${m==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[m!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${m==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(Sx,{hasExtensions:y,ideName:b||"IDE",activeChatTab:S,extensionTabs:T,onSelectTab:p}),s.jsx(Hi,{activeConv:g,onModalButton:A.handleModalButton}),s.jsx(na,{activeConv:g,ideEntry:j,showMetaChips:!1,handleSendChat:A.handleSendChat,isSendingChat:A.isSendingChat,sendFeedbackMessage:A.sendFeedbackMessage,handleFocusAgent:A.handleFocusAgent,isFocusingAgent:A.isFocusingAgent,actionLogs:V,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${m==="split"?"order-1 md:order-2":""}`,children:s.jsx(Oi,{addLog:()=>{},connState:g.connectionState||"new",connScreenshot:I,screenshotUsage:P,transportType:g.transport,onAction:O})})]})]})})}function Ix({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=mf(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[s.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",i,"?"]}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:t?"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.":"This provider does not support graceful stop. Force Stop will end the runtime immediately."})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),s.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Force Stop"}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function Mx({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(xf,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.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}),t.conversation&&s.jsx(Cx,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),r.open&&r.targetConv&&(Qe(r.targetConv)||Xe(r.targetConv))&&s.jsx(Ix,{activeConv:r.targetConv,canSaveAndStop:Qe(r.targetConv)&&!Xe(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(kc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&s.jsx(kx,{onClose:i.onClose})]})}function Ax({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:i}){return e.length===0?null:s.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(sr,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[r?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(c=>{const l=At(c,{fallbackId:c.id}),d=n[c.id],f=c.version||c.daemonVersion||"unknown",u=c.versionUpdateRequired===!0;return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:l}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",f]}),u&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:u?"Update now":"Upgrade"})]},c.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:s.jsx(vt,{size:16})})]})}function Tx(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Lx(e){const t=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:r===e.autoReadKey?r:null}:r===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:r}:{shouldSchedule:!0,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!r,nextPendingKey:null}}function Rx(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&t&&t!==r),autoReadKey:i,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Px(e){const t=e.machine;return typeof(t==null?void 0:t.cpus)!="number"||typeof(t==null?void 0:t.totalMem)!="number"||typeof(t==null?void 0:t.arch)!="string"||typeof(t==null?void 0:t.release)!="string"}function _x(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>Px(t)).map(t=>t.id)}}function Dx(){var eo,to,so,ro;const{sendCommand:e}=wt(),t=ar(),r=$c(),n=pa(),a=As(),[i,c]=ad(),l=i.get("activeTab"),d=((eo=n.state)==null?void 0:eo.openRemoteForTabKey)||null,f=((to=n.state)==null?void 0:to.openMachineId)||null,u=((so=n.state)==null?void 0:so.mobileSection)||null,x=fc(),m=x.ides||[],v=x.initialLoaded??!0,{updateRouteChats:S,setToasts:p}=x,[h,j]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),b=x.toasts||[],N=x.wsStatus||"connected",T=x.isConnected??!0,y=x.connectionStates||{},C=x.showReconnected||!1,{layoutProfile:k,groupAssignments:w,updateGroupAssignments:g,focusedGroup:D,updateFocusedGroup:A,focusGroup:I,groupActiveTabIds:P,updateGroupActiveTabIds:O,setGroupActiveTab:V,groupTabOrders:L,updateGroupTabOrders:R,setGroupTabOrder:G,groupSizes:K,updateGroupSizes:E,isMobile:W,hasHydratedStoredLayout:J,hydrateStoredLayout:be,focusConversationTab:xe}=Gp(),[de,ye]=o.useState(()=>Ha());o.useEffect(()=>up(ye),[]);const ge=o.useMemo(()=>Tx({isMobile:W,mobileViewMode:de}),[W,de]),[ve,z]=o.useState([]),[F,Q]=o.useState({}),[ue,te]=o.useState({});rr("Dashboard",{ideCount:m.length,toastCount:b.length,focusedGroup:D,groupCount:Object.keys(w).length,actionLogCount:ve.length});const fe=o.useMemo(()=>m.filter(Oe=>Oe.type==="adhdev-daemon").sort(wa),[m]),re=fe[0],pe=!!re;o.useEffect(()=>{const{metadataDaemonIds:Oe,runtimeDaemonIds:jt}=_x(fe);for(const Dt of Oe)t(Dt,{minFreshMs:3e4}).catch(()=>{});for(const Dt of jt)r(Dt,{minFreshMs:3e4}).catch(()=>{})},[t,r,fe]);const oe=(re==null?void 0:re.terminalBackend)||null,le=re?At(re,{fallbackId:re.id}):null,ae=(re==null?void 0:re.id)||null,Y=o.useMemo(()=>jp(m,F),[m,F]),{hiddenTabs:X,hideTarget:ne,toggleTarget:M,showTarget:H,showAllTabs:ce}=wp(),{conversations:me,visibleConversations:je,visibleTabKeys:_e,resolveConversationBySessionId:Me,resolveConversationByTarget:Be}=Rp({ides:Y,connectionStates:y,clearedTabs:ue,hiddenTabs:X}),We=o.useMemo(()=>new Map(me.map(Oe=>[Oe.tabKey,Oe])),[me]),Fe=qm(je,ge),nt=o.useMemo(()=>Po(me,Fe),[me,Fe]),Ze=o.useMemo(()=>Po(je,Fe),[je,Fe]);o.useEffect(()=>{Object.keys(F).length!==0&&Q(Oe=>kp(Oe,m))},[m,F]);const it=o.useMemo(()=>vu(m),[m]),{notifications:dt,unreadCount:mt}=ch({conversations:nt,liveSessionInboxState:it}),{handleMarkDashboardNotificationRead:at,handleMarkDashboardNotificationUnread:ut,handleDeleteDashboardNotification:Ce}=lh({notifications:dt,sendDaemonCommand:e}),$e=o.useRef(null),Ue=o.useRef(null),Ve=o.useRef(null),qe=o.useRef(null),Je=o.useRef(null),{containerRef:Z,normalizedGroupAssignments:Le,numGroups:De,isSplitMode:st,groupedConvs:Ct,moveTabToGroup:ft,closeGroup:Tt,handleResizeStart:yt,splitTabRelative:B}=eh({groupAssignments:w,updateGroupAssignments:g,updateFocusedGroup:A,updateGroupActiveTabIds:O,updateGroupTabOrders:R,groupSizes:K,updateGroupSizes:E,isMobile:W,visibleConversations:Ze,visibleTabKeys:_e}),{activeConv:$,openDesktopConversation:U,requestScrollToBottom:q,scrollToBottomRequest:ie,setDesktopActiveTab:ke}=yh({isMobile:W,conversations:nt,visibleConversations:Ze,groupActiveTabIds:P,focusedGroup:D,groupedConvs:Ct,setSearchParams:c});o.useEffect(()=>{const Oe=()=>{Ve.current&&(clearTimeout(Ve.current),Ve.current=null),qe.current&&(clearTimeout(qe.current),qe.current=null),Je.current&&(document.removeEventListener("visibilitychange",Je.current),Je.current=null),Ue.current=null};if(W){Oe(),$e.current=null;return}if(!($!=null&&$.sessionId)){Oe(),$e.current=null;return}const jt=Or($,it),Dt=Rx({tabKey:$.tabKey,historySessionId:nr($)||"",lastMessageHash:$.lastMessageHash||"",lastMessageAt:Number($.lastMessageAt||0),timestamp:es($),liveState:jt}),cr=Dt.autoReadKey,lr=Lx({autoReadKey:cr,shouldMarkSeen:Dt.shouldMarkSeen,completedKey:$e.current,pendingKey:Ue.current});if(!Dt.shouldMarkSeen){lr.shouldCancelPending&&Oe(),$e.current=cr;return}if(!lr.shouldSchedule)return;lr.shouldCancelPending&&Oe();const no=()=>{if(document.visibilityState!=="visible"||$e.current===cr)return;$e.current=cr,Ue.current=null,Ve.current=null,qe.current=null,Je.current&&(document.removeEventListener("visibilitychange",Je.current),Je.current=null);const dr=Dt.readAt;e($.daemonId||$.routeId,"mark_session_seen",{sessionId:$.sessionId,seenAt:dr}).catch(()=>{})};if(Ue.current=lr.nextPendingKey,document.visibilityState==="visible"){Ve.current=setTimeout(no,1500);const dr=()=>{document.visibilityState!=="visible"&&Ve.current&&(clearTimeout(Ve.current),Ve.current=null)};Je.current=dr,document.addEventListener("visibilitychange",dr);return}const ao=()=>{document.visibilityState==="visible"&&(qe.current&&clearTimeout(qe.current),qe.current=setTimeout(no,800),Je.current&&(document.removeEventListener("visibilitychange",Je.current),Je.current=null))};Je.current=ao,document.addEventListener("visibilitychange",ao)},[$,W,it,e]),o.useEffect(()=>()=>{Ve.current&&clearTimeout(Ve.current),qe.current&&clearTimeout(qe.current),Je.current&&document.removeEventListener("visibilitychange",Je.current)},[]);const{requestedDesktopTabKey:Ie,requestedMobileTabKey:Ne,consumeRequestedActiveTab:se}=Pp({isMobile:W,urlActiveTab:l,resolveConversationBySessionId:Me,setSearchParams:c}),{remoteDialogConv:we,remoteDialogIdeEntry:Ke,remoteDialogActiveConv:He,setRemoteDialogActiveConv:Ye,openRemoteDialog:ze,closeRemoteDialog:Pe,cliStopDialogOpen:_,cliStopTargetConv:ee,requestCliStop:he,cancelCliStop:Re,confirmCliStop:Se}=jh({isMobile:W,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:Ie,conversations:me,ides:m,resolveConversationByTarget:Be,activeConv:$,sendDaemonCommand:e}),{historyModalOpen:Ae,openHistoryModal:Te,closeHistoryModal:pt,historyTargetConv:ct,isSavedSessionHistoryTarget:Ot,isHistoryCreatingChat:kl,isHistoryRefreshingHistory:Sl,handleHistorySwitchSession:Nl,handleHistoryNewChat:Cl,handleHistoryRefresh:Il,savedHistorySessions:Ml,savedHistoryFilters:Al,setSavedHistoryFilters:Tl,isSavedHistoryLoading:Ll,resumingSavedHistorySessionId:Rl,handleRefreshSavedHistory:Pl,handleResumeSavedHistorySession:_l}=vh({activeConv:$,remoteDialogConv:we,remoteDialogActiveConv:He,ides:m,sendDaemonCommand:e,updateRouteChats:S,setToasts:p,setClearedTabs:te,setSearchParams:c}),Dl=o.useMemo(()=>Ze,[Ze]),ir=W&&de==="chat",El=o.useMemo(()=>nt.filter(Oe=>Fa(X,Oe)),[nt,X]),Ja=o.useCallback(Oe=>{const jt=new URLSearchParams(i);jt.set("activeTab",Oe),c(jt,{replace:!0})},[i,c]),{trackPendingLaunch:$l}=hh({ides:m,conversations:me,onOpenSession:Ja}),{handleBrowseMachineDirectory:Bl,handleSaveMachineWorkspace:Kl,handleLaunchMachineIde:Ol,handleLaunchMachineProvider:Wl,handleListMachineSavedSessions:Hl,setActiveCliViewMode:Fl}=xh({sendDaemonCommand:e,trackPendingLaunch:$l,onOpenSession:Ja,activeConv:$,ides:m,setCliViewModeOverrides:Q});Sp({visibleConversations:je,clearedTabs:ue,setClearedTabs:te,setActionLogs:z}),_p({ides:m,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Be});const{isRefreshingHistory:Ul,handleRefreshHistory:zl}=qc({sendDaemonCommand:e,activeConv:$,chats:(ro=m.find(Oe=>Oe.id===($==null?void 0:$.routeId)))==null?void 0:ro.chats,updateRouteChats:S,setToasts:p,setClearedTabs:te});Yp({urlActiveTab:W&&!ir?l:null,conversations:me,resolveConversationBySessionId:Me,normalizedGroupAssignments:Le,hasHydratedStoredLayout:W&&!ir?J:!0,hydrateStoredLayout:W&&!ir?be:()=>{},focusConversationTab:xe,setSearchParams:c,historyModalOpen:Ae,activeConv:$,isRefreshingHistory:Ul,ides:m,handleRefreshHistory:zl});const Vl=o.useMemo(()=>!$||!Qe($)||Xe($)?null:Ls($),[$]),{versionMismatchDaemons:Gl,hasRequiredVersionDaemons:Qa,appVersion:ql,versionBannerDismissed:Yl,setVersionBannerDismissed:Xl,upgradingDaemons:Jl,handleBannerUpgrade:Ql}=th({ides:m,sendDaemonCommand:e}),Za=o.useCallback(Oe=>{H(Oe),U(Oe)},[U,H]),Zl=o.useCallback(Oe=>{ne(Oe)},[ne]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[s.jsx(bf,{terminalBackend:oe,isStandalone:pe,machineLabel:le,machineKey:ae}),(!Yl||Qa)&&s.jsx(Ax,{daemons:Gl,targetVersion:ql,required:Qa,upgradingDaemons:Jl,onUpgrade:Ql,onDismiss:()=>Xl(!0)}),s.jsx(jx,{showMobileChatMode:ir,isMobile:W,activeConv:$,wsStatus:N,isConnected:T,onOpenHistory:Oe=>{Oe&&Ye(Oe),Te()},onOpenRemote:ze,onStopCli:he,activeCliViewMode:Vl,onSetActiveCliViewMode:Fl,mobileChatConversations:Dl,ides:m,actionLogs:ve,sendDaemonCommand:e,setActionLogs:z,setCliViewModeOverrides:Q,isStandalone:pe,initialDataLoaded:v,userName:x.userName,requestedMobileTabKey:Ne,onRequestedMobileTabConsumed:se,requestedMachineId:f,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:u,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Z,isSplitMode:st,numGroups:De,groupSizes:K,groupedConvs:Ct,clearedTabs:ue,focusedGroup:D,focusGroup:I,moveTabToGroup:ft,splitTabRelative:B,closeGroup:Tt,handleResizeStart:yt,groupActiveTabIds:P,setGroupActiveTab:V,groupTabOrders:L,setGroupTabOrder:G,toggleHiddenTab:Oe=>M(We.get(Oe)||{tabKey:Oe}),visibleConversations:Ze,hiddenConversations:El,requestedDesktopTabKey:Ie,onRequestedDesktopTabConsumed:se,onDesktopActiveTabChange:ke,onRequestScrollToBottom:q,onHideConversation:Zl,onShowHiddenConversation:Za,onShowAllHiddenConversations:ce,scrollToBottomRequest:ie,machineEntries:fe,layoutProfile:k,onBrowseMachineDirectory:Bl,onSaveMachineWorkspace:Kl,onLaunchMachineIde:Ol,onLaunchMachineProvider:Wl,onListMachineSavedSessions:Hl,notifications:dt,notificationUnreadCount:mt,liveSessionInboxState:it,onMarkNotificationRead:at,onMarkNotificationUnread:ut,onDeleteNotification:Ce}),s.jsx("style",{children:`
|
|
57
57
|
body { overflow: hidden; overscroll-behavior: none; }
|
|
58
|
-
`}),s.jsx(
|
|
59
|
-
This will terminate the process.`))try{const J=await r(e,"stop_cli",{cliType:
|
|
60
|
-
This will disconnect CDP and optionally kill the process.`))try{const E=await r(
|
|
61
|
-
✅ Auto-fix completed!`]),j.current&&clearInterval(j.current))}catch{}},3e3)},[e,t.type,r,a]),C=async()=>{if(
|
|
62
|
-
⚠️ Auto-fix cancelled.`]),i("done"),j.current&&clearInterval(j.current)}catch{}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:v=>v.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:t.icon||"🔧"}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",t.displayName]}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),s.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),s.jsx("div",{className:"flex gap-2",children:Tx.map(v=>s.jsxs("button",{onClick:()=>l(v.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===v.value?v.color+"66":"var(--border-subtle)",background:c===v.value?v.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===v.value?v.color:"var(--text-primary)"},children:v.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:v.desc})]},v.value))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:N,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),s.jsx("button",{onClick:T,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:ri.map(v=>s.jsxs("button",{onClick:()=>b(v),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(v)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(v)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(v)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(v)?"☑ ":"☐ ",v]},v))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",s.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:d,onChange:v=>h(v.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[m.map((v,g)=>s.jsx("div",{className:v.startsWith("✅")?"text-green-400":"",style:v.startsWith("❌")||v.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:v},g)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:x})]}),S&&s.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:S})]})]}),s.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[s.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&u.length>0&&`${u.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),s.jsxs("div",{className:"flex gap-2",children:[a==="config"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick: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"&&s.jsx("button",{onClick:k,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{i("config"),w([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Rx({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var y;const i=t.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,w]=o.useState(!1),[S,p]=o.useState(""),[x,j]=o.useState(!1),b=C=>{const k=C.toLowerCase().replace(/[^a-z0-9-]/g,"");f(k),(!d||d===N(u))&&h(N(k))},N=C=>C.split("-").map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(" "),T=async()=>{if(!(!u||!d||!c)){w(!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?(j(!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")}w(!1)}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:C=>C.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:x?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:u})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",u,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",u]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(C=>s.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:[s.jsx("div",{className:"text-lg",children:C.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===C.type?"#a78bfa":"var(--text-secondary)"},children:C.displayName})]},C.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:u,onChange:C=>b(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"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",u||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:d,onChange: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&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:S})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:x?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:T,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 Px({machineId:e,providers:t,sendDaemonCommand:r}){var M;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),[w,S]=o.useState(!1),[p,x]=o.useState(null),[j,b]=o.useState("normal"),[N,T]=o.useState(""),[y,C]=o.useState(!1),k=o.useCallback(async()=>{if(e)try{const I=await r(e,"get_provider_source_config",{}),P=si(I);P&&(x(P),b(P.sourceMode),T(P.explicitProviderDir||""))}catch{}},[e,r]),v=o.useCallback(async()=>{if(e){c(!0);try{const I=await r(e,"get_provider_settings",{}),P=Ix(I);if(P){const K=Ax(P,t);K.sort((V,L)=>V.category.localeCompare(L.category)||V.displayName.localeCompare(L.displayName)),a(K)}}catch{}c(!1)}},[e,t,r]);o.useEffect(()=>{n.length===0&&v(),p||k()},[]);const g=async(I,P,K)=>{u(`${I}.${P}`),a(V=>V.map(L=>L.type===I?{...L,values:{...L.values,[P]:K}}:L));try{const V=await r(e,"set_provider_setting",{providerType:I,key:P,value:K});V!=null&&V.success||v()}catch{v()}u(null)},D=async()=>{C(!0);try{const I=await r(e,"set_provider_source_config",{providerSourceMode:j,providerDir:Mx(N)}),P=si(I);P?(x(P),b(P.sourceMode),T(P.explicitProviderDir||"")):await k(),await v()}catch{await k()}C(!1)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between items-center mb-4",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(I=>s.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))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>S(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),s.jsx("button",{onClick:v,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Existing running sessions may need restart."})]}),s.jsx("button",{onClick:k,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),s.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),s.jsxs("select",{value:j,onChange:I=>b(I.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),s.jsx("input",{type:"text",value:N,onChange:I=>T(I.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void D(),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"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((M=p==null?void 0:p.providerRoots)==null?void 0:M.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 K=[...P.entries()].filter(([,L])=>L.total===I.length);if(K.length===0)return null;const V=async(L,R)=>{for(const G of I)await g(G.type,L,R)};return s.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[s.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",f.toUpperCase()," providers (",I.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:K.map(([L,R])=>{const G=R.onCount===R.total,B=R.onCount===0;return s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:R.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",R.onCount,"/",R.total,")"]}),s.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"}),s.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?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):s.jsx("div",{className:"flex flex-col gap-2",children:n.filter(I=>f==="all"||I.category===f).map(I=>s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[s.jsx("span",{className:"text-lg",children:I.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:I.displayName}),s.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"&&s.jsx("button",{onClick:()=>m(t.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"})]}),s.jsx("div",{className:"flex flex-col gap-2",children:I.schema.map(P=>s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[P.label||P.key,l===`${I.type}.${P.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),P.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:P.description})]}),s.jsx("div",{className:"shrink-0",children:P.type==="boolean"?s.jsx("button",{onClick:()=>g(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:s.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:I.values[P.key]??P.default?21:3}})}):P.type==="number"?s.jsx("input",{type:"number",value:Number(I.values[P.key]??P.default??0)||0,min:P.min,max:P.max,onChange:K=>{const V=parseInt(K.target.value)||0;P.min!==void 0&&V<P.min||P.max!==void 0&&V>P.max||g(I.type,P.key,V)},className:"machine-input w-20 text-center text-[11px]"}):P.type==="select"&&P.options?s.jsx("select",{value:String(I.values[P.key]??P.default??""),onChange:K=>g(I.type,P.key,K.target.value),className:"machine-input text-[11px]",children:P.options.map(K=>s.jsx("option",{value:K,children:K},K))}):s.jsx("input",{type:"text",value:String(I.values[P.key]??P.default??""),onBlur:K=>g(I.type,P.key,K.target.value),className:"machine-input w-[120px] text-[11px]"})})]},P.key))})]},I.type))}),h&&s.jsx(Lx,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>m(null)}),w&&s.jsx(Rx,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>S(!1),onCreated:()=>{S(!1),v()}})]})}const _x=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Dx({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function Ex(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function $x(e){return e.trim().toLowerCase()}function cn(e,t){const r=$x(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Ga(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Qs(e,t=220){const r=Ga(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function Bx(e){const t=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(t))return{kind:t.length>0?"structured":"empty",entries:t.map(r=>{const n=r;return{timestamp:Number(n.ts)||0,level:n.level||"info",message:`[${String(n.category||"daemon")}] ${String(n.message||"")}`.trim()}}),rawText:""};if(typeof t=="string"){const r=t.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function fl(e,t){return e.filter(r=>cn([r.level,r.message],t))}function Kx(e,t){return e.split(`
|
|
63
|
-
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>cn([r],t))}function
|
|
58
|
+
`}),s.jsx(Mx,{historyModal:{open:Ae,targetConv:ct,ides:m,isCreatingChat:kl,isRefreshingHistory:Ot?!1:Sl,savedSessions:Ml,savedHistoryFilters:Al,onSavedHistoryFiltersChange:Tl,isSavedSessionsLoading:Ll,isResumingSavedSessionId:Rl,onClose:pt,onNewChat:Cl,onSwitchSession:Nl,onRefreshHistory:Ot?Pl:Il,onResumeSavedSession:_l},remoteDialog:{conversation:we,ideEntry:Ke,ides:m,connectionStates:y,actionLogs:ve,sendDaemonCommand:e,setActionLogs:z,isStandalone:pe,userName:x.userName,onOpenHistory:Oe=>{Oe&&Ye(Oe),Te()},onConversationChange:Ye,onClose:Pe},cliStopDialog:{open:_,targetConv:ee,onCancel:Re,onStopNow:async()=>{await Se("hard")},onSaveAndStop:async()=>{await Se("save")}},connectionBanner:{wsStatus:N,showReconnected:C,loginUrl:x.connectionLoginUrl,onReconnect:x.retryServerConnection},toastOverlay:{toasts:b,onDismiss:Oe=>p(jt=>jt.filter(Dt=>Dt.id!==Oe)),onClick:Oe=>{if(Oe.targetKey){const jt=Be(Oe.targetKey);jt&&(xe(jt.tabKey,Le),Za(jt),q(jt.tabKey,"toast-open"))}}},onboarding:{open:h,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}j(!1)}}})]})}function Ex({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,d]=o.useState(null),[f,u]=o.useState(null),[x,m]=o.useState(!1),[v,S]=o.useState(null),[p,h]=o.useState(!1),[j,b]=o.useState(""),N=o.useRef(null),T=o.useCallback(K=>{N.current=K},[]),y=o.useCallback((K,E,W=!1)=>{c(J=>[...J.slice(-100),{timestamp:Date.now(),level:K,message:E}]),setTimeout(()=>{var J;return(J=a.current)==null?void 0:J.scrollIntoView({behavior:"smooth"})},100),W&<.showToast(E,K==="error"||K==="warn"?"warning":"success")},[a]),C=o.useCallback(K=>{const E=K instanceof Error?K.message:String(K||"");return E.includes("P2P command timeout")||E.includes("P2P not connected")||E.includes("P2P not available")},[]),k=o.useCallback(async(K,E)=>{var W;if(!e||l)return!1;d(K),y("info",`Launching ${tt(K)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const J={ideType:K,enableCdp:!0};(W=E==null?void 0:E.workspace)!=null&&W.trim()?J.workspace=E.workspace.trim():E!=null&&E.useDefaultWorkspace&&(J.useDefaultWorkspace=!0);const be=await r(e,"launch_ide",J);return y(be!=null&&be.success?"info":"error",be!=null&&be.success?`${tt(K)} launched`:`Failed: ${be==null?void 0:be.error}`,!0),!!(be!=null&&be.success)}catch(J){return y("error",`Launch error: ${J.message}`,!0),!1}finally{d(null)}},[e,l,y,r]),w=o.useCallback(async K=>{if(!e)return{success:!1};const{cliType:E,dir:W,workspaceId:J,useDefaultWorkspace:be,useHome:xe,argsStr:de,model:ye,resumeSessionId:ge}=K;if(!E)return y("warn","Select a CLI or ACP provider first",!0),{success:!1};const ve=de?de.split(/\s+/).filter(Boolean):void 0,z=(W==null?void 0:W.trim())||(J?"(saved id)":be?"(default workspace)":xe?"(home)":"");y("info",`Launching ${E}${z?` in ${z}`:""}${ye?` (model: ${ye})`:""}...`),u(E);try{const F={cliType:E,cliArgs:ve,initialModel:ye||void 0};W!=null&&W.trim()?F.dir=W.trim():J?F.workspaceId=J:be?F.useDefaultWorkspace=!0:xe&&(F.useHome=!0),ge&&(F.resumeSessionId=ge);const Q=await r(e,"launch_cli",F),ue=(Q==null?void 0:Q.result)||Q;return Q!=null&&Q.success?(y("info",`${E} launched`,!0),(ue==null?void 0:ue.launchSource)==="home"?y("info","📂 Running in home directory (explicit choice)"):(ue==null?void 0:ue.launchSource)==="defaultWorkspace"&&y("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ue==null?void 0:ue.sessionId}):(y("error",`Failed: ${(Q==null?void 0:Q.error)||(ue==null?void 0:ue.error)}`,!0),(Q==null?void 0:Q.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&S({cliType:E,argsStr:de,model:ye}),{success:!1,sessionId:ue==null?void 0:ue.sessionId})}catch(F){return C(F)?(y("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(y("error",`Launch error: ${F.message}`,!0),{success:!1})}finally{u(null)}},[e,y,C,r]),g=o.useCallback(async(K,E,W,J)=>e?K?E.trim()?w({cliType:K,dir:E,argsStr:W,model:J}):(S({cliType:K,argsStr:W,model:J}),{success:!1}):(y("warn","Select a provider",!0),{success:!1}):{success:!1},[e,y,w]),D=o.useCallback(async(K,E,W)=>{if(e&&window.confirm(`Stop ${K}?
|
|
59
|
+
This will terminate the process.`))try{const J=await r(e,"stop_cli",{cliType:K,dir:E,targetSessionId:W});J!=null&&J.success?y("info",`${K} 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 K=>{try{await r(K.daemonId,"restart_ide",{ideType:K.type}),y("info",`${tt(K.type)} restart initiated`,!0)}catch(E){y("error",`Restart failed: ${E.message}`,!0)}},[y,r]),I=o.useCallback(async K=>{if(window.confirm(`Stop ${tt(K.type)}?
|
|
60
|
+
This will disconnect CDP and optionally kill the process.`))try{const E=await r(K.daemonId,"stop_ide",{ideType:K.type,killProcess:!0});E!=null&&E.success?y("info",`${tt(K.type)} stopped`,!0):y("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){y("error",`Stop failed: ${E.message}`,!0)}},[y,r]),P=o.useCallback(async()=>{if(e)try{const K=await r(e,"detect_ides",{});y("info",`Found ${((K==null?void 0:K.result)||[]).length} IDE(s)`,!0)}catch(K){y("error",`Detection failed: ${K.message}`,!0)}},[e,y,r]),O=o.useCallback(async K=>{if(!e||!K.trim())return!1;m(!0);try{const E=await r(e,"workspace_add",{path:K.trim()});return E!=null&&E.success?(y("info",`Workspace added: ${K.trim()}`),!0):(y("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return y("error",E.message),!1}finally{m(!1)}},[e,y,r]),V=o.useCallback(async K=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){m(!0);try{const E=await r(e,"workspace_remove",{id:K});E!=null&&E.success?y("info","Workspace removed",!0):y("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){y("error",E.message,!0)}finally{m(!1)}}},[e,y,r]),L=o.useCallback(async K=>{var E;if(e){m(!0);try{const W=await r(e,"workspace_set_default",K===null?{clear:!0}:{id:K});if(W!=null&&W.success){y("info",K?"Default workspace updated":"Default workspace cleared",!0);const J=typeof W.defaultWorkspacePath=="string"?W.defaultWorkspacePath:"";J&&((E=N.current)==null||E.call(N,J))}else y("error",(W==null?void 0:W.error)||"workspace_set_default failed",!0)}catch(W){y("error",W.message,!0)}finally{m(!1)}}},[e,y,r]),R=o.useCallback(async K=>{var W;if(!e||!K.trim())return;const E=K.trim();m(!0);try{const J=await r(e,"workspace_set_default",{path:E});J!=null&&J.success?(y("info","Default workspace set from history"),(W=N.current)==null||W.call(N,E)):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:j}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:j})}catch(K){y("warn",`Live nickname updated, but account sync failed: ${K.message}`)}y("info",`Nickname set to "${j||"(cleared)"}"`),h(!1)}catch(K){y("error",`Failed: ${K.message}`)}},[e,j,t,y,n,r]);return{logs:i,launchingIde:l,launchingAgentType:f,workspaceBusy:x,launchPick:v,setLaunchPick:S,editingNickname:p,setEditingNickname:h,nicknameInput:j,setNicknameInput:b,addLog:y,handleLaunchIde:k,runLaunchCliCore:w,handleLaunchCli:g,handleStopCli:D,handleRestartIde:A,handleStopIde:I,handleDetectIdes:P,handleWorkspaceAdd:O,handleWorkspaceRemove:V,handleWorkspaceSetDefault:L,handleWorkspaceResumePath:R,handleSaveNickname:G,setOnDefaultWorkspaceChanged:T}}function $x({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var A;const{workspaceBusy:l,handleWorkspaceAdd:d,handleWorkspaceRemove:f,handleWorkspaceSetDefault:u}=i,[x,m]=o.useState(!1),[v,S]=o.useState(""),[p,h]=o.useState([]),[j,b]=o.useState(!1),[N,T]=o.useState(""),y=o.useCallback(async I=>{b(!0),T("");try{const P=await rn(c,e,I);S(P.path),h(P.directories)}catch(P){T(P instanceof Error?P.message:"Could not load folder")}finally{b(!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(t.platform,tn(I,t.defaultWorkspacePath,(t.workspaces||[]).map(O=>O.path)));y(P)},[a,n,r,y,t.defaultWorkspacePath,t.platform,t.workspaces]),k=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,w=t.availableMem??t.freeMem??t.totalMem,g=k&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-w)/t.totalMem*100))):0,D=((A=t.loadavg)==null?void 0:A[0])||0;return s.jsxs("div",{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[s.jsx(fr,{icon:s.jsx(_i,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?Su(t.uptime):"Waiting…"}),s.jsx(fr,{icon:s.jsx(Nt,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(fr,{icon:s.jsx(ga,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(fr,{icon:s.jsx(Od,{size:16}),label:"ACPs",value:`${a.length}`})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),s.jsxs("div",{className:"flex gap-6",children:[s.jsx(go,{value:k?Math.min(Math.round(D/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:k?`${D.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(go,{value:g,max:100,label:"Memory",color:"#3b82f6",detail:k?`${pn(t.totalMem-w)} / ${pn(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${pn(t.totalMem)} total`})]})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[s.jsx(Ns,{size:14})," Workspaces"]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),s.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:l,value:t.defaultWorkspaceId||"",onChange:I=>void u(I.target.value===""?null:I.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(I=>s.jsx("option",{value:I.id,children:I.label||I.path},I.id))]}),t.defaultWorkspacePath&&s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:t.defaultWorkspacePath,children:t.defaultWorkspacePath})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:l,onClick:C,children:"Select workspace…"}),s.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(t.workspaces||[]).length>0&&s.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(t.workspaces||[]).map(I=>s.jsxs("li",{className:"flex items-start gap-2 text-[11px] text-text-muted rounded-lg border border-border-subtle bg-bg-primary px-2.5 py-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[I.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:Zr(I.path,I.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:I.path,children:I.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void f(I.id),children:"Remove"})]},I.id))})]}),x&&s.jsx(an,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:v,directories:p,busy:j,error:N,confirmLabel:"Add workspace",onClose:()=>m(!1),onNavigate:I=>{y(I)},onConfirm:I=>{(async()=>{if(!I)return;await d(I)&&m(!1)})()}})]})}function Bx(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function Kx(e,t,r){const n=[];for(const[a,i]of Object.entries(e.settings)){const c=i;if(c.length===0)continue;const l=t.find(d=>d.type===a);n.push({type:a,displayName:(l==null?void 0:l.displayName)||a,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[a]||{}})}return n}function _n(e){if(!e||typeof e!="object")return!1;const t=e;return(t.sourceMode==="normal"||t.sourceMode==="no-upstream")&&typeof t.disableUpstream=="boolean"&&(t.explicitProviderDir===null||typeof t.explicitProviderDir=="string")&&typeof t.userDir=="string"&&typeof t.upstreamDir=="string"&&Array.isArray(t.providerRoots)}function ii(e){if(!e||typeof e!="object")return null;if(_n(e))return e;const t=e,r=t.result;return _n(r)?r:_n(t.sourceConfig)?t.sourceConfig:null}function Ox(e){const t=e.trim();return t||null}const ci=["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 Hx({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[d,f]=o.useState([]),[u,x]=o.useState(""),[m,v]=o.useState([]),[S,p]=o.useState(""),h=o.useRef(null),j=o.useRef(null),b=w=>{f(g=>g.includes(w)?g.filter(D=>D!==w):[...g,w])},N=()=>f([...ci]),T=()=>f([]);o.useEffect(()=>{var w;(w=h.current)==null||w.scrollIntoView({behavior:"smooth"})},[m]),o.useEffect(()=>()=>{j.current&&clearInterval(j.current)},[]);const y=o.useCallback(()=>{j.current&&clearInterval(j.current),j.current=setInterval(async()=>{try{const w=await r(e,"provider_auto_fix_status",{providerType:t.type});(w==null?void 0:w.running)===!1&&a==="running"&&(i("done"),v(g=>[...g,`
|
|
61
|
+
✅ Auto-fix completed!`]),j.current&&clearInterval(j.current))}catch{}},3e3)},[e,t.type,r,a]),C=async()=>{if(d.length!==0){i("running"),v(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${d.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),p("");try{const w=await r(e,"provider_auto_fix",{providerType:t.type,functions:d,agent:c,...u?{comment:u}:{}});w!=null&&w.success&&(w!=null&&w.started||w!=null&&w.running)?(v(g=>[...g,"✅ 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")}}},k=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),v(w=>[...w,`
|
|
62
|
+
⚠️ Auto-fix cancelled.`]),i("done"),j.current&&clearInterval(j.current)}catch{}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:w=>w.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:t.icon||"🔧"}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",t.displayName]}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),s.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),s.jsx("div",{className:"flex gap-2",children:Wx.map(w=>s.jsxs("button",{onClick:()=>l(w.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===w.value?w.color+"66":"var(--border-subtle)",background:c===w.value?w.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===w.value?w.color:"var(--text-primary)"},children:w.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:w.desc})]},w.value))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:N,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),s.jsx("button",{onClick:T,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:ci.map(w=>s.jsxs("button",{onClick:()=>b(w),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(w)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(w)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(w)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(w)?"☑ ":"☐ ",w]},w))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",s.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:u,onChange:w=>x(w.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[m.map((w,g)=>s.jsx("div",{className:w.startsWith("✅")?"text-green-400":"",style:w.startsWith("❌")||w.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:w},g)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:h})]}),S&&s.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:S})]})]}),s.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[s.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&d.length>0&&`${d.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),s.jsxs("div",{className:"flex gap-2",children:[a==="config"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:C,disabled:d.length===0,className:"machine-btn",style:{background:d.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:d.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:d.length>0?"#a78bfa":void 0,opacity:d.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&s.jsx("button",{onClick:k,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{i("config"),v([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Fx({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var y;const i=t.filter(C=>C.category==="ide"),[c,l]=o.useState(((y=i[0])==null?void 0:y.type)||""),[d,f]=o.useState(""),[u,x]=o.useState(""),[m,v]=o.useState(!1),[S,p]=o.useState(""),[h,j]=o.useState(!1),b=C=>{const k=C.toLowerCase().replace(/[^a-z0-9-]/g,"");f(k),(!u||u===N(d))&&x(N(k))},N=C=>C.split("-").map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(" "),T=async()=>{if(!(!d||!u||!c)){v(!0),p("");try{const C=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:c});C!=null&&C.success||C!=null&&C.created?(j(!0),a==null||a(d)):p((C==null?void 0:C.error)||"Failed to create provider")}catch(C){p((C==null?void 0:C.message)||"Connection failed")}v(!1)}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:C=>C.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:h?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:d})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(C=>s.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:[s.jsx("div",{className:"text-lg",children:C.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===C.type?"#a78bfa":"var(--text-secondary)"},children:C.displayName})]},C.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:d,onChange:C=>b(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"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:u,onChange:C=>x(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&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:S})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:h?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:T,disabled:!d||!u||m,className:"machine-btn",style:{background:d&&u?"rgba(34,197,94,0.12)":void 0,borderColor:d&&u?"rgba(34,197,94,0.3)":void 0,color:d&&u?"#86efac":void 0,opacity:!d||!u||m?.4:1},children:m?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Ux({machineId:e,providers:t,sendDaemonCommand:r}){var A;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,d]=o.useState(null),[f,u]=o.useState("all"),[x,m]=o.useState(null),[v,S]=o.useState(!1),[p,h]=o.useState(null),[j,b]=o.useState("normal"),[N,T]=o.useState(""),[y,C]=o.useState(!1),k=o.useCallback(async()=>{if(e)try{const I=await r(e,"get_provider_source_config",{}),P=ii(I);P&&(h(P),b(P.sourceMode),T(P.explicitProviderDir||""))}catch{}},[e,r]),w=o.useCallback(async()=>{if(e){c(!0);try{const I=await r(e,"get_provider_settings",{}),P=Bx(I);if(P){const O=Kx(P,t);O.sort((V,L)=>V.category.localeCompare(L.category)||V.displayName.localeCompare(L.displayName)),a(O)}}catch{}c(!1)}},[e,t,r]);o.useEffect(()=>{n.length===0&&w(),p||k()},[]);const g=async(I,P,O)=>{d(`${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()}d(null)},D=async()=>{C(!0);try{const I=await r(e,"set_provider_source_config",{providerSourceMode:j,providerDir:Ox(N)}),P=ii(I);P?(h(P),b(P.sourceMode),T(P.explicitProviderDir||"")):await k(),await w()}catch{await k()}C(!1)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between items-center mb-4",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(I=>s.jsx("button",{onClick:()=>u(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))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>S(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),s.jsx("button",{onClick:w,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Existing running sessions may need restart."})]}),s.jsx("button",{onClick:k,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),s.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),s.jsxs("select",{value:j,onChange:I=>b(I.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),s.jsx("input",{type:"text",value:N,onChange:I=>T(I.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void D(),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"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((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),K=!!(L.values[R.key]??R.default);G?(G.onCount+=K?1:0,G.total+=1):P.set(R.key,{label:R.label||R.key,onCount:K?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 g(G.type,L,R)};return s.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[s.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",f.toUpperCase()," providers (",I.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:O.map(([L,R])=>{const G=R.onCount===R.total,K=R.onCount===0;return s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:R.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",R.onCount,"/",R.total,")"]}),s.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"}),s.jsx("button",{onClick:()=>void V(L,!1),disabled:K,className:`machine-btn text-[9px] px-1.5 py-px ${K?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},L)})})]})})(),i&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):s.jsx("div",{className:"flex flex-col gap-2",children:n.filter(I=>f==="all"||I.category===f).map(I=>s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[s.jsx("span",{className:"text-lg",children:I.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:I.displayName}),s.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"&&s.jsx("button",{onClick:()=>m(t.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"})]}),s.jsx("div",{className:"flex flex-col gap-2",children:I.schema.map(P=>s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[P.label||P.key,l===`${I.type}.${P.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),P.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:P.description})]}),s.jsx("div",{className:"shrink-0",children:P.type==="boolean"?s.jsx("button",{onClick:()=>g(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:s.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:I.values[P.key]??P.default?21:3}})}):P.type==="number"?s.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||g(I.type,P.key,V)},className:"machine-input w-20 text-center text-[11px]"}):P.type==="select"&&P.options?s.jsx("select",{value:String(I.values[P.key]??P.default??""),onChange:O=>g(I.type,P.key,O.target.value),className:"machine-input text-[11px]",children:P.options.map(O=>s.jsx("option",{value:O,children:O},O))}):s.jsx("input",{type:"text",value:String(I.values[P.key]??P.default??""),onBlur:O=>g(I.type,P.key,O.target.value),className:"machine-input w-[120px] text-[11px]"})})]},P.key))})]},I.type))}),x&&s.jsx(Hx,{machineId:e,provider:x,sendDaemonCommand:r,onClose:()=>m(null)}),v&&s.jsx(Fx,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>S(!1),onCreated:()=>{S(!1),w()}})]})}const zx=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Vx({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function Gx(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function qx(e){return e.trim().toLowerCase()}function cn(e,t){const r=qx(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Ya(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function er(e,t=220){const r=Ya(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function Yx(e){const t=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(t))return{kind:t.length>0?"structured":"empty",entries:t.map(r=>{const n=r;return{timestamp:Number(n.ts)||0,level:n.level||"info",message:`[${String(n.category||"daemon")}] ${String(n.message||"")}`.trim()}}),rawText:""};if(typeof t=="string"){const r=t.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function bl(e,t){return e.filter(r=>cn([r.level,r.message],t))}function Xx(e,t){return e.split(`
|
|
63
|
+
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>cn([r],t))}function gl(e,t){return e.filter(r=>cn([r.level,r.category,r.stage,r.interactionId,Ya(r.payload)],t))}function yl(e,t){return e.filter(r=>cn([r.kind,r.topic,r.interactionId,Ya(r.payload)],t))}function li(e){return e==="warn"||e==="error"}function Jx({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){return{all:e.length+t.length+r.length+n.length,info:e.filter(a=>a.level!=="debug").length+r.filter(a=>a.level!=="debug").length+n.length,issues:e.filter(a=>li(a.level)).length+r.filter(a=>li(a.level)).length}}function Qx({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(i=>`${new Date(i.timestamp).toISOString()} ${i.level.toUpperCase()} ${i.message}`)].join(`
|
|
64
64
|
`)):t.length>0&&a.push(["[daemon logs]",...t].join(`
|
|
65
|
-
`)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${
|
|
66
|
-
`)),n.length>0&&a.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${
|
|
65
|
+
`)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${er(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}`:""} ${er(i.payload,500)}`.trim())].join(`
|
|
67
67
|
`)),a.join(`
|
|
68
68
|
|
|
69
|
-
`)}function Hx({daemonLogs:e,trace:t,webEvents:r,daemonLogKind:n,daemonFetchError:a,traceFetchError:i,searchQuery:c}){const l=fl(e,c),u=pl(t,c),f=hl(r,c),d=l.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"daemon",level:w.level,timestamp:w.timestamp,label:"daemon",detail:w.message})),h=u.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"trace",level:w.level,timestamp:w.ts,label:`${w.category}.${w.stage}`,detail:Qs(w.payload,320)||`${w.category}.${w.stage}`})),m=[...d,...h].sort((w,S)=>S.timestamp-w.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 ai(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function oi(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 Dn(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 Fx({machineId:e,sendDaemonCommand:t}){var X,ae;const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[u,f]=o.useState([]),[d,h]=o.useState([]),[m,w]=o.useState(0),[S,p]=o.useState(0),[x,j]=o.useState(null),[b,N]=o.useState(!0),[T,y]=o.useState("info"),[C,k]=o.useState("info"),[v,g]=o.useState("all"),[D,M]=o.useState(""),[I,P]=o.useState(!0),[K,V]=o.useState(!0),[L,R]=o.useState(""),[G,B]=o.useState(""),[E,W]=o.useState(0),[J,be]=o.useState({daemon:!0,trace:!1,web:!1}),he=o.useRef(null),de=o.useRef(!1),ye=o.useMemo(()=>Ex(u,v),[u,v]),ge=o.useMemo(()=>fl(r,D),[r,D]),ve=o.useMemo(()=>Kx(c,D),[c,D]),z=o.useMemo(()=>pl(ye,D),[ye,D]),F=o.useMemo(()=>hl(d,D),[d,D]),Q=o.useMemo(()=>C==="issues"?ge.filter(A=>A.level==="warn"||A.level==="error"):C==="info"?ge.filter(A=>A.level!=="debug"):ge,[ge,C]),ue=o.useMemo(()=>C==="all"?ve:[],[ve,C]),te=o.useMemo(()=>C==="issues"?z.filter(A=>A.level==="warn"||A.level==="error"):C==="info"?z.filter(A=>A.level!=="debug"):z,[z,C]),fe=o.useMemo(()=>C==="issues"?[]:F,[F,C]),ne=o.useMemo(()=>Ox({daemonLogs:ge,daemonRawLines:ve,trace:z,webEvents:F}),[ge,ve,z,F]),xe=o.useMemo(()=>Hx({daemonLogs:r,trace:ye,webEvents:d,daemonLogKind:a,daemonFetchError:L,traceFetchError:G,searchQuery:D}),[L,a,r,ye,D,G,d]),re=o.useCallback(async()=>{if(!e)return;const[A,H]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:T,since:m}),t(e,"get_debug_trace",Dx({count:120,since:S,category:v}))]);if(A.status==="fulfilled"){const ce=A.value,me=(ce==null?void 0:ce.result)||ce,we=Bx(me);if(P(!1),R((ce==null?void 0:ce.success)===!1?String((ce==null?void 0:ce.error)||"Could not load daemon logs"):""),i(we.kind),l(we.rawText),we.entries.length>0){n(Ae=>(m>0?[...Ae,...we.entries]:we.entries).slice(-300));const _e=we.entries.reduce((Ae,Ke)=>Math.max(Ae,Number(Ke.timestamp||0)),m);_e>m&&w(_e)}else we.kind!=="structured"&&m===0&&n([])}else P(!1),R(A.reason instanceof Error?A.reason.message:"Could not load daemon logs");if(H.status==="fulfilled"){const ce=H.value,me=(ce==null?void 0:ce.result)||ce;if((ce==null?void 0:ce.success)===!1)B(String((ce==null?void 0:ce.error)||"Could not load daemon trace"));else if(Array.isArray(me==null?void 0:me.trace)){B(""),f(me.trace.slice(-120));const we=me.trace.reduce((_e,Ae)=>Math.max(_e,Number(Ae.ts||0)),S);we>S&&p(we)}else B(""),f([]);V(!1)}else V(!1),B(H.reason instanceof Error?H.reason.message:"Could not load daemon trace");h(ks.list({limit:120})),j(Date.now())},[m,S,T,e,t,v]);o.useEffect(()=>{if(!e||(re(),!b))return;const A=setInterval(()=>{re()},3e3);return()=>clearInterval(A)},[b,re,e,E]),o.useEffect(()=>{if(b&&(Q.length>0||ue.length>0||te.length>0||fe.length>0)){const A=de.current?"smooth":"instant";setTimeout(()=>{var H;(H=he.current)==null||H.scrollIntoView({behavior:A}),de.current=!0},50)}},[Q.length,ue.length,te.length,fe.length,b]),o.useEffect(()=>{f([]),p(0),V(!0)},[v]);const le=((X=xe.latestIssue)==null?void 0:X.level)==="error"?"danger":((ae=xe.latestIssue)==null?void 0:ae.level)==="warn"?"warning":"good",oe=L||G?"danger":b?"good":"neutral",Y=o.useCallback(async()=>{var H;const A=Wx({daemonLogs:Q,daemonRawLines:ue,trace:te,webEvents:fe});if(!A.trim()){lt.showToast("복사할 visible logs가 없습니다.","info");return}try{await((H=navigator.clipboard)==null?void 0:H.writeText(A)),lt.showToast("Visible logs를 클립보드에 복사했습니다.","success")}catch(ce){lt.showToast(ce instanceof Error?ce.message:"Could not copy visible logs","warning")}},[Q,ue,te,fe]);return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"Level"}),["debug","info","warn","error"].map(A=>s.jsx("button",{onClick:()=>{y(A),n([]),l(""),i("empty"),w(0),P(!0)},className:`machine-btn text-[10px] px-2 py-0.5 ${T===A?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:A.toUpperCase()},A)),s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider ml-3 mr-1",children:"Trace"}),_x.map(A=>s.jsx("button",{onClick:()=>g(A.value),className:`machine-btn text-[10px] px-2 py-0.5 ${v===A.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:A.label},A.value))]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${ne.info})`},{id:"issues",label:`Issues (${ne.issues})`},{id:"all",label:`All (${ne.all})`}].map(A=>s.jsx("button",{type:"button",onClick:()=>k(A.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${C===A.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:A.label},A.id))}),s.jsx("input",{value:D,onChange:A=>M(A.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"}),s.jsx("button",{onClick:()=>{Y()},className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:()=>N(A=>!A),className:`machine-btn ${b?"text-green-500 border-green-500/30":""}`,children:b?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:()=>W(A=>A+1),className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:()=>{n([]),l(""),i("empty"),f([]),h([]),w(0),p(0),j(null),R(""),B(""),P(!0),V(!0),ks.clear()},className:"machine-btn",children:"Clear"})]})]}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Dn(xe.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Visible signals"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:["daemon ",Q.length+ue.length," · trace ",te.length," · web ",fe.length]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:D.trim()?`Filtered by “${D.trim()}”`:"Showing the latest buffered entries"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Dn(le)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Attention needed"}),xe.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[xe.latestIssue.source," · ",xe.latestIssue.label]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:xe.latestIssue.detail}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:[xe.issueCount," warn/error signal(s) · ",ai(xe.latestIssue.timestamp)]})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No recent warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use search or lower the log level if you need more context."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Dn(oe)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Fetch status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:L||G?"Needs attention":b?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",ai(x)]}),(L||G)&&s.jsxs("div",{className:"text-[11px] text-red-300 mt-2 space-y-1",children:[L&&s.jsxs("div",{children:["Daemon logs: ",L]}),G&&s.jsxs("div",{children:["Daemon trace: ",G]})]})]})]}),s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>be(A=>({...A,daemon:!A.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:a==="text"?`${ue.length} visible raw line(s) from file fallback`:`${Q.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:J.daemon?"Hide":"Show"})]}),J.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[I&&!xe.hasAnyData&&!L&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!I&&L&&a==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:L}),!I&&a==="empty"&&!L&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),a==="text"&&ue.length===0&&c&&s.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&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),a==="text"&&ue.map((A,H)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:A},`raw-${H}`)),a!=="text"&&Q.map((A,H)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${oi(A.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(A.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:A.level==="error"?"ERR":A.level==="warn"?"WRN":A.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:A.message})]},`log-${H}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>be(A=>({...A,trace:!A.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",v==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[te.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:J.trace?"Hide":"Show"})]}),J.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[K&&te.length===0&&!G&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!K&&G&&te.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:G}),!K&&te.length===0&&!G&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:D.trim()?"No trace entries match the current search.":v==="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."}),te.map(A=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${oi(A.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(A.ts).toLocaleTimeString()}),s.jsx("span",{children:A.level.toUpperCase()}),s.jsxs("span",{children:[A.category,".",A.stage]}),A.interactionId&&s.jsxs("span",{children:["ix=",A.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Qs(A.payload,360)||"No payload"})]},A.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>be(A=>({...A,web:!A.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[fe.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:J.web?"Hide":"Show"})]}),J.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[fe.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:D.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),fe.map(A=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(A.ts).toLocaleTimeString()}),s.jsx("span",{children:A.kind}),A.topic&&s.jsxs("span",{children:["topic=",A.topic]}),A.interactionId&&s.jsxs("span",{children:["ix=",A.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Qs(A.payload,360)||"No payload"})]},A.id))]})]})]}),s.jsx("div",{ref:he})]})}function Ux(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 xl(e){const t=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return t?t==="auto_resumed"?"restored after restart":t==="resume_failed"?"restore failed":t==="host_restart_interrupted"?"host restart interrupted":t==="orphan_snapshot"?"snapshot recovered":t.replace(/_/g," "):null}function zx(e){var a;const t=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=xl((i==null?void 0:i.meta)||void 0),u=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?t.push(i):(c==="stopped"||c==="failed")&&(u||l)?r.push(i):n.push(i)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function Vx(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function En(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 $n(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Bn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function ii(e){if(!e)return"unknown";const t=Date.now()-e,r=Math.max(0,Math.round(t/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function Gx(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function qx(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 Yx(e){var r;const t=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const i=`${n.providerType}::${n.workspace}::${a}`;t.set(i,(t.get(i)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function Xx({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),f=ip(e,{enabled:!!e,includeSessions:!0,limit:Co,intervalMs:km}),d=f.diagnostics,h=f.loading,m=f.applyDiagnostics,w=o.useMemo(()=>Ux({diagnostics:d,loading:h,refreshing:l,error:n}),[d,h,l,n]),S=o.useMemo(()=>new Map(t.map(M=>[M.sessionId||M.id,M])),[t]),p=o.useCallback(async()=>{if(e){u(!0);try{const M=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Co}),I=$n(M);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(M){const I=M instanceof Error?M.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(M,I)=>{const P=`${M}:${I.sessionId}`;if(!(M==="session_host_stop_session"&&!window.confirm(`Stop ${I.displayName}?
|
|
70
|
-
This will terminate the hosted runtime.`))){c(P);try{const
|
|
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=$n(I);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const K=P.result||{},V=Array.isArray(K.prunedSessionIds)?K.prunedSessionIds.length:0,L=typeof K.duplicateGroupCount=="number"?K.duplicateGroupCount:0;lt.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";lt.showToast(P,"warning"),a(P)}finally{c(I=>I==="session_host_prune_duplicate_sessions"?null:I)}}},[e,p,r]),b=o.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((M,I)=>(I.lastActivityAt||0)-(M.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)||[]}:zx(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),T=N.liveRuntimes,y=N.recoverySnapshots,C=N.inactiveRecords,k=o.useMemo(()=>Yx(T),[T]),v=o.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),g=o.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(M=>M.level==="warn"||M.level==="error")||null,[d==null?void 0:d.recentLogs]),D=(M,I)=>{var W;const P=i===`session_host_resume_session:${M.sessionId}`,K=i===`session_host_restart_session:${M.sessionId}`,V=i===`session_host_stop_session:${M.sessionId}`,L=xl(M.meta),R=S.get(M.sessionId),G=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,B=I==="recovery"?"Recover":"Resume",E=Vx(I);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:M.displayName||(R==null?void 0:R.cliName)||M.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${qx(M.lifecycle)}`,children:M.lifecycle}),L&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:L})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:M.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||M.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:M.runtimeKey}),M.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",M.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((W=M.writeOwner)==null?void 0:W.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Gx(M.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(Si,{size:11})," ",G]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",ii(M.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[I==="recovery"&&(M.lifecycle==="interrupted"||M.lifecycle==="failed"||M.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_resume_session",M)},children:P?`${B}ing…`:B}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_restart_session",M)},children:K?"Restarting…":"Restart"}),I==="live"&&(M.lifecycle==="running"||M.lifecycle==="starting"||M.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{x("session_host_stop_session",M)},children:V?"Stopping…":"Stop"})]})]})},M.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(ls,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:ff()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[k>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{j()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${k})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${w.toneClass}`,children:w.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||l,children:[s.jsx(er,{size:13}),h||l?"Refreshing…":"Refresh"]})]})]}),n&&!d&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(qs,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:y.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:ii(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Bn(d.hostStartedAt)})]})]}),g&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(qs,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:g.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Bn(g.timestamp),g.sessionId?` · ${g.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(ga,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("live")}),T.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:T.map(M=>D(M,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(ls,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("recovery")}),y.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:y.map(M=>D(M,"recovery"))})]}),C.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:C.map(M=>D(M,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),v.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:v.map(M=>{var P;const I=b.find(K=>K.sessionId===M.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(I==null?void 0:I.displayName)||((P=S.get(M.sessionId))==null?void 0:P.cliName)||M.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[M.action,M.lifecycle?` · ${M.lifecycle}`:"",M.detail?` · ${M.detail}`:"",M.error?` · ${M.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${M.success===!1?"text-red-300":"text-text-secondary"}`,children:Bn(M.timestamp)})]},`${M.sessionId}:${M.timestamp}:${M.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Jx({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function Kn({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function On({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function Qx({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),d=Hs(e,"0.9.23");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[l.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Kn,{icon:s.jsx(Ft,{size:13}),children:"Current Chats"}),s.jsx(On,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const m=ea(h);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(h),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:tt(h)}),m>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Jr(m)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:us(h)})]},h.tabKey)})})})]}),u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Kn,{icon:s.jsx(Mi,{size:13}),children:"Recent Launches"}),s.jsx(On,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:m,updatedLabel:w}=Xc(h);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(h),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:h.label}),w&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:w})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:m})]},h.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Kn,{icon:s.jsx(qs,{size:13}),children:"Daemon Update"}),s.jsx(On,{className:"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:d?"Daemon update required":"Version mismatch detected"}),s.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:d?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(er,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Zx(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const eb={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 Wn({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:f}){const d=As(),{handleLaunchIde:h,handleStopCli:m,handleRestartIde:w,handleStopIde:S,handleDetectIdes:p,launchingIde:x,launchingAgentType:j,addLog:b}=c,[N,T]=o.useState(null),y=o.useCallback(_=>{_&&d(Gt(_))},[d]),C=eb[e],k=e==="ide",v=e==="acp",g=o.useMemo(()=>n.filter(_=>_.category===e&&(e==="ide"||_.installed!==!1)),[e,n]),D=o.useMemo(()=>new Map(g.map(_=>[_.type,_.displayName||_.type])),[g]),[M,I]=o.useState(""),[P,K]=o.useState(""),[V,L]=o.useState([]),[R,G]=o.useState(""),[B,E]=o.useState(""),[W,J]=o.useState([]),[be,he]=o.useState(!1),[de,ye]=o.useState(!1),[ge,ve]=o.useState(""),[z,F]=o.useState(!1),[Q,ue]=o.useState(()=>ht()),[te,fe]=o.useState(null),[ne,xe]=o.useState(f?"__custom__":u||t.defaultWorkspaceId||""),[re,le]=o.useState(f||""),[oe,Y]=o.useState([]),[X,ae]=o.useState(!1),[A,H]=o.useState(""),[ce,me]=o.useState([]),[we,_e]=o.useState(!1),[Ae,Ke]=o.useState(""),Fe=o.useRef(null),[ze,ot]=o.useState(null),it=o.useRef("__home__"),[dt,ut]=o.useState("__home__"),[mt,Xe]=o.useState(!1),rt=o.useRef(0),je=oe.filter(_=>!a.some(ee=>ee.type===_&&bt(ee.status)!=="stopped")),Ee=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!ne&&xe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(f){xe("__custom__"),le(f);return}u&&(xe(u),le(""))},[u,f]),o.useEffect(()=>{k||M&&(g.some(_=>_.type===M)||(I(""),E("")))},[g,k,M]);const Be=(()=>{if(ne==="__custom__")return re.trim();if(!ne)return"";const _=(t.workspaces||[]).find(ee=>ee.id===ne);return(_==null?void 0:_.path)||""})(),nt=o.useCallback(_=>{const ee=Ee.current[_];ee&&(clearTimeout(ee),delete Ee.current[_]),Y(pe=>pe.includes(_)?pe.filter(Re=>Re!==_):pe)},[]),st=o.useRef(new Set),yt=o.useCallback(async _=>{if(l){_e(!0),Ke("");try{const ee=await rn(l,r,_);H(ee.path),le(ee.path),me(ee.directories)}catch(ee){Ke(ee instanceof Error?ee.message:"Could not load folder")}finally{_e(!1)}}},[r,l]),Z=o.useCallback(()=>{if(!l)return;xe("__custom__"),ae(!0);const _=a.map(pe=>pe.workspace),ee=sn(t.platform,tn(re.trim(),Be,f,_,t.defaultWorkspacePath,(t.workspaces||[]).map(pe=>pe.path)));yt(ee)},[re,f,yt,t.defaultWorkspacePath,t.platform,t.workspaces,a,Be,l]),Le=o.useCallback(_=>{const ee=String(_.workspace||"").trim();if(!ee)return;const pe=(t.workspaces||[]).find(Re=>Ir(Re.path)===Ir(ee));if(pe){xe(pe.id),le("");return}xe("__custom__"),le(ee)},[t.workspaces]),De=o.useCallback(_=>{const ee=String(_.workspace||"").trim();if(!ee)return{workspaceId:null,workspacePath:"",useHome:!0};const pe=(t.workspaces||[]).find(Re=>Ir(Re.path)===Ir(ee));return pe?{workspaceId:pe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ee,useHome:!1}},[t.workspaces]),et=o.useCallback(async _=>{if(!l||!_||e!=="cli"){J([]),he(!1),ye(!1),ve("");return}const ee=rt.current+1;rt.current=ee,he(!0),ve("");try{const pe=await l(r,"list_saved_sessions",{providerType:_,kind:"cli",limit:30});if(rt.current!==ee)return;const Re=(pe==null?void 0:pe.result)??pe;J(Array.isArray(Re==null?void 0:Re.sessions)?Re.sessions:[])}catch(pe){if(rt.current!==ee)return;J([]),ve(pe instanceof Error?pe.message:"Could not load saved sessions")}finally{rt.current===ee&&(he(!1),ye(!0))}},[e,r,l]),Tt=o.useMemo(()=>{if(e!=="cli"||!M)return null;const _=D.get(M)||M;return{routeId:r,daemonId:r,providerSessionId:B||void 0,transport:"pty",mode:"chat",agentName:_,agentType:M,status:"idle",title:_,messages:[],ideType:M,workspaceName:Be,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${M}`}},[e,r,D,Be,B,M]),ft=o.useCallback(_=>{if(e==="ide"||!_){L([]);return}L(ll(r,_))},[e,r]);o.useEffect(()=>{rt.current+=1,E(""),ft(M),ye(!1),J([]),ve(""),he(!1)},[e,ft,et,M]);const He=o.useMemo(()=>W.find(_=>_.providerSessionId===B)||null,[W,B]);o.useEffect(()=>{if(!B)return;const _=W.find(ee=>ee.providerSessionId===B);_!=null&&_.canResume||E("")},[W,B]);const vt=o.useCallback((_,ee)=>{Fe.current=ee,it.current=_.selectedWorkspaceKey||"__home__",ut(_.selectedWorkspaceKey||"__home__"),ot(_)},[]),$=o.useCallback(()=>{Fe.current&&(Xe(!0),Fe.current().finally(()=>{Fe.current=null,Xe(!1),ot(null)}))},[]),O=o.useCallback(_=>{if(!_)return;Y(pe=>pe.includes(_)?pe:[...pe,_]);const ee=Ee.current[_];ee&&clearTimeout(ee),Ee.current[_]=setTimeout(()=>{Y(pe=>pe.includes(_)?pe.filter(Re=>Re!==_):pe),delete Ee.current[_]},2e4)},[]);o.useEffect(()=>{for(const ee of a)bt(ee.status)!=="stopped"&&(oe.includes(ee.type)&&!st.current.has(ee.type)&&(st.current.add(ee.type),b("info",`${D.get(ee.type)||ee.type} launched`,!0)),nt(ee.type));const _=new Set(a.filter(ee=>bt(ee.status)!=="stopped").map(ee=>ee.type));st.current.forEach(ee=>{!oe.includes(ee)&&!_.has(ee)&&st.current.delete(ee)})},[b,nt,a,oe,D]),o.useEffect(()=>()=>{Object.values(Ee.current).forEach(clearTimeout),Ee.current={}},[]);const[U,q]=o.useState({}),[ie,Se]=o.useState(null);o.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const ee=await l(r,"get_ide_extensions",{}),pe=(ee==null?void 0:ee.result)||ee;pe!=null&&pe.success&&(pe!=null&&pe.ideExtensions)&&q(pe.ideExtensions)}catch{}})()},[k,r,l]);const Ie=_=>k?Ze(_.type):e==="cli"?_.cliName:_.acpName,Ce=k?t.detectedIdes||[]:[],se=o.useCallback(async _=>{const ee=(_==null?void 0:_.type)||M,pe=(_==null?void 0:_.workspacePath)??Be;if(k){await h(ee,pe?{workspace:pe}:void 0)&&O(ee);return}const Re=await c.runLaunchCliCore({cliType:ee,dir:_!=null&&_.workspaceId?void 0:pe||void 0,workspaceId:(_==null?void 0:_.workspaceId)||void 0,useHome:(_==null?void 0:_.useHome)||!(_!=null&&_.workspaceId)&&!pe,argsStr:(_==null?void 0:_.argsStr)??(P||void 0),model:(_==null?void 0:_.model)??(v&&R||void 0),resumeSessionId:(_==null?void 0:_.resumeSessionId)||!v&&e==="cli"&&ee===M&&B||void 0});if(Re.success||Re.pending){const Ne=(_==null?void 0:_.argsStr)??P;!k&&(Ne!=null&&Ne.trim())&&(dl(r,ee,Ne),ft(ee)),O(ee),Re.success&&Re.sessionId&&y(Re.sessionId)}},[c,h,v,k,P,R,ft,O,r,y,Be,B,M]),ke=bc(k?"ide":v?"acp":"cli",!k&&!v&&!!B),Oe=gc(k?"ide":v?"acp":"cli",!k&&!v&&!!B),Ue=()=>{var Ne;const _=k?Ze(M):D.get(M)||M,ee=!k&&!v&&!!B,{options:pe,selectedKey:Re}=os({machine:t,currentWorkspaceId:ne&&ne!=="__custom__"?ne:null,currentWorkspacePath:Be});vt({title:ee?Pa(_):ss("start-fresh",_),description:ee?_a():rs("start-fresh"),confirmLabel:ke,busyLabel:Oe,workspaceOptions:pe,selectedWorkspaceKey:Re,details:[{label:"Mode",value:C.label},{label:"Provider",value:_},...!k&&e==="cli"&&B?[{label:"Resume",value:((Ne=W.find(Me=>Me.providerSessionId===B))==null?void 0:Ne.title)||B}]:[],...!k&&P.trim()?[{label:"Arguments",value:P.trim()}]:[],...v&&R.trim()?[{label:"Model",value:R.trim()}]:[]]},async()=>{const Me=pe.find(Te=>Te.key===it.current);Me!=null&&Me.workspaceId?(xe(Me.workspaceId),le("")):Me!=null&&Me.workspacePath?(xe("__custom__"),le(Me.workspacePath)):(xe(""),le("")),await se({workspaceId:(Me==null?void 0:Me.workspaceId)??null,workspacePath:(Me==null?void 0:Me.workspacePath)??"",useHome:!(Me!=null&&Me.workspaceId)&&!(Me!=null&&Me.workspacePath)})})},Ye=_=>{k?S(_):m(_.type,_.workspace,_.id)},Ve=o.useCallback(async(_,ee,pe=!1)=>{if(_.mode===ee){pe&&_.sessionId&&y(_.sessionId);return}if(!l||!_.sessionId){pe&&_.sessionId&&y(_.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_.type,mode:ee}),pe&&y(_.sessionId)}catch(Re){const Ne=Bc(Re);$c(Re)?console.warn(Ne?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Re instanceof Error?Re.message:String(Re)):console.error("Failed to switch CLI view mode:",Re)}},[r,y,l]),Pe=s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:ne,onChange:_=>{const ee=_.target.value;if(xe(ee),ee==="__custom__"&&l){Z();return}ee!=="__custom__"&&le("")},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:(t.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(t.workspaces||[]).map(_=>s.jsxs("option",{value:_.id,children:[_.id===t.defaultWorkspaceId?"⭐ ":"",Zr(_.path,_.label)]},_.id)),s.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),ne==="__custom__"&&(l?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:Z,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:re,onChange:_=>le(_.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:ne==="__custom__"?Be?s.jsx("span",{className:"font-mono truncate block",title:Be,children:Be}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Be?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:ne===t.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:Be,children:Be})]}):"No workspace selected. This launches in the home directory."})]});return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${C.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",C.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?Ce.length>0?Ce.map(_=>{const ee=a.find(Te=>(Te.type||"").toLowerCase()===(_.type||"").toLowerCase()&&bt(Te.status)!=="stopped"),pe=_.running||!!ee,Re=!!ee&&ee.cdpConnected,Ne=oe.includes(_.type||_.id||""),Me=M===(_.type||"");return s.jsxs("button",{onClick:()=>{if(Re&&ee){const Te=ee.sessionId;Te?d(Gt(Te),{state:{openRemoteForTabKey:Te}}):d("/dashboard",{state:{openRemoteForTabKey:ee.id}});return}Ne||I(Te=>Te===(_.type||"")?"":_.type||"")},disabled:!!x||Ne,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Re?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Me?"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:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(_.type)}),pe&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Re?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.name||Ze(_.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Re?"text-green-400":Ne?"text-orange-400":Me?"text-accent-primary":"text-text-muted"}`,children:Re?"Open Session":Ne?"Starting...":Me?"Configure":"Select"})]})]},_.type)}):s.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",s.jsxs("button",{onClick:p,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[s.jsx(Md,{size:14})," Scan System"]})]}):g.length>0?g.map(_=>{const ee=M===_.type,pe=oe.includes(_.type),Ne=!!a.find(Me=>Me.type===_.type&&bt(Me.status)!=="stopped");return s.jsxs("button",{onClick:()=>I(Me=>Me===_.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:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:_.icon}),Ne&&s.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${pe?"text-orange-400":ee?"text-accent-primary":"text-text-muted"}`,children:pe?"Starting...":ee?"Configure":"Select"})]})]},_.type)}):s.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),M&&(k?Ce.find(_=>_.type===M):g.find(_=>_.type===M))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:k?Ze(M):D.get(M)||M})]}),Pe,!k&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&s.jsx(ml,{busy:!!j||!!x||oe.includes(M),savedSessionsLoading:be,savedSessionsError:ge,selectedSession:He,onRefresh:()=>void et(M),onOpenHistory:()=>{M&&(F(!0),ul({hasLoadedInitialResults:de,isLoading:be})&&et(M))},onClearSelection:()=>E("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value: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"})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),s.jsx("input",{type:"text",placeholder:"Optional flags...",value:P,onChange:_=>K(_.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),V.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:V.map(_=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>K(_),title:_,children:_},_))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:Ue,disabled:!!j||!!x||oe.includes(M),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:j===M||x===M?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+oe.filter(_=>!a.some(ee=>ee.type===_&&bt(ee.status)!=="stopped")).length,")"]}),a.length===0&&je.length===0?s.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",C.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[je.map(_=>s.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(_)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?Ze(_):D.get(_)||_}),s.jsx("div",{className:"text-[11px] text-text-muted",children:j===_?"Launching process...":"Waiting for process and session to register..."})]})]}),s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${_}`)),a.map(_=>{const ee=k?_:null,pe=!k&&!v?_:null,Re=bt(_.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(_.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ie(_),(ee==null?void 0:ee.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ee.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[s.jsx("span",{children:_.workspace||"—"}),(pe==null?void 0:pe.mode)&&s.jsx("span",{className:pe.mode==="chat"?"text-violet-400":"text-text-secondary",children:pe.mode==="chat"?"Chat view":"Terminal view"})]}),pe&&(pe.runtimeKey||pe.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[pe.runtimeKey&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),s.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",pe.runtimeKey]}),s.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Ne;(Ne=navigator.clipboard)==null||Ne.writeText(`adhdev attach ${pe.runtimeKey}`),T(pe.runtimeKey||null),window.setTimeout(()=>{T(Me=>Me===pe.runtimeKey?null:Me)},1200)},children:N===pe.runtimeKey?"Copied":"Copy"})]}),pe.runtimeWriteOwner&&s.jsx("span",{style:{color:pe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:pe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Zx(pe.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Re==="stopped"?"bg-red-500/[0.08] text-red-500":Re==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Re}),k&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Ne=_.sessionId;if(Ne){d(Gt(Ne),{state:{openRemoteForTabKey:Ne}});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:s.jsx(Ct,{size:13})}),s.jsx("button",{onClick:()=>{const Ne=_.workspace||"",{options:Me,selectedKey:Te}=os({machine:t,currentWorkspacePath:Ne});vt({title:ss("restart-ide",Ze(_.type)),description:rs("restart-ide"),confirmLabel:Cs("restart-ide"),busyLabel:Is("restart-ide"),workspaceOptions:Me,selectedWorkspaceKey:Te,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:Ze(_.type)}]},async()=>{const pt=Me.find(Ut=>Ut.key===it.current),ct=(pt==null?void 0:pt.workspacePath)??"";if(ct&&ct!==Ne){await se({type:_.type,workspacePath:ct});return}await w(_)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:s.jsx(er,{size:14})})]}),v&&s.jsx("button",{onClick:()=>{const Ne=_.sessionId;Ne&&y(Ne)},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:s.jsx(Ft,{size:14})}),pe&&Re!=="stopped"&&s.jsxs(s.Fragment,{children:[pe.mode&&s.jsx(Ta,{mode:pe.mode,onChange:Ne=>void Ve(pe,Ne,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Ne=_.sessionId;Ne&&y(Ne)},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:pe.mode==="chat"?s.jsx(Ft,{size:14}):s.jsx(Ct,{size:13})})]}),Re==="stopped"?s.jsx("button",{onClick:()=>{const Ne=_.workspace||"",Me=k?Ze(_.type):Ie(_),{options:Te,selectedKey:pt}=os({machine:t,currentWorkspacePath:Ne});vt({title:ss("restart-stopped",Me),description:rs("restart-stopped"),confirmLabel:Cs("restart-stopped"),busyLabel:Is("restart-stopped"),workspaceOptions:Te,selectedWorkspaceKey:pt,details:[{label:"Mode",value:C.label},{label:"Provider",value:Me}]},async()=>{const ct=Te.find(Ut=>Ut.key===it.current);await se({type:_.type,workspaceId:(ct==null?void 0:ct.workspaceId)??null,workspacePath:(ct==null?void 0:ct.workspacePath)??"",useHome:!(ct!=null&&ct.workspaceId)&&!(ct!=null&&ct.workspacePath)})})},disabled:oe.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:oe.includes(_.type)?"⏳":s.jsx(ya,{size:14})}):s.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:s.jsx(wt,{size:14})})]})]}),ee&&ee.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ee.aiAgents.map(Ne=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Ki(Ne.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ne.name," · ",bt(Ne.status)]},Ne.id))}),ee&&(U[ee.type]||[]).length>0&&l&&s.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[s.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(U[ee.type]||[]).map(Ne=>s.jsxs("button",{disabled:ie===`${ee.type}.${Ne.type}`,onClick:async()=>{const Me=`${ee.type}.${Ne.type}`;Se(Me);try{await l(r,"set_ide_extension",{ideType:ee.type,extensionType:Ne.type,enabled:!Ne.enabled}),q(Te=>({...Te,[ee.type]:(Te[ee.type]||[]).map(pt=>pt.type===Ne.type?{...pt,enabled:!pt.enabled}:pt)}))}catch(Te){console.error("Extension toggle failed:",Te)}finally{Se(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 ${Ne.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Ne.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ne.name,s.jsx("span",{className:"text-[9px] font-normal",children:Ne.enabled?"ON":"OFF"})]},Ne.type))})]})]},_.id)})]}),X&&l&&s.jsx(an,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:A,directories:ce,busy:we,error:Ae,confirmLabel:"Use this folder",onClose:()=>ae(!1),onNavigate:_=>{yt(_)},onConfirm:_=>{le(_),xe("__custom__"),ae(!1)}}),ze&&s.jsx(za,{title:ze.title,description:ze.description,details:ze.details,workspaceOptions:ze.workspaceOptions,selectedWorkspaceKey:dt,onWorkspaceChange:_=>{it.current=_,ut(_)},confirmLabel:ze.confirmLabel,busyLabel:ze.busyLabel,busy:mt,onConfirm:$,onCancel:()=>{Fe.current=null,ot(null)}}),z&&Tt&&s.jsx(Da,{activeConv:Tt,ides:[],isCreatingChat:!1,isRefreshingHistory:be,savedSessions:W,isSavedSessionsLoading:be,isResumingSavedSessionId:te,savedHistoryFilters:Q,onSavedHistoryFiltersChange:ue,onClose:()=>F(!1),onNewChat:()=>{E(""),F(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{et(M)},onResumeSavedSession:_=>{if(!_.canResume||te)return;const ee=De(_);E(_.providerSessionId),Le(_),fe(_.providerSessionId),F(!1),se({type:_.providerType,workspaceId:ee.workspaceId,workspacePath:ee.workspacePath,useHome:ee.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{fe(pe=>pe===_.providerSessionId?null:pe)})}})]})}const ci=[{id:"ide",label:"IDE",helper:"Open a graphical workspace and attach CDP"},{id:"cli",label:"CLI",helper:"Launch a terminal-first workspace on this machine"},{id:"acp",label:"ACP",helper:"Launch an ACP-backed workspace on this machine"}];function tb({machine:e,machineId:t,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,w]=o.useState(u);o.useEffect(()=>{w(u)},[u]);const S=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:ci.map(x=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${m===x.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>w(x.id),children:[s.jsx("span",{children:x.label}),s.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))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(p=ci.find(x=>x.id===m))==null?void 0:p.helper})]}),m==="ide"&&s.jsx(Wn,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d}),m==="cli"&&s.jsx(Wn,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d}),m==="acp"&&s.jsx(Wn,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:d})]})}function sb({onNicknameSynced:e}={}){var fe,ne,xe,re,le,oe,Y,X,ae;const{id:t}=Zl(),r=As(),n=pa(),{sendCommand:a}=jt(),i=nr(),c=Pc(),l=lc(),u=l.ides||[],f=l.initialLoaded??!0,d=u.find(A=>A.id===t&&A.type==="adhdev-daemon"),h=u.some(A=>A.type==="adhdev-daemon"),[m,w]=o.useState("workspace"),[S,p]=o.useState("ide"),x=o.useRef(null),[j,b]=o.useState(null),N=o.useRef("__home__"),[T,y]=o.useState("__home__"),[C,k]=o.useState(!1),v=o.useRef(null);o.useEffect(()=>{!t||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||i(t,{minFreshMs:3e4}).catch(()=>{})},[i,d,t]),o.useEffect(()=>{if(!t||!d||m!=="overview")return;const A=d.machine;(typeof(A==null?void 0:A.cpus)!="number"||typeof(A==null?void 0:A.totalMem)!="number"||typeof(A==null?void 0:A.arch)!="string"||typeof(A==null?void 0:A.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[m,c,d,t]),op(t&&m==="overview"?[t]:[],{enabled:m==="overview",intervalMs:ym});const g=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},D=Nx({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:v});o.useEffect(()=>lt.onToast(H=>{l.setToasts(me=>{if(me.some(Ae=>Ae.message===H.message&&H.timestamp-Ae.timestamp<3e3))return me;const _e={id:H.id,message:H.message,type:H.type,timestamp:H.timestamp,targetKey:H.targetKey,actions:H.actions};return[...me.slice(-4),_e]});const ce=H.duration||5e3;setTimeout(()=>l.setToasts(me=>me.filter(we=>we.id!==H.id)),ce)}),[l]);const M=(d==null?void 0:d.availableProviders)||[],I={};for(const A of M)I[A.type]=A.icon;const P=A=>I[A]||"",K=d?{id:d.id,hostname:Oi(d,{fallbackId:d.id}),platform:((fe=d.machine)==null?void 0:fe.platform)||"unknown",arch:((ne=d.machine)==null?void 0:ne.arch)||"",cpus:((xe=d.machine)==null?void 0:xe.cpus)||0,totalMem:((re=d.machine)==null?void 0:re.totalMem)||0,freeMem:(le=d.machine)==null?void 0:le.freeMem,availableMem:(oe=d.machine)==null?void 0:oe.availableMem,loadavg:(Y=d.machine)==null?void 0:Y.loadavg,uptime:(X=d.machine)==null?void 0:X.uptime,release:((ae=d.machine)==null?void 0:ae.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(A=>A.daemonId===t&&A.type!=="adhdev-daemon").filter(A=>!Xs(A)&&!ys(A)).map(A=>({id:A.id,sessionId:A.sessionId,type:A.type,version:A.version||"",instanceId:A.instanceId||"",status:A.status,workspace:A.workspace||null,terminals:A.terminals||0,aiAgents:Su(A.aiAgents||(A.agents||[]).map(H=>({id:H.name,name:H.name,status:H.status,version:H.version}))),activeChat:A.activeChat||null,chats:A.chats||[],childSessions:A.childSessions||[],cdpConnected:A.cdpConnected||!1,daemonId:t})),L=u.filter(A=>A.daemonId===t&&Xs(A)).map(A=>({id:A.id,sessionId:A.sessionId,type:A.type,cliName:A.cliName||A.type,status:A.status,workspace:A.workspace||"",activeChat:A.activeChat||null,providerSessionId:A.providerSessionId,mode:A.mode,runtimeKey:A.runtimeKey,runtimeDisplayName:A.runtimeDisplayName,runtimeWorkspaceLabel:A.runtimeWorkspaceLabel,runtimeWriteOwner:A.runtimeWriteOwner||null,runtimeAttachedClients:A.runtimeAttachedClients||[],daemonId:t})),R=u.filter(A=>A.daemonId===t&&ys(A)).map(A=>({id:A.id,sessionId:A.sessionId,type:A.type,acpName:A.cliName||A.type,status:A.status,workspace:A.workspace||"",activeChat:A.activeChat||null,providerSessionId:A.providerSessionId,daemonId:t})),G=d?Mt(d,{fallbackId:t}):"",B="workspace",E=n.state,W=E==null?void 0:E.initialMachineTab,J=E==null?void 0:E.initialWorkspaceCategory,be=E==null?void 0:E.initialWorkspaceId,he=E==null?void 0:E.initialWorkspacePath,de=W==="ides"||W==="clis"||W==="acps"?"workspace":W||B,ye=W==="ides"?"ide":W==="clis"?"cli":W==="acps"?"acp":J,ge=[...V.map(A=>{var H,ce,me,we,_e;return{id:`ide:${A.type}:${A.workspace||""}`,label:((H=A.activeChat)==null?void 0:H.title)||A.type,kind:"ide",providerType:A.type,subtitle:A.workspace||void 0,workspace:A.workspace||void 0,lastLaunchedAt:((_e=(we=(me=(ce=A.activeChat)==null?void 0:ce.messages)==null?void 0:me.at)==null?void 0:we.call(me,-1))==null?void 0:_e.timestamp)||0}}),...L.map(A=>{var H,ce,me,we,_e;return{id:`cli:${A.type}:${A.workspace||""}`,label:((H=A.activeChat)==null?void 0:H.title)||A.cliName,kind:"cli",providerType:A.type,providerSessionId:A.providerSessionId,subtitle:A.workspace||void 0,workspace:A.workspace||void 0,lastLaunchedAt:((_e=(we=(me=(ce=A.activeChat)==null?void 0:ce.messages)==null?void 0:me.at)==null?void 0:we.call(me,-1))==null?void 0:_e.timestamp)||0}}),...R.map(A=>{var H,ce,me,we,_e;return{id:`acp:${A.type}:${A.workspace||""}`,label:((H=A.activeChat)==null?void 0:H.title)||A.acpName,kind:"acp",providerType:A.type,providerSessionId:A.providerSessionId,subtitle:ds(A.summaryMetadata)||A.workspace||void 0,workspace:A.workspace||void 0,lastLaunchedAt:((_e=(we=(me=(ce=A.activeChat)==null?void 0:ce.messages)==null?void 0:me.at)==null?void 0:we.call(me,-1))==null?void 0:_e.timestamp)||0}})].sort((A,H)=>(H.lastLaunchedAt||0)-(A.lastLaunchedAt||0)),ve=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(A=>({id:A.id,label:A.title||A.providerName||A.providerType,kind:A.kind,providerType:A.providerType,providerSessionId:A.providerSessionId,subtitle:ds(A.summaryMetadata)||A.workspace||void 0,workspace:A.workspace,summaryMetadata:A.summaryMetadata,lastLaunchedAt:A.lastLaunchedAt})):ge,z=o.useMemo(()=>{var H;const A=((H=l.connectionStates)==null?void 0:H[t||""])||void 0;return u.filter(ce=>ce.daemonId===t&&ce.type!=="adhdev-daemon").flatMap(ce=>Ea(ce,{connectionStates:t&&A?{[t]:A}:void 0,defaultConnectionState:A})).filter(ce=>!(ce.transport==="pty"&&ce.mode==="terminal")).sort((ce,me)=>ea(me)-ea(ce))},[u,l.connectionStates,t]),F=o.useCallback(A=>{const H=Ia(A);H&&r(Gt(H))},[r]),Q=o.useCallback(()=>{x.current&&(k(!0),x.current().finally(()=>{x.current=null,k(!1),b(null)}))},[]),ue=o.useCallback(A=>{if(!K)return;const{options:H,selectedKey:ce}=os({machine:K,currentWorkspacePath:A.workspace}),me=async()=>{p(A.kind),w("workspace")};x.current=async()=>{const we=H.find(Ke=>Ke.key===N.current),_e=(we==null?void 0:we.workspacePath)??null,Ae=(we==null?void 0:we.workspaceId)??null;if(A.kind==="ide"&&A.providerType){await D.handleLaunchIde(A.providerType,_e?{workspace:_e}:void 0);return}if((A.kind==="cli"||A.kind==="acp")&&A.providerType){await D.runLaunchCliCore({cliType:A.providerType,dir:Ae?void 0:_e||"",workspaceId:Ae||void 0,model:A.kind==="acp"&&Hi(A.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:A.providerSessionId});return}await me()},N.current=ce,y(ce),b({title:A.kind==="ide"?ss("restart-ide",A.label):A.providerSessionId?Pa(A.label):ss("start-fresh",A.label),description:A.kind==="ide"?rs("restart-ide"):A.providerSessionId?_a():rs("start-fresh"),confirmLabel:A.kind==="ide"?Cs("restart-ide"):A.providerSessionId?Ur(!0):Cs("start-fresh"),busyLabel:A.kind==="ide"?Is("restart-ide"):A.providerSessionId?La(!0):Is("start-fresh"),workspaceOptions:H,details:[{label:"Mode",value:A.kind.toUpperCase()},...A.providerType?[{label:"Provider",value:A.providerType}]:[]]})},[D,K]);if(o.useEffect(()=>{w(de)},[B,de,t]),o.useEffect(()=>{ye&&p(ye)},[ye,t]),!K)return f?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:g,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const te=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ct,{size:14})," Workspace"]}),count:V.length+L.length+R.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ls,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Yr,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Td,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Id,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:g,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[D.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:D.nicknameInput,onChange:A=>D.setNicknameInput(A.target.value),onKeyDown:A=>{A.key==="Enter"&&D.handleSaveNickname(),A.key==="Escape"&&D.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:D.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>D.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{D.setEditingNickname(!0),D.setNicknameInput(K.machineNickname||"")},title:"Click to set nickname",children:G}),s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[K.platform," · ",K.arch]}),s.jsxs("span",{children:[K.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),K.p2p.available&&s.jsxs("span",{children:["P2P ",K.p2p.state==="connected"?"connected":K.p2p.state]}),K.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:K.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:te.map(A=>s.jsxs("button",{onClick:()=>w(A.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${m===A.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[A.label,A.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${m===A.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:A.count})]},A.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[m==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(Qx,{machineEntry:d,providers:M,recentLaunches:ve,currentConversations:z,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:ue,onOpenConversation:F}),s.jsx(tb,{machine:K,machineId:t,providers:M,ideSessions:V,cliSessions:L,acpSessions:R,actions:D,getIcon:P,initialCategory:S,initialWorkspaceId:be,initialWorkspacePath:he,sendDaemonCommand:a})]}),m==="providers"&&s.jsx(Px,{machineId:t,providers:M,sendDaemonCommand:a}),m==="overview"&&s.jsx(Cx,{machineId:t,machine:K,ideSessions:V,cliSessions:L,acpSessions:R,actions:D,sendDaemonCommand:a}),m==="session-host"&&s.jsx(Xx,{machineId:t,cliSessions:L,sendDaemonCommand:a}),m==="logs"&&s.jsx(Fx,{machineId:t,sendDaemonCommand:a})]})})}),D.launchPick&&K&&s.jsx(Jx,{machine:K,launchPick:D.launchPick,actions:D}),j&&s.jsx(za,{title:j.title,description:j.description,details:j.details,workspaceOptions:j.workspaceOptions,selectedWorkspaceKey:T,onWorkspaceChange:A=>{N.current=A,y(A)},confirmLabel:j.confirmLabel,busyLabel:j.busyLabel,busy:C,onConfirm:Q,onCancel:()=>{x.current=null,b(null)}}),s.jsx(yc,{toasts:l.toasts||[],onDismiss:A=>l.setToasts(H=>H.filter(ce=>ce.id!==A)),onClickToast:A=>{A.targetKey&&r(Gt(A.targetKey))}}),s.jsx("style",{children:`
|
|
69
|
+
`)}function Zx({daemonLogs:e,trace:t,webEvents:r,daemonLogKind:n,daemonFetchError:a,traceFetchError:i,searchQuery:c}){const l=bl(e,c),d=gl(t,c),f=yl(r,c),u=l.filter(v=>v.level==="warn"||v.level==="error").map(v=>({source:"daemon",level:v.level,timestamp:v.timestamp,label:"daemon",detail:v.message})),x=d.filter(v=>v.level==="warn"||v.level==="error").map(v=>({source:"trace",level:v.level,timestamp:v.ts,label:`${v.category}.${v.stage}`,detail:er(v.payload,320)||`${v.category}.${v.stage}`})),m=[...u,...x].sort((v,S)=>S.timestamp-v.timestamp);return{daemonCount:l.length,traceCount:d.length,webCount:f.length,issueCount:m.length,latestIssue:m[0]||null,hasAnyData:n==="text"||l.length>0||d.length>0||f.length>0,hasBlockingError:!!(a||i)}}function di(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function ui(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 Dn(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 eb({machineId:e,sendDaemonCommand:t}){var X,ne;const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[d,f]=o.useState([]),[u,x]=o.useState([]),[m,v]=o.useState(0),[S,p]=o.useState(0),[h,j]=o.useState(null),[b,N]=o.useState(!0),[T,y]=o.useState("info"),[C,k]=o.useState("info"),[w,g]=o.useState("all"),[D,A]=o.useState(""),[I,P]=o.useState(!0),[O,V]=o.useState(!0),[L,R]=o.useState(""),[G,K]=o.useState(""),[E,W]=o.useState(0),[J,be]=o.useState({daemon:!0,trace:!1,web:!1}),xe=o.useRef(null),de=o.useRef(!1),ye=o.useMemo(()=>Gx(d,w),[d,w]),ge=o.useMemo(()=>bl(r,D),[r,D]),ve=o.useMemo(()=>Xx(c,D),[c,D]),z=o.useMemo(()=>gl(ye,D),[ye,D]),F=o.useMemo(()=>yl(u,D),[u,D]),Q=o.useMemo(()=>C==="issues"?ge.filter(M=>M.level==="warn"||M.level==="error"):C==="info"?ge.filter(M=>M.level!=="debug"):ge,[ge,C]),ue=o.useMemo(()=>C==="all"?ve:[],[ve,C]),te=o.useMemo(()=>C==="issues"?z.filter(M=>M.level==="warn"||M.level==="error"):C==="info"?z.filter(M=>M.level!=="debug"):z,[z,C]),fe=o.useMemo(()=>C==="issues"?[]:F,[F,C]),re=o.useMemo(()=>Jx({daemonLogs:ge,daemonRawLines:ve,trace:z,webEvents:F}),[ge,ve,z,F]),pe=o.useMemo(()=>Zx({daemonLogs:r,trace:ye,webEvents:u,daemonLogKind:a,daemonFetchError:L,traceFetchError:G,searchQuery:D}),[L,a,r,ye,D,G,u]),oe=o.useCallback(async()=>{if(!e)return;const[M,H]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:T,since:m}),t(e,"get_debug_trace",Vx({count:120,since:S,category:w}))]);if(M.status==="fulfilled"){const ce=M.value,me=(ce==null?void 0:ce.result)||ce,je=Yx(me);if(P(!1),R((ce==null?void 0:ce.success)===!1?String((ce==null?void 0:ce.error)||"Could not load daemon logs"):""),i(je.kind),l(je.rawText),je.entries.length>0){n(Me=>(m>0?[...Me,...je.entries]:je.entries).slice(-300));const _e=je.entries.reduce((Me,Be)=>Math.max(Me,Number(Be.timestamp||0)),m);_e>m&&v(_e)}else je.kind!=="structured"&&m===0&&n([])}else P(!1),R(M.reason instanceof Error?M.reason.message:"Could not load daemon logs");if(H.status==="fulfilled"){const ce=H.value,me=(ce==null?void 0:ce.result)||ce;if((ce==null?void 0:ce.success)===!1)K(String((ce==null?void 0:ce.error)||"Could not load daemon trace"));else if(Array.isArray(me==null?void 0:me.trace)){K(""),f(me.trace.slice(-120));const je=me.trace.reduce((_e,Me)=>Math.max(_e,Number(Me.ts||0)),S);je>S&&p(je)}else K(""),f([]);V(!1)}else V(!1),K(H.reason instanceof Error?H.reason.message:"Could not load daemon trace");x(ks.list({limit:120})),j(Date.now())},[m,S,T,e,t,w]);o.useEffect(()=>{if(!e||(oe(),!b))return;const M=setInterval(()=>{oe()},3e3);return()=>clearInterval(M)},[b,oe,e,E]),o.useEffect(()=>{if(b&&(Q.length>0||ue.length>0||te.length>0||fe.length>0)){const M=de.current?"smooth":"instant";setTimeout(()=>{var H;(H=xe.current)==null||H.scrollIntoView({behavior:M}),de.current=!0},50)}},[Q.length,ue.length,te.length,fe.length,b]),o.useEffect(()=>{f([]),p(0),V(!0)},[w]);const le=((X=pe.latestIssue)==null?void 0:X.level)==="error"?"danger":((ne=pe.latestIssue)==null?void 0:ne.level)==="warn"?"warning":"good",ae=L||G?"danger":b?"good":"neutral",Y=o.useCallback(async()=>{var H;const M=Qx({daemonLogs:Q,daemonRawLines:ue,trace:te,webEvents:fe});if(!M.trim()){lt.showToast("복사할 visible logs가 없습니다.","info");return}try{await((H=navigator.clipboard)==null?void 0:H.writeText(M)),lt.showToast("Visible logs를 클립보드에 복사했습니다.","success")}catch(ce){lt.showToast(ce instanceof Error?ce.message:"Could not copy visible logs","warning")}},[Q,ue,te,fe]);return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"Level"}),["debug","info","warn","error"].map(M=>s.jsx("button",{onClick:()=>{y(M),n([]),l(""),i("empty"),v(0),P(!0)},className:`machine-btn text-[10px] px-2 py-0.5 ${T===M?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:M.toUpperCase()},M)),s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider ml-3 mr-1",children:"Trace"}),zx.map(M=>s.jsx("button",{onClick:()=>g(M.value),className:`machine-btn text-[10px] px-2 py-0.5 ${w===M.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:M.label},M.value))]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${re.info})`},{id:"issues",label:`Issues (${re.issues})`},{id:"all",label:`All (${re.all})`}].map(M=>s.jsx("button",{type:"button",onClick:()=>k(M.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${C===M.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:M.label},M.id))}),s.jsx("input",{value:D,onChange:M=>A(M.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"}),s.jsx("button",{onClick:()=>{Y()},className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:()=>N(M=>!M),className:`machine-btn ${b?"text-green-500 border-green-500/30":""}`,children:b?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:()=>W(M=>M+1),className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:()=>{n([]),l(""),i("empty"),f([]),x([]),v(0),p(0),j(null),R(""),K(""),P(!0),V(!0),ks.clear()},className:"machine-btn",children:"Clear"})]})]}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Dn(pe.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Visible signals"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:["daemon ",Q.length+ue.length," · trace ",te.length," · web ",fe.length]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:D.trim()?`Filtered by “${D.trim()}”`:"Showing the latest buffered entries"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Dn(le)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Attention needed"}),pe.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[pe.latestIssue.source," · ",pe.latestIssue.label]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:pe.latestIssue.detail}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:[pe.issueCount," warn/error signal(s) · ",di(pe.latestIssue.timestamp)]})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No recent warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use search or lower the log level if you need more context."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Dn(ae)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Fetch status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:L||G?"Needs attention":b?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",di(h)]}),(L||G)&&s.jsxs("div",{className:"text-[11px] text-red-300 mt-2 space-y-1",children:[L&&s.jsxs("div",{children:["Daemon logs: ",L]}),G&&s.jsxs("div",{children:["Daemon trace: ",G]})]})]})]}),s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>be(M=>({...M,daemon:!M.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:a==="text"?`${ue.length} visible raw line(s) from file fallback`:`${Q.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:J.daemon?"Hide":"Show"})]}),J.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[I&&!pe.hasAnyData&&!L&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!I&&L&&a==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:L}),!I&&a==="empty"&&!L&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),a==="text"&&ue.length===0&&c&&s.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&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),a==="text"&&ue.map((M,H)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:M},`raw-${H}`)),a!=="text"&&Q.map((M,H)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${ui(M.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(M.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:M.level==="error"?"ERR":M.level==="warn"?"WRN":M.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:M.message})]},`log-${H}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>be(M=>({...M,trace:!M.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",w==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[te.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:J.trace?"Hide":"Show"})]}),J.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[O&&te.length===0&&!G&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!O&&G&&te.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:G}),!O&&te.length===0&&!G&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:D.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."}),te.map(M=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${ui(M.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(M.ts).toLocaleTimeString()}),s.jsx("span",{children:M.level.toUpperCase()}),s.jsxs("span",{children:[M.category,".",M.stage]}),M.interactionId&&s.jsxs("span",{children:["ix=",M.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:er(M.payload,360)||"No payload"})]},M.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>be(M=>({...M,web:!M.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[fe.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:J.web?"Hide":"Show"})]}),J.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[fe.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:D.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),fe.map(M=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(M.ts).toLocaleTimeString()}),s.jsx("span",{children:M.kind}),M.topic&&s.jsxs("span",{children:["topic=",M.topic]}),M.interactionId&&s.jsxs("span",{children:["ix=",M.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:er(M.payload,360)||"No payload"})]},M.id))]})]})]}),s.jsx("div",{ref:xe})]})}function tb(e){return e.diagnostics?{label:"Managed",toneClass:"bg-green-500/[0.08] text-green-500"}:e.loading||e.refreshing?{label:"Checking…",toneClass:"bg-sky-500/[0.08] text-sky-400"}:e.error?{label:"Diagnostics issue",toneClass:"bg-amber-500/[0.08] text-amber-400"}:{label:"Unavailable",toneClass:"bg-red-500/[0.08] text-red-400"}}function vl(e){const t=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return t?t==="auto_resumed"?"restored after restart":t==="resume_failed"?"restore failed":t==="host_restart_interrupted"?"host restart interrupted":t==="orphan_snapshot"?"snapshot recovered":t.replace(/_/g," "):null}function sb(e){var a;const t=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=vl((i==null?void 0:i.meta)||void 0),d=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?t.push(i):(c==="stopped"||c==="failed")&&(d||l)?r.push(i):n.push(i)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function rb(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function En(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 $n(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Bn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function mi(e){if(!e)return"unknown";const t=Date.now()-e,r=Math.max(0,Math.round(t/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function nb(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function ab(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 ob(e){var r;const t=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const i=`${n.providerType}::${n.workspace}::${a}`;t.set(i,(t.get(i)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function ib({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,d]=o.useState(!1),f=gp(e,{enabled:!!e,includeSessions:!0,limit:Mo,intervalMs:Tm}),u=f.diagnostics,x=f.loading,m=f.applyDiagnostics,v=o.useMemo(()=>tb({diagnostics:u,loading:x,refreshing:l,error:n}),[u,x,l,n]),S=o.useMemo(()=>new Map(t.map(A=>[A.sessionId||A.id,A])),[t]),p=o.useCallback(async()=>{if(e){d(!0);try{const A=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Mo}),I=$n(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{d(!1)}}},[m,e,r]);o.useEffect(()=>{!e||u||x||l||p()},[u,x,e,p,l]);const h=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=$n(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";lt.showToast(`Session host ${L}: ${I.displayName}`,"success"),await p()}catch(O){const V=O instanceof Error?O.message:"Session host action failed";lt.showToast(V,"warning"),a(V)}finally{c(O=>O===P?null:O)}}},[e,p,r]),j=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=$n(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;lt.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";lt.showToast(P,"warning"),a(P)}finally{c(I=>I==="session_host_prune_duplicate_sessions"?null:I)}}},[e,p,r]),b=o.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((A,I)=>(I.lastActivityAt||0)-(A.lastActivityAt||0)),[u==null?void 0:u.sessions]),N=o.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:sb(b),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,b]),T=N.liveRuntimes,y=N.recoverySnapshots,C=N.inactiveRecords,k=o.useMemo(()=>ob(T),[T]),w=o.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),g=o.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(A=>A.level==="warn"||A.level==="error")||null,[u==null?void 0:u.recentLogs]),D=(A,I)=>{var W;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=vl(A.meta),R=S.get(A.sessionId),G=A.attachedClients.length===1?"1 client":`${A.attachedClients.length} clients`,K=I==="recovery"?"Recover":"Resume",E=rb(I);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:A.displayName||(R==null?void 0:R.cliName)||A.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${ab(A.lifecycle)}`,children:A.lifecycle}),L&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:L})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:A.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||A.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:A.runtimeKey}),A.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",A.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((W=A.writeOwner)==null?void 0:W.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:nb(A.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(Ai,{size:11})," ",G]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",mi(A.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[I==="recovery"&&(A.lifecycle==="interrupted"||A.lifecycle==="failed"||A.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{h("session_host_resume_session",A)},children:P?`${K}ing…`:K}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{h("session_host_restart_session",A)},children:O?"Restarting…":"Restart"}),I==="live"&&(A.lifecycle==="running"||A.lifecycle==="starting"||A.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{h("session_host_stop_session",A)},children:V?"Stopping…":"Stop"})]})]})},A.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(ls,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Sf()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[k>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{j()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${k})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${v.toneClass}`,children:v.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:x||l,children:[s.jsx(sr,{size:13}),x||l?"Refreshing…":"Refresh"]})]})]}),n&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(Xs,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:y.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:mi(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Bn(u.hostStartedAt)})]})]}),g&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(Xs,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:g.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Bn(g.timestamp),g.sessionId?` · ${g.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(ga,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("live")}),T.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:T.map(A=>D(A,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(ls,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("recovery")}),y.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:y.map(A=>D(A,"recovery"))})]}),C.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:C.map(A=>D(A,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),w.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:w.map(A=>{var P;const I=b.find(O=>O.sessionId===A.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(I==null?void 0:I.displayName)||((P=S.get(A.sessionId))==null?void 0:P.cliName)||A.sessionId}),s.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}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${A.success===!1?"text-red-300":"text-text-secondary"}`,children:Bn(A.timestamp)})]},`${A.sessionId}:${A.timestamp}:${A.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function cb({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function Kn({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function On({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function lb({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),d=r.slice(0,4),u=zs(e,"0.9.25");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[l.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Kn,{icon:s.jsx(Ut,{size:13}),children:"Current Chats"}),s.jsx(On,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(x=>{const m=ea(x);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(x),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:rt(x)}),m>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Jr(m)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:us(x)})]},x.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Kn,{icon:s.jsx(_i,{size:13}),children:"Recent Launches"}),s.jsx(On,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(x=>{const{metaText:m,updatedLabel:v}=el(x);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(x),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:x.label}),v&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:v})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:m})]},x.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Kn,{icon:s.jsx(Xs,{size:13}),children:"Daemon Update"}),s.jsx(On,{className:"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u?"Daemon update required":"Version mismatch detected"}),s.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:u?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(sr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function db(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const ub={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 Wn({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:f}){const u=As(),{handleLaunchIde:x,handleStopCli:m,handleRestartIde:v,handleStopIde:S,handleDetectIdes:p,launchingIde:h,launchingAgentType:j,addLog:b}=c,[N,T]=o.useState(null),y=o.useCallback(_=>{_&&u(Gt(_))},[u]),C=ub[e],k=e==="ide",w=e==="acp",g=o.useMemo(()=>n.filter(_=>_.category===e&&(e==="ide"||_.installed!==!1)),[e,n]),D=o.useMemo(()=>new Map(g.map(_=>[_.type,_.displayName||_.type])),[g]),[A,I]=o.useState(""),[P,O]=o.useState(""),[V,L]=o.useState([]),[R,G]=o.useState(""),[K,E]=o.useState(""),[W,J]=o.useState([]),[be,xe]=o.useState(!1),[de,ye]=o.useState(!1),[ge,ve]=o.useState(""),[z,F]=o.useState(!1),[Q,ue]=o.useState(()=>ht()),[te,fe]=o.useState(null),[re,pe]=o.useState(f?"__custom__":d||t.defaultWorkspaceId||""),[oe,le]=o.useState(f||""),[ae,Y]=o.useState([]),[X,ne]=o.useState(!1),[M,H]=o.useState(""),[ce,me]=o.useState([]),[je,_e]=o.useState(!1),[Me,Be]=o.useState(""),We=o.useRef(null),[Fe,nt]=o.useState(null),Ze=o.useRef("__home__"),[it,dt]=o.useState("__home__"),[mt,at]=o.useState(!1),ut=o.useRef(0),Ce=ae.filter(_=>!a.some(ee=>ee.type===_&&bt(ee.status)!=="stopped")),$e=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!re&&pe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(f){pe("__custom__"),le(f);return}d&&(pe(d),le(""))},[d,f]),o.useEffect(()=>{k||A&&(g.some(_=>_.type===A)||(I(""),E("")))},[g,k,A]);const Ue=(()=>{if(re==="__custom__")return oe.trim();if(!re)return"";const _=(t.workspaces||[]).find(ee=>ee.id===re);return(_==null?void 0:_.path)||""})(),Ve=o.useCallback(_=>{const ee=$e.current[_];ee&&(clearTimeout(ee),delete $e.current[_]),Y(he=>he.includes(_)?he.filter(Re=>Re!==_):he)},[]),qe=o.useRef(new Set),Je=o.useCallback(async _=>{if(l){_e(!0),Be("");try{const ee=await rn(l,r,_);H(ee.path),le(ee.path),me(ee.directories)}catch(ee){Be(ee instanceof Error?ee.message:"Could not load folder")}finally{_e(!1)}}},[r,l]),Z=o.useCallback(()=>{if(!l)return;pe("__custom__"),ne(!0);const _=a.map(he=>he.workspace),ee=sn(t.platform,tn(oe.trim(),Ue,f,_,t.defaultWorkspacePath,(t.workspaces||[]).map(he=>he.path)));Je(ee)},[oe,f,Je,t.defaultWorkspacePath,t.platform,t.workspaces,a,Ue,l]),Le=o.useCallback(_=>{const ee=String(_.workspace||"").trim();if(!ee)return;const he=(t.workspaces||[]).find(Re=>Ir(Re.path)===Ir(ee));if(he){pe(he.id),le("");return}pe("__custom__"),le(ee)},[t.workspaces]),De=o.useCallback(_=>{const ee=String(_.workspace||"").trim();if(!ee)return{workspaceId:null,workspacePath:"",useHome:!0};const he=(t.workspaces||[]).find(Re=>Ir(Re.path)===Ir(ee));return he?{workspaceId:he.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ee,useHome:!1}},[t.workspaces]),st=o.useCallback(async _=>{if(!l||!_||e!=="cli"){J([]),xe(!1),ye(!1),ve("");return}const ee=ut.current+1;ut.current=ee,xe(!0),ve("");try{const he=await l(r,"list_saved_sessions",{providerType:_,kind:"cli",limit:30});if(ut.current!==ee)return;const Re=(he==null?void 0:he.result)??he;J(Array.isArray(Re==null?void 0:Re.sessions)?Re.sessions:[])}catch(he){if(ut.current!==ee)return;J([]),ve(he instanceof Error?he.message:"Could not load saved sessions")}finally{ut.current===ee&&(xe(!1),ye(!0))}},[e,r,l]),Ct=o.useMemo(()=>{if(e!=="cli"||!A)return null;const _=D.get(A)||A;return{routeId:r,daemonId:r,providerSessionId:K||void 0,transport:"pty",mode:"chat",agentName:_,agentType:A,status:"idle",title:_,messages:[],ideType:A,workspaceName:Ue,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${A}`}},[e,r,D,Ue,K,A]),ft=o.useCallback(_=>{if(e==="ide"||!_){L([]);return}L(fl(r,_))},[e,r]);o.useEffect(()=>{ut.current+=1,E(""),ft(A),ye(!1),J([]),ve(""),xe(!1)},[e,ft,st,A]);const Tt=o.useMemo(()=>W.find(_=>_.providerSessionId===K)||null,[W,K]);o.useEffect(()=>{if(!K)return;const _=W.find(ee=>ee.providerSessionId===K);_!=null&&_.canResume||E("")},[W,K]);const yt=o.useCallback((_,ee)=>{We.current=ee,Ze.current=_.selectedWorkspaceKey||"__home__",dt(_.selectedWorkspaceKey||"__home__"),nt(_)},[]),B=o.useCallback(()=>{We.current&&(at(!0),We.current().finally(()=>{We.current=null,at(!1),nt(null)}))},[]),$=o.useCallback(_=>{if(!_)return;Y(he=>he.includes(_)?he:[...he,_]);const ee=$e.current[_];ee&&clearTimeout(ee),$e.current[_]=setTimeout(()=>{Y(he=>he.includes(_)?he.filter(Re=>Re!==_):he),delete $e.current[_]},2e4)},[]);o.useEffect(()=>{for(const ee of a)bt(ee.status)!=="stopped"&&(ae.includes(ee.type)&&!qe.current.has(ee.type)&&(qe.current.add(ee.type),b("info",`${D.get(ee.type)||ee.type} launched`,!0)),Ve(ee.type));const _=new Set(a.filter(ee=>bt(ee.status)!=="stopped").map(ee=>ee.type));qe.current.forEach(ee=>{!ae.includes(ee)&&!_.has(ee)&&qe.current.delete(ee)})},[b,Ve,a,ae,D]),o.useEffect(()=>()=>{Object.values($e.current).forEach(clearTimeout),$e.current={}},[]);const[U,q]=o.useState({}),[ie,ke]=o.useState(null);o.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const ee=await l(r,"get_ide_extensions",{}),he=(ee==null?void 0:ee.result)||ee;he!=null&&he.success&&(he!=null&&he.ideExtensions)&&q(he.ideExtensions)}catch{}})()},[k,r,l]);const Ie=_=>k?tt(_.type):e==="cli"?_.cliName:_.acpName,Ne=k?t.detectedIdes||[]:[],se=o.useCallback(async _=>{const ee=(_==null?void 0:_.type)||A,he=(_==null?void 0:_.workspacePath)??Ue;if(k){await x(ee,he?{workspace:he}:void 0)&&$(ee);return}const Re=await c.runLaunchCliCore({cliType:ee,dir:_!=null&&_.workspaceId?void 0:he||void 0,workspaceId:(_==null?void 0:_.workspaceId)||void 0,useHome:(_==null?void 0:_.useHome)||!(_!=null&&_.workspaceId)&&!he,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&&K||void 0});if(Re.success||Re.pending){const Se=(_==null?void 0:_.argsStr)??P;!k&&(Se!=null&&Se.trim())&&(pl(r,ee,Se),ft(ee)),$(ee),Re.success&&Re.sessionId&&y(Re.sessionId)}},[c,x,w,k,P,R,ft,$,r,y,Ue,K,A]),we=wc(k?"ide":w?"acp":"cli",!k&&!w&&!!K),Ke=jc(k?"ide":w?"acp":"cli",!k&&!w&&!!K),He=()=>{var Se;const _=k?tt(A):D.get(A)||A,ee=!k&&!w&&!!K,{options:he,selectedKey:Re}=os({machine:t,currentWorkspaceId:re&&re!=="__custom__"?re:null,currentWorkspacePath:Ue});yt({title:ee?Da(_):ss("start-fresh",_),description:ee?Ea():rs("start-fresh"),confirmLabel:we,busyLabel:Ke,workspaceOptions:he,selectedWorkspaceKey:Re,details:[{label:"Mode",value:C.label},{label:"Provider",value:_},...!k&&e==="cli"&&K?[{label:"Resume",value:((Se=W.find(Ae=>Ae.providerSessionId===K))==null?void 0:Se.title)||K}]:[],...!k&&P.trim()?[{label:"Arguments",value:P.trim()}]:[],...w&&R.trim()?[{label:"Model",value:R.trim()}]:[]]},async()=>{const Ae=he.find(Te=>Te.key===Ze.current);Ae!=null&&Ae.workspaceId?(pe(Ae.workspaceId),le("")):Ae!=null&&Ae.workspacePath?(pe("__custom__"),le(Ae.workspacePath)):(pe(""),le("")),await se({workspaceId:(Ae==null?void 0:Ae.workspaceId)??null,workspacePath:(Ae==null?void 0:Ae.workspacePath)??"",useHome:!(Ae!=null&&Ae.workspaceId)&&!(Ae!=null&&Ae.workspacePath)})})},Ye=_=>{k?S(_):m(_.type,_.workspace,_.id)},ze=o.useCallback(async(_,ee,he=!1)=>{if(_.mode===ee){he&&_.sessionId&&y(_.sessionId);return}if(!l||!_.sessionId){he&&_.sessionId&&y(_.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_.type,mode:ee}),he&&y(_.sessionId)}catch(Re){const Se=Hc(Re);Wc(Re)?console.warn(Se?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Re instanceof Error?Re.message:String(Re)):console.error("Failed to switch CLI view mode:",Re)}},[r,y,l]),Pe=s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:re,onChange:_=>{const ee=_.target.value;if(pe(ee),ee==="__custom__"&&l){Z();return}ee!=="__custom__"&&le("")},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:(t.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(t.workspaces||[]).map(_=>s.jsxs("option",{value:_.id,children:[_.id===t.defaultWorkspaceId?"⭐ ":"",Zr(_.path,_.label)]},_.id)),s.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),re==="__custom__"&&(l?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:Z,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:oe,onChange:_=>le(_.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:re==="__custom__"?Ue?s.jsx("span",{className:"font-mono truncate block",title:Ue,children:Ue}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Ue?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:re===t.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:Ue,children:Ue})]}):"No workspace selected. This launches in the home directory."})]});return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${C.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",C.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?Ne.length>0?Ne.map(_=>{const ee=a.find(Te=>(Te.type||"").toLowerCase()===(_.type||"").toLowerCase()&&bt(Te.status)!=="stopped"),he=_.running||!!ee,Re=!!ee&&ee.cdpConnected,Se=ae.includes(_.type||_.id||""),Ae=A===(_.type||"");return s.jsxs("button",{onClick:()=>{if(Re&&ee){const Te=ee.sessionId;Te?u(Gt(Te),{state:{openRemoteForTabKey:Te}}):u("/dashboard",{state:{openRemoteForTabKey:ee.id}});return}Se||I(Te=>Te===(_.type||"")?"":_.type||"")},disabled:!!h||Se,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Re?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ae?"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:h&&h!==_.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(_.type)}),he&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Re?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.name||tt(_.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Re?"text-green-400":Se?"text-orange-400":Ae?"text-accent-primary":"text-text-muted"}`,children:Re?"Open Session":Se?"Starting...":Ae?"Configure":"Select"})]})]},_.type)}):s.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",s.jsxs("button",{onClick:p,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[s.jsx(Ed,{size:14})," Scan System"]})]}):g.length>0?g.map(_=>{const ee=A===_.type,he=ae.includes(_.type),Se=!!a.find(Ae=>Ae.type===_.type&&bt(Ae.status)!=="stopped");return s.jsxs("button",{onClick:()=>I(Ae=>Ae===_.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:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:_.icon}),Se&&s.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${he?"text-orange-400":ee?"text-accent-primary":"text-text-muted"}`,children:he?"Starting...":ee?"Configure":"Select"})]})]},_.type)}):s.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),A&&(k?Ne.find(_=>_.type===A):g.find(_=>_.type===A))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:k?tt(A):D.get(A)||A})]}),Pe,!k&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&s.jsx(xl,{busy:!!j||!!h||ae.includes(A),savedSessionsLoading:be,savedSessionsError:ge,selectedSession:Tt,onRefresh:()=>void st(A),onOpenHistory:()=>{A&&(F(!0),hl({hasLoadedInitialResults:de,isLoading:be})&&st(A))},onClearSelection:()=>E("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value: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"})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),s.jsx("input",{type:"text",placeholder:"Optional flags...",value: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&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:V.map(_=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>O(_),title:_,children:_},_))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:He,disabled:!!j||!!h||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:j===A||h===A?"⏳ Launching...":"▶ Launch"})})]})]}),s.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&&Ce.length===0?s.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",C.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ce.map(_=>s.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(_)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?tt(_):D.get(_)||_}),s.jsx("div",{className:"text-[11px] text-text-muted",children:j===_?"Launching process...":"Waiting for process and session to register..."})]})]}),s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${_}`)),a.map(_=>{const ee=k?_:null,he=!k&&!w?_:null,Re=bt(_.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(_.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ie(_),(ee==null?void 0:ee.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ee.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[s.jsx("span",{children:_.workspace||"—"}),(he==null?void 0:he.mode)&&s.jsx("span",{className:he.mode==="chat"?"text-violet-400":"text-text-secondary",children:he.mode==="chat"?"Chat view":"Terminal view"})]}),he&&(he.runtimeKey||he.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[he.runtimeKey&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),s.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",he.runtimeKey]}),s.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Se;(Se=navigator.clipboard)==null||Se.writeText(`adhdev attach ${he.runtimeKey}`),T(he.runtimeKey||null),window.setTimeout(()=>{T(Ae=>Ae===he.runtimeKey?null:Ae)},1200)},children:N===he.runtimeKey?"Copied":"Copy"})]}),he.runtimeWriteOwner&&s.jsx("span",{style:{color:he.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:he.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:db(he.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Re==="stopped"?"bg-red-500/[0.08] text-red-500":Re==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Re}),k&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Se=_.sessionId;if(Se){u(Gt(Se),{state:{openRemoteForTabKey:Se}});return}u("/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:s.jsx(Nt,{size:13})}),s.jsx("button",{onClick:()=>{const Se=_.workspace||"",{options:Ae,selectedKey:Te}=os({machine:t,currentWorkspacePath:Se});yt({title:ss("restart-ide",tt(_.type)),description:rs("restart-ide"),confirmLabel:Is("restart-ide"),busyLabel:Ms("restart-ide"),workspaceOptions:Ae,selectedWorkspaceKey:Te,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:tt(_.type)}]},async()=>{const pt=Ae.find(Ot=>Ot.key===Ze.current),ct=(pt==null?void 0:pt.workspacePath)??"";if(ct&&ct!==Se){await se({type:_.type,workspacePath:ct});return}await v(_)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:s.jsx(sr,{size:14})})]}),w&&s.jsx("button",{onClick:()=>{const Se=_.sessionId;Se&&y(Se)},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:s.jsx(Ut,{size:14})}),he&&Re!=="stopped"&&s.jsxs(s.Fragment,{children:[he.mode&&s.jsx(Ra,{mode:he.mode,onChange:Se=>void ze(he,Se,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Se=_.sessionId;Se&&y(Se)},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:he.mode==="chat"?s.jsx(Ut,{size:14}):s.jsx(Nt,{size:13})})]}),Re==="stopped"?s.jsx("button",{onClick:()=>{const Se=_.workspace||"",Ae=k?tt(_.type):Ie(_),{options:Te,selectedKey:pt}=os({machine:t,currentWorkspacePath:Se});yt({title:ss("restart-stopped",Ae),description:rs("restart-stopped"),confirmLabel:Is("restart-stopped"),busyLabel:Ms("restart-stopped"),workspaceOptions:Te,selectedWorkspaceKey:pt,details:[{label:"Mode",value:C.label},{label:"Provider",value:Ae}]},async()=>{const ct=Te.find(Ot=>Ot.key===Ze.current);await se({type:_.type,workspaceId:(ct==null?void 0:ct.workspaceId)??null,workspacePath:(ct==null?void 0:ct.workspacePath)??"",useHome:!(ct!=null&&ct.workspaceId)&&!(ct!=null&&ct.workspacePath)})})},disabled: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)?"⏳":s.jsx(ya,{size:14})}):s.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:s.jsx(vt,{size:14})})]})]}),ee&&ee.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ee.aiAgents.map(Se=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Ui(Se.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Se.name," · ",bt(Se.status)]},Se.id))}),ee&&(U[ee.type]||[]).length>0&&l&&s.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[s.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(U[ee.type]||[]).map(Se=>s.jsxs("button",{disabled:ie===`${ee.type}.${Se.type}`,onClick:async()=>{const Ae=`${ee.type}.${Se.type}`;ke(Ae);try{await l(r,"set_ide_extension",{ideType:ee.type,extensionType:Se.type,enabled:!Se.enabled}),q(Te=>({...Te,[ee.type]:(Te[ee.type]||[]).map(pt=>pt.type===Se.type?{...pt,enabled:!pt.enabled}:pt)}))}catch(Te){console.error("Extension toggle failed:",Te)}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 ${Se.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Se.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Se.name,s.jsx("span",{className:"text-[9px] font-normal",children:Se.enabled?"ON":"OFF"})]},Se.type))})]})]},_.id)})]}),X&&l&&s.jsx(an,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:M,directories:ce,busy:je,error:Me,confirmLabel:"Use this folder",onClose:()=>ne(!1),onNavigate:_=>{Je(_)},onConfirm:_=>{le(_),pe("__custom__"),ne(!1)}}),Fe&&s.jsx(Ga,{title:Fe.title,description:Fe.description,details:Fe.details,workspaceOptions:Fe.workspaceOptions,selectedWorkspaceKey:it,onWorkspaceChange:_=>{Ze.current=_,dt(_)},confirmLabel:Fe.confirmLabel,busyLabel:Fe.busyLabel,busy:mt,onConfirm:B,onCancel:()=>{We.current=null,nt(null)}}),z&&Ct&&s.jsx($a,{activeConv:Ct,ides:[],isCreatingChat:!1,isRefreshingHistory:be,savedSessions:W,isSavedSessionsLoading:be,isResumingSavedSessionId:te,savedHistoryFilters:Q,onSavedHistoryFiltersChange:ue,onClose:()=>F(!1),onNewChat:()=>{E(""),F(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{st(A)},onResumeSavedSession:_=>{if(!_.canResume||te)return;const ee=De(_);E(_.providerSessionId),Le(_),fe(_.providerSessionId),F(!1),se({type:_.providerType,workspaceId:ee.workspaceId,workspacePath:ee.workspacePath,useHome:ee.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{fe(he=>he===_.providerSessionId?null:he)})}})]})}const fi=[{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 mb({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:d="ide",initialWorkspaceId:f,initialWorkspacePath:u,sendDaemonCommand:x}){var p;const[m,v]=o.useState(d);o.useEffect(()=>{v(d)},[d]);const S=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:fi.map(h=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${m===h.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>v(h.id),children:[s.jsx("span",{children:h.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${m===h.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:S[h.id]})]},h.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(p=fi.find(h=>h.id===m))==null?void 0:p.helper})]}),m==="ide"&&s.jsx(Wn,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:u}),m==="cli"&&s.jsx(Wn,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:u}),m==="acp"&&s.jsx(Wn,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:u})]})}function fb({onNicknameSynced:e}={}){var fe,re,pe,oe,le,ae,Y,X,ne;const{id:t}=od(),r=As(),n=pa(),{sendCommand:a}=wt(),i=ar(),c=$c(),l=fc(),d=l.ides||[],f=l.initialLoaded??!0,u=d.find(M=>M.id===t&&M.type==="adhdev-daemon"),x=d.some(M=>M.type==="adhdev-daemon"),[m,v]=o.useState("workspace"),[S,p]=o.useState("ide"),h=o.useRef(null),[j,b]=o.useState(null),N=o.useRef("__home__"),[T,y]=o.useState("__home__"),[C,k]=o.useState(!1),w=o.useRef(null);o.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||i(t,{minFreshMs:3e4}).catch(()=>{})},[i,u,t]),o.useEffect(()=>{if(!t||!u||m!=="overview")return;const M=u.machine;(typeof(M==null?void 0:M.cpus)!="number"||typeof(M==null?void 0:M.totalMem)!="number"||typeof(M==null?void 0:M.arch)!="string"||typeof(M==null?void 0:M.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[m,c,u,t]),bp(t&&m==="overview"?[t]:[],{enabled:m==="overview",intervalMs:Cm});const g=()=>{if(x){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},D=Ex({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:w});o.useEffect(()=>lt.onToast(H=>{l.setToasts(me=>{if(me.some(Me=>Me.message===H.message&&H.timestamp-Me.timestamp<3e3))return me;const _e={id:H.id,message:H.message,type:H.type,timestamp:H.timestamp,targetKey:H.targetKey,actions:H.actions};return[...me.slice(-4),_e]});const ce=H.duration||5e3;setTimeout(()=>l.setToasts(me=>me.filter(je=>je.id!==H.id)),ce)}),[l]);const A=(u==null?void 0:u.availableProviders)||[],I={};for(const M of A)I[M.type]=M.icon;const P=M=>I[M]||"",O=u?{id:u.id,hostname:zi(u,{fallbackId:u.id}),platform:((fe=u.machine)==null?void 0:fe.platform)||"unknown",arch:((re=u.machine)==null?void 0:re.arch)||"",cpus:((pe=u.machine)==null?void 0:pe.cpus)||0,totalMem:((oe=u.machine)==null?void 0:oe.totalMem)||0,freeMem:(le=u.machine)==null?void 0:le.freeMem,availableMem:(ae=u.machine)==null?void 0:ae.availableMem,loadavg:(Y=u.machine)==null?void 0:Y.loadavg,uptime:(X=u.machine)==null?void 0:X.uptime,release:((ne=u.machine)==null?void 0:ne.release)||"",cdpConnected:!!u.cdpConnected,machineNickname:u.machineNickname||null,p2p:u.p2p?{screenshotActive:!1,...u.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:u.detectedIdes||[],workspaces:u.workspaces||[],defaultWorkspaceId:u.defaultWorkspaceId??u.activeWorkspaceId??null,defaultWorkspacePath:u.defaultWorkspacePath??u.activeWorkspacePath??null}:null,V=d.filter(M=>M.daemonId===t&&M.type!=="adhdev-daemon").filter(M=>!Qs(M)&&!ys(M)).map(M=>({id:M.id,sessionId:M.sessionId,type:M.type,version:M.version||"",instanceId:M.instanceId||"",status:M.status,workspace:M.workspace||null,terminals:M.terminals||0,aiAgents:Lu(M.aiAgents||(M.agents||[]).map(H=>({id:H.name,name:H.name,status:H.status,version:H.version}))),activeChat:M.activeChat||null,chats:M.chats||[],childSessions:M.childSessions||[],cdpConnected:M.cdpConnected||!1,daemonId:t})),L=d.filter(M=>M.daemonId===t&&Qs(M)).map(M=>({id:M.id,sessionId:M.sessionId,type:M.type,cliName:M.cliName||M.type,status:M.status,workspace:M.workspace||"",activeChat:M.activeChat||null,providerSessionId:M.providerSessionId,mode:M.mode,runtimeKey:M.runtimeKey,runtimeDisplayName:M.runtimeDisplayName,runtimeWorkspaceLabel:M.runtimeWorkspaceLabel,runtimeWriteOwner:M.runtimeWriteOwner||null,runtimeAttachedClients:M.runtimeAttachedClients||[],daemonId:t})),R=d.filter(M=>M.daemonId===t&&ys(M)).map(M=>({id:M.id,sessionId:M.sessionId,type:M.type,acpName:M.cliName||M.type,status:M.status,workspace:M.workspace||"",activeChat:M.activeChat||null,providerSessionId:M.providerSessionId,daemonId:t})),G=u?At(u,{fallbackId:t}):"",K="workspace",E=n.state,W=E==null?void 0:E.initialMachineTab,J=E==null?void 0:E.initialWorkspaceCategory,be=E==null?void 0:E.initialWorkspaceId,xe=E==null?void 0:E.initialWorkspacePath,de=W==="ides"||W==="clis"||W==="acps"?"workspace":W||K,ye=W==="ides"?"ide":W==="clis"?"cli":W==="acps"?"acp":J,ge=[...V.map(M=>{var H,ce,me,je,_e;return{id:`ide:${M.type}:${M.workspace||""}`,label:((H=M.activeChat)==null?void 0:H.title)||M.type,kind:"ide",providerType:M.type,subtitle:M.workspace||void 0,workspace:M.workspace||void 0,lastLaunchedAt:((_e=(je=(me=(ce=M.activeChat)==null?void 0:ce.messages)==null?void 0:me.at)==null?void 0:je.call(me,-1))==null?void 0:_e.timestamp)||0}}),...L.map(M=>{var H,ce,me,je,_e;return{id:`cli:${M.type}:${M.workspace||""}`,label:((H=M.activeChat)==null?void 0:H.title)||M.cliName,kind:"cli",providerType:M.type,providerSessionId:M.providerSessionId,subtitle:M.workspace||void 0,workspace:M.workspace||void 0,lastLaunchedAt:((_e=(je=(me=(ce=M.activeChat)==null?void 0:ce.messages)==null?void 0:me.at)==null?void 0:je.call(me,-1))==null?void 0:_e.timestamp)||0}}),...R.map(M=>{var H,ce,me,je,_e;return{id:`acp:${M.type}:${M.workspace||""}`,label:((H=M.activeChat)==null?void 0:H.title)||M.acpName,kind:"acp",providerType:M.type,providerSessionId:M.providerSessionId,subtitle:ds(M.summaryMetadata)||M.workspace||void 0,workspace:M.workspace||void 0,lastLaunchedAt:((_e=(je=(me=(ce=M.activeChat)==null?void 0:ce.messages)==null?void 0:me.at)==null?void 0:je.call(me,-1))==null?void 0:_e.timestamp)||0}})].sort((M,H)=>(H.lastLaunchedAt||0)-(M.lastLaunchedAt||0)),ve=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(M=>({id:M.id,label:M.title||M.providerName||M.providerType,kind:M.kind,providerType:M.providerType,providerSessionId:M.providerSessionId,subtitle:ds(M.summaryMetadata)||M.workspace||void 0,workspace:M.workspace,summaryMetadata:M.summaryMetadata,lastLaunchedAt:M.lastLaunchedAt})):ge,z=o.useMemo(()=>{var H;const M=((H=l.connectionStates)==null?void 0:H[t||""])||void 0;return d.filter(ce=>ce.daemonId===t&&ce.type!=="adhdev-daemon").flatMap(ce=>Ba(ce,{connectionStates:t&&M?{[t]:M}:void 0,defaultConnectionState:M})).filter(ce=>!(ce.transport==="pty"&&ce.mode==="terminal")).sort((ce,me)=>ea(me)-ea(ce))},[d,l.connectionStates,t]),F=o.useCallback(M=>{const H=Ia(M);H&&r(Gt(H))},[r]),Q=o.useCallback(()=>{h.current&&(k(!0),h.current().finally(()=>{h.current=null,k(!1),b(null)}))},[]),ue=o.useCallback(M=>{if(!O)return;const{options:H,selectedKey:ce}=os({machine:O,currentWorkspacePath:M.workspace}),me=async()=>{p(M.kind),v("workspace")};h.current=async()=>{const je=H.find(Be=>Be.key===N.current),_e=(je==null?void 0:je.workspacePath)??null,Me=(je==null?void 0:je.workspaceId)??null;if(M.kind==="ide"&&M.providerType){await D.handleLaunchIde(M.providerType,_e?{workspace:_e}:void 0);return}if((M.kind==="cli"||M.kind==="acp")&&M.providerType){await D.runLaunchCliCore({cliType:M.providerType,dir:Me?void 0:_e||"",workspaceId:Me||void 0,model:M.kind==="acp"&&Gi(M.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:M.providerSessionId});return}await me()},N.current=ce,y(ce),b({title:M.kind==="ide"?ss("restart-ide",M.label):M.providerSessionId?Da(M.label):ss("start-fresh",M.label),description:M.kind==="ide"?rs("restart-ide"):M.providerSessionId?Ea():rs("start-fresh"),confirmLabel:M.kind==="ide"?Is("restart-ide"):M.providerSessionId?Ur(!0):Is("start-fresh"),busyLabel:M.kind==="ide"?Ms("restart-ide"):M.providerSessionId?Pa(!0):Ms("start-fresh"),workspaceOptions:H,details:[{label:"Mode",value:M.kind.toUpperCase()},...M.providerType?[{label:"Provider",value:M.providerType}]:[]]})},[D,O]);if(o.useEffect(()=>{v(de)},[K,de,t]),o.useEffect(()=>{ye&&p(ye)},[ye,t]),!O)return f?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:g,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const te=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nt,{size:14})," Workspace"]}),count:V.length+L.length+R.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ls,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Yr,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx($d,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_d,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:g,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[D.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:D.nicknameInput,onChange:M=>D.setNicknameInput(M.target.value),onKeyDown:M=>{M.key==="Enter"&&D.handleSaveNickname(),M.key==="Escape"&&D.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:D.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>D.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{D.setEditingNickname(!0),D.setNicknameInput(O.machineNickname||"")},title:"Click to set nickname",children:G}),s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[O.platform," · ",O.arch]}),s.jsxs("span",{children:[O.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),O.p2p.available&&s.jsxs("span",{children:["P2P ",O.p2p.state==="connected"?"connected":O.p2p.state]}),O.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:O.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:te.map(M=>s.jsxs("button",{onClick:()=>v(M.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${m===M.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[M.label,M.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${m===M.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:M.count})]},M.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[m==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(lb,{machineEntry:u,providers:A,recentLaunches:ve,currentConversations:z,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:ue,onOpenConversation:F}),s.jsx(mb,{machine:O,machineId:t,providers:A,ideSessions:V,cliSessions:L,acpSessions:R,actions:D,getIcon:P,initialCategory:S,initialWorkspaceId:be,initialWorkspacePath:xe,sendDaemonCommand:a})]}),m==="providers"&&s.jsx(Ux,{machineId:t,providers:A,sendDaemonCommand:a}),m==="overview"&&s.jsx($x,{machineId:t,machine:O,ideSessions:V,cliSessions:L,acpSessions:R,actions:D,sendDaemonCommand:a}),m==="session-host"&&s.jsx(ib,{machineId:t,cliSessions:L,sendDaemonCommand:a}),m==="logs"&&s.jsx(eb,{machineId:t,sendDaemonCommand:a})]})})}),D.launchPick&&O&&s.jsx(cb,{machine:O,launchPick:D.launchPick,actions:D}),j&&s.jsx(Ga,{title:j.title,description:j.description,details:j.details,workspaceOptions:j.workspaceOptions,selectedWorkspaceKey:T,onWorkspaceChange:M=>{N.current=M,y(M)},confirmLabel:j.confirmLabel,busyLabel:j.busyLabel,busy:C,onConfirm:Q,onCancel:()=>{h.current=null,b(null)}}),s.jsx(kc,{toasts:l.toasts||[],onDismiss:M=>l.setToasts(H=>H.filter(ce=>ce.id!==M)),onClickToast:M=>{M.targetKey&&r(Gt(M.targetKey))}}),s.jsx("style",{children:`
|
|
72
72
|
@keyframes toast-in {
|
|
73
73
|
from { opacity: 0; transform: translateX(40px); }
|
|
74
74
|
to { opacity: 1; transform: translateX(0); }
|
|
75
75
|
}
|
|
76
|
-
`})]})}function qa(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function rb(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=qa();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Et(e,t){return await fetch(rb(e),{credentials:"same-origin",...t})}function bl(){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 nb{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(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r)}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,i,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:i,rows:c})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r){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(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Ot=new nb;function ab(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=qa();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Ar=ab(),li=3e3,ob=3e4;let Rt=null,ib=0;const qr=new Map;let Jt=null,Us=null;function di(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Es(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function cb(e){return e==="connected"?"connected":e}async function Er(e,t,r){const n=jc(e,r||{}),a=Rt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++ib}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{qr.delete(i),l(new Error(`WS command timeout: ${t}`))},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:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function da(e,t){const r=Rt;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function lb(e,t,r){const n=Rt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=jc(e,{sessionId:t,targetSessionId:t,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class db{constructor(t){Ge(this,"daemonId");Ge(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Er(this.daemonId,t,r)}async sendInput(t,r){return Er(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Jt&&(clearInterval(Jt),Jt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await 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(t){Jt&&(clearInterval(Jt),Jt=null)}}let At=null;function ub(e){return(!At||At.daemonId!==e)&&(At=new db(e)),At}function mb({children:e}){const t=o.useRef(Gs()),r=Gs();t.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(li),m=o.useRef(!0),w=o.useRef(!1),S=o.useRef("initial_connect");return o.useEffect(()=>{m.current=!0,w.current=!1;function p(){var b,N;if(!m.current||((b=f.current)==null?void 0:b.readyState)===WebSocket.OPEN||((N=f.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Ar}...`),Es("connect_attempt",{url:Ar,reason:S.current,delayMs:h.current});let j;try{j=new WebSocket(Ar)}catch(T){console.error("[Standalone WS] Failed to create WebSocket:",T),x();return}f.current=j,j.onopen=()=>{if(!m.current){j.close();return}u("connected"),h.current=li,Es("open",{url:Ar,reason:S.current}),qt.resubscribeAll({sendData:da}),console.log("[Standalone WS] Connected")},Rt=j,j.onmessage=T=>{var y,C;try{const k=JSON.parse(T.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const v=qr.get(k.requestId);v&&(qr.delete(k.requestId),k.type==="error"?v.reject(new Error(((y=k.data)==null?void 0:y.message)||"Command failed")):v.resolve(k.data));return}if(k.type==="session_output"){const v=k.sessionId||k.cliId||k.cliType;v&&Ot.emitSessionOutput(v,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){Ot.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated,typeof k.cols=="number"?k.cols:void 0,typeof k.rows=="number"?k.rows:void 0);return}if(k.type==="topic_update"){const v=k.update;v&&qt.publish(v);return}if(k.type==="status"||k.type==="initial_state"){const v=k.data;if(!v)return;const{injectEntries:g,markLoaded:D,getIdes:M}=t.current,I=v.instanceId||"standalone",P=M().find(L=>L.id===I),K=ub(I);Ot.register(I,K),Ot.setState(I,"connected"),u("connected",I),Ot.emitStatus(I,v);const V=Fr(v,{daemonId:I,existingDaemon:P,existingEntries:M()});di("ws_status",{type:k.type,daemonId:I,sessions:(v.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:(v.recentLaunches||[]).map(L=>({id:L.id,providerType:L.providerType,kind:L.kind,workspace:L.workspace,lastLaunchedAt:L.lastLaunchedAt}))}),di("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&&g(V,{authoritativeDaemonIds:[I]}),D(),c.current!==I&&((C=i.current)==null||C.call(i),c.current=I,i.current=qt.subscribe({sendData:da},I,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${I}`,params:{includeSessions:!0}},L=>{if(L.topic!=="daemon.metadata")return;const R=t.current.getIdes(),G=R.find(E=>E.id===I),B=Fr(L.status,{daemonId:I,existingDaemon:G,existingEntries:R,timestamp:L.timestamp});B.length>0&&t.current.injectEntries(B,{authoritativeDaemonIds:[I]}),L.userName&&a.current&&a.current(L.userName)}))}}catch(k){console.error("[Standalone WS] Parse error:",k)}},j.onclose=T=>{m.current&&(At==null||At.stopScreenshots(),At&&Ot.setState(At.daemonId,"disconnected"),u("disconnected"),f.current=null,S.current=`close:${T.code}${T.wasClean?":clean":":unclean"}`,Es("close",{code:T.code,reason:T.reason||"",wasClean:T.wasClean}),x())},j.onerror=T=>{w.current||!m.current||(S.current="error",Es("error",{message:T instanceof Event?"event":String(T),readyState:j.readyState}),console.warn("[Standalone WS] Error, will reconnect:",T))}}function x(){if(!m.current)return;clearTimeout(d.current);const j=h.current;console.log(`[Standalone WS] Reconnecting in ${j}ms...`),Es("schedule_reconnect",{reason:S.current,delayMs:j}),d.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,ob),p()},j)}return p(),()=>{var j;m.current=!1,w.current=!0,(j=i.current)==null||j.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),At&&(At.stopScreenshots(),Ot.unregister(At.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function fb({children:e}){const[t,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=t==="connected",l=cb(t),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:t,isConnected:c,connectionStates:u}},[t,n]);return s.jsx(bd,{connectionOverrides:i,children:s.jsx(mb,{children:e})})}const gl="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"}],pb=new Set(ln.map(e=>e.id)),hb=new Set(Zs.map(e=>e.id));function Bt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:$r("chat",t.chat),code:$r("code",t.code),terminal:$r("terminal",t.terminal)}}function $r(e,t){const r=is[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?pb:hb).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Br(e,t){var a;const r=$r(e,t);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 xb(e){const t=Bt(e),r=Br("chat",t.chat),n=Br("code",t.code),a=Br("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Zt(e,t=document.documentElement){const r=Bt(e),n=xb(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function ua(e){const t=Bt(e);try{localStorage.setItem(gl,JSON.stringify(t))}catch{}return t}function bb(){try{const e=localStorage.getItem(gl);if(e)return Bt(JSON.parse(e))}catch{}return is}function gb(){return Zt(bb())}function $s(e,t){var n;const r=e==="chat"?ln:Zs;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const yb=[{id:"dashboard",path:"/dashboard",icon:s.jsx(ki,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(ls,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(Yr,{}),label:"Settings"}];function vb({children:e}){const t=As(),r=pa(),n=o.useMemo(()=>yb.map(i=>({...i,active:r.pathname.startsWith(i.path),onSelect:()=>t(i.path)})),[r.pathname,t]),a=o.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Ni,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Ci,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Rf,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.23"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:i?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const wb=[{icon:s.jsx(ls,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ft,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Ii,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Ct,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Ys,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Ni,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],jb=[{icon:s.jsx(Rd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(ki,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Xr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Cd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Si,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Ad,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],kb=[{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 Sb(){return s.jsxs(Cc,{icon:s.jsx(Ci,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.23"]}),children:[s.jsx(Nt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),s.jsx(Nt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:wb.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(Nt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:kc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Nc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Sc.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(Nt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:jb.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(Nt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:kb.map((e,t)=>s.jsxs("tr",{className:t%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),s.jsx(Ac,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(Hd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Hn(e,t,r){return{...e,[t]:r}}function Fn({surface:e,title:t,description:r,value:n,options:a,onChange:i}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>i({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Br(e,n)})]})]})]})}function Nb({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:u}){const f=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Fn,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:ln,onChange:d=>i(Hn(e,"chat",d))}),s.jsx(Fn,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Zs,onChange:d=>i(Hn(e,"code",d))}),s.jsx(Fn,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Zs,onChange:d=>i(Hn(e,"terminal",d))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",$s("chat",e.chat.preset)," · Code: ",$s("code",e.code.preset)," · Terminal: ",$s("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",$s("chat",is.chat.preset)," / ",$s("code",is.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:c,disabled:r||!f,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:l,disabled:r||!f,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick: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 Cb(){const{ides:e}=cs(),t=e.find(z=>z.type==="adhdev-daemon"),r=(t==null?void 0:t.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),[w,S]=o.useState(!1),[p,x]=o.useState(""),[j,b]=o.useState(""),[N,T]=o.useState("127.0.0.1"),[y,C]=o.useState(""),[k,v]=o.useState(""),[g,D]=o.useState(""),[M,I]=o.useState(""),[P,K]=o.useState(""),[V,L]=o.useState(!1),R=async()=>{const F=await(await Et("/auth/session")).json();u(F)},G=async()=>{const F=await(await Et("/api/v1/standalone/preferences")).json();d(F),T(F.standaloneBindHost);const Q=Bt(F.standaloneFontPreferences);m(Q),Zt(Q),ua(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 F=z.target.value.trim();t!=null&&t.id&&F!==a&&n(t.id,"set_user_name",{userName:F}).catch(console.error)},[E,W]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=z=>{W(z);try{localStorage.setItem("adhdev_sound",z?"1":"0")}catch{}},be=async()=>{x(""),b(""),S(!0);try{const z=Bt(h),F=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:z})}),Q=await F.json();if(!F.ok)throw new Error((Q==null?void 0:Q.error)||"Failed to save standalone font preferences");const ue=Bt(Q.standaloneFontPreferences);d(Q),m(ue),Zt(ue),ua(ue),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(z){x(z instanceof Error?z.message:String(z))}finally{S(!1)}},he=()=>{const z=Bt(f==null?void 0:f.standaloneFontPreferences);x(""),b(""),m(z),Zt(z)},de=()=>{x(""),b(""),m(is),Zt(is)},ye=async()=>{I(""),K(""),L(!0);try{const z=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),F=await z.json();if(!z.ok)throw new Error((F==null?void 0:F.error)||"Failed to save standalone network preference");d(F),T(F.standaloneBindHost),K(F.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)}},ge=async()=>{if(I(""),K(""),k.trim().length<4){I("Password must be at least 4 characters.");return}if(k!==g){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:k})}),F=await z.json();if(!z.ok)throw new Error((F==null?void 0:F.error)||"Failed to save password");u(F),await G(),C(""),v(""),D(""),K(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),bl()}catch(z){I(z instanceof Error?z.message:String(z))}finally{L(!1)}},ve=async()=>{I(""),K(""),L(!0);try{const z=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),F=await z.json();if(!z.ok)throw new Error((F==null?void 0:F.error)||"Failed to clear password");u(F),await G(),C(""),v(""),D(""),K("Standalone password disabled.")}catch(z){I(z instanceof Error?z.message:String(z))}finally{L(!1)}};return s.jsxs(Cc,{icon:s.jsx(Yr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(gr,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&s.jsx(gr,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(Nt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.23"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(Nt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:N==="127.0.0.1",onChange:()=>T("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:N==="0.0.0.0",onChange:()=>T("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:()=>{ye()},disabled: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"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(Nt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),M&&s.jsx(gr,{variant:"error",children:M}),P&&s.jsx(gr,{variant:"success",children:P}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:y,onChange:z=>C(z.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:k,onChange:z=>v(z.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:g,onChange:z=>D(z.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.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…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ve()},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"})]})]})}),s.jsx(Nt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(z=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${z.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:z.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:z.type})]},z.type))})}),s.jsx(Nt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Wf,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(Nt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(zf,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),s.jsx(Zf,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),s.jsx(Nb,{value:h,savedValue:Bt(f==null?void 0:f.standaloneFontPreferences),saving:w,error:p,notice:j,onChange:m,onSave:()=>{be()},onResetToSaved:he,onResetToDefaults:de})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),s.jsx(sp,{})]})]})}),s.jsx(Nt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Bf,{}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Wd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:J})]})}),s.jsx(Nt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Nd,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:i,onChange:z=>c(z.target.value),onBlur:B,onKeyDown:z=>{z.key==="Enter"&&z.currentTarget.blur()}})]})})})]})}Tf();Jf();gb();const Ib=vi({baseUrl:"",getToken:qa});function Ab({children:e}){const[t,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(w){u(w instanceof Error?w.message:String(w))}finally{a(!1)}};o.useEffect(()=>{h()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let w=!1;return(async()=>{try{const S=await Et("/api/v1/standalone/preferences");if(!S.ok)return;const p=await S.json();if(w)return;const x=Bt(p.standaloneFontPreferences);Zt(x),ua(x)}catch{}})(),()=>{w=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const m=async w=>{w.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(""),bl()}catch(S){u(S instanceof Error?S.message:String(S))}finally{d(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:m,children:[s.jsx("input",{type:"password",value:i,onChange:w=>c(w.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled: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"})]}):s.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&s.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function ui(){const{ides:e,initialLoaded:t}=cs();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx(Vn,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Vn,{to:"/dashboard",replace:!0})}function Mb(){const e=o.useMemo(()=>({sendCommand:Er,sendData:da,sendPtyInput:lb}),[]);return s.jsx(ed,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(vd,{client:Ib,children:s.jsx(Ab,{children:s.jsx(fb,{children:s.jsx(jd,{value:e,children:s.jsx(vb,{children:s.jsxs(td,{children:[s.jsx(Yt,{path:"/dashboard",element:s.jsx(Sx,{})}),s.jsx(Yt,{path:"/machine",element:s.jsx(ui,{})}),s.jsx(Yt,{path:"/machines/:id",element:s.jsx(sb,{})}),s.jsx(Yt,{path:"/machines",element:s.jsx(ui,{})}),s.jsx(Yt,{path:"/about",element:s.jsx(Sb,{})}),s.jsx(Yt,{path:"/settings",element:s.jsx(Cb,{})}),s.jsx(Yt,{path:"*",element:s.jsx(Vn,{to:"/dashboard",replace:!0})})]})})})})})})})}qm({connectionManager:Ot});sd(document.getElementById("root")).render(s.jsx(Mb,{}));
|
|
76
|
+
`})]})}function Xa(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function pb(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=Xa();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Et(e,t){return await fetch(pb(e),{credentials:"same-origin",...t})}function wl(){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 hb{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(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r)}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,i,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:i,rows:c})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r){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(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Wt=new hb;function xb(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Xa();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Mr=xb(),pi=3e3,bb=3e4;let Rt=null,gb=0;const qr=new Map;let Jt=null,Gs=null;function hi(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Ks(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function yb(e){return e==="connected"?"connected":e}async function Er(e,t,r){const n=Cc(e,r||{}),a=Rt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++gb}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{qr.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);qr.set(i,{resolve:f=>{clearTimeout(d),c(f)},reject:f=>{clearTimeout(d),l(f)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function da(e,t){const r=Rt;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function vb(e,t,r){const n=Rt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Cc(e,{sessionId:t,targetSessionId:t,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class wb{constructor(t){Ge(this,"daemonId");Ge(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Er(this.daemonId,t,r)}async sendInput(t,r){return Er(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Jt&&(clearInterval(Jt),Jt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await 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());Wt.emitScreenshot(this.daemonId,a)}}catch{}};r(),Jt=setInterval(r,2e3)}stopScreenshots(t){Jt&&(clearInterval(Jt),Jt=null)}}let Mt=null;function jb(e){return(!Mt||Mt.daemonId!==e)&&(Mt=new wb(e)),Mt}function kb({children:e}){const t=o.useRef(Ys()),r=Ys();t.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"),d=o.useCallback((p,h)=>{l(p),Gs==null||Gs(p,h)},[]),f=o.useRef(null),u=o.useRef(),x=o.useRef(pi),m=o.useRef(!0),v=o.useRef(!1),S=o.useRef("initial_connect");return o.useEffect(()=>{m.current=!0,v.current=!1;function p(){var b,N;if(!m.current||((b=f.current)==null?void 0:b.readyState)===WebSocket.OPEN||((N=f.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Mr}...`),Ks("connect_attempt",{url:Mr,reason:S.current,delayMs:x.current});let j;try{j=new WebSocket(Mr)}catch(T){console.error("[Standalone WS] Failed to create WebSocket:",T),h();return}f.current=j,j.onopen=()=>{if(!m.current){j.close();return}d("connected"),x.current=pi,Ks("open",{url:Mr,reason:S.current}),qt.resubscribeAll({sendData:da}),console.log("[Standalone WS] Connected")},Rt=j,j.onmessage=T=>{var y,C;try{const k=JSON.parse(T.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const w=qr.get(k.requestId);w&&(qr.delete(k.requestId),k.type==="error"?w.reject(new Error(((y=k.data)==null?void 0:y.message)||"Command failed")):w.resolve(k.data));return}if(k.type==="session_output"){const w=k.sessionId||k.cliId||k.cliType;w&&Wt.emitSessionOutput(w,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){Wt.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated,typeof k.cols=="number"?k.cols:void 0,typeof k.rows=="number"?k.rows:void 0);return}if(k.type==="topic_update"){const w=k.update;w&&qt.publish(w);return}if(k.type==="status"||k.type==="initial_state"){const w=k.data;if(!w)return;const{injectEntries:g,markLoaded:D,getIdes:A}=t.current,I=w.instanceId||"standalone",P=A().find(L=>L.id===I),O=jb(I);Wt.register(I,O),Wt.setState(I,"connected"),d("connected",I),Wt.emitStatus(I,w);const V=Fr(w,{daemonId:I,existingDaemon:P,existingEntries:A()});hi("ws_status",{type:k.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}))}),hi("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&&g(V,{authoritativeDaemonIds:[I]}),D(),c.current!==I&&((C=i.current)==null||C.call(i),c.current=I,i.current=qt.subscribe({sendData:da},I,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${I}`,params:{includeSessions:!0}},L=>{if(L.topic!=="daemon.metadata")return;const R=t.current.getIdes(),G=R.find(E=>E.id===I),K=Fr(L.status,{daemonId:I,existingDaemon:G,existingEntries:R,timestamp:L.timestamp});K.length>0&&t.current.injectEntries(K,{authoritativeDaemonIds:[I]}),L.userName&&a.current&&a.current(L.userName)}))}}catch(k){console.error("[Standalone WS] Parse error:",k)}},j.onclose=T=>{m.current&&(Mt==null||Mt.stopScreenshots(),Mt&&Wt.setState(Mt.daemonId,"disconnected"),d("disconnected"),f.current=null,S.current=`close:${T.code}${T.wasClean?":clean":":unclean"}`,Ks("close",{code:T.code,reason:T.reason||"",wasClean:T.wasClean}),h())},j.onerror=T=>{v.current||!m.current||(S.current="error",Ks("error",{message:T instanceof Event?"event":String(T),readyState:j.readyState}),console.warn("[Standalone WS] Error, will reconnect:",T))}}function h(){if(!m.current)return;clearTimeout(u.current);const j=x.current;console.log(`[Standalone WS] Reconnecting in ${j}ms...`),Ks("schedule_reconnect",{reason:S.current,delayMs:j}),u.current=setTimeout(()=>{x.current=Math.min(x.current*1.5,bb),p()},j)}return p(),()=>{var j;m.current=!1,v.current=!0,(j=i.current)==null||j.call(i),i.current=null,c.current=null,clearTimeout(u.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),Mt&&(Mt.stopScreenshots(),Wt.unregister(Mt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function Sb({children:e}){const[t,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Gs=(c,l)=>{r(c),l&&a(l)},()=>{Gs=null}),[]);const i=o.useMemo(()=>{const c=t==="connected",l=yb(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(Sd,{connectionOverrides:i,children:s.jsx(kb,{children:e})})}const jl="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"}],tr=[{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"}],Nb=new Set(ln.map(e=>e.id)),Cb=new Set(tr.map(e=>e.id));function Bt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:$r("chat",t.chat),code:$r("code",t.code),terminal:$r("terminal",t.terminal)}}function $r(e,t){const r=is[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?Nb:Cb).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Br(e,t){var a;const r=$r(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?ln:tr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function Ib(e){const t=Bt(e),r=Br("chat",t.chat),n=Br("code",t.code),a=Br("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Zt(e,t=document.documentElement){const r=Bt(e),n=Ib(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function ua(e){const t=Bt(e);try{localStorage.setItem(jl,JSON.stringify(t))}catch{}return t}function Mb(){try{const e=localStorage.getItem(jl);if(e)return Bt(JSON.parse(e))}catch{}return is}function Ab(){return Zt(Mb())}function Os(e,t){var n;const r=e==="chat"?ln:tr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Tb=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Mi,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(ls,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(Yr,{}),label:"Settings"}];function Lb({children:e}){const t=As(),r=pa(),n=o.useMemo(()=>Tb.map(i=>({...i,active:r.pathname.startsWith(i.path),onSelect:()=>t(i.path)})),[r.pathname,t]),a=o.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Ti,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Li,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Ff,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.25"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:i?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const Rb=[{icon:s.jsx(ls,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ut,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Ri,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Nt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Js,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Ti,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Pb=[{icon:s.jsx(Kd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Mi,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Xr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Pd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Ai,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Dd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],_b=[{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 Db(){return s.jsxs(Tc,{icon:s.jsx(Li,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.25"]}),children:[s.jsx(St,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),s.jsx(St,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Rb.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(St,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Ic.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Ac.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Mc.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(St,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Pb.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(St,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:_b.map((e,t)=>s.jsxs("tr",{className:t%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),s.jsx(Rc,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(Yd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Hn(e,t,r){return{...e,[t]:r}}function Fn({surface:e,title:t,description:r,value:n,options:a,onChange:i}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>i({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Br(e,n)})]})]})]})}function Eb({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:d}){const f=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Fn,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:ln,onChange:u=>i(Hn(e,"chat",u))}),s.jsx(Fn,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:tr,onChange:u=>i(Hn(e,"code",u))}),s.jsx(Fn,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:tr,onChange:u=>i(Hn(e,"terminal",u))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Os("chat",e.chat.preset)," · Code: ",Os("code",e.code.preset)," · Terminal: ",Os("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Os("chat",is.chat.preset)," / ",Os("code",is.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:c,disabled:r||!f,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:l,disabled:r||!f,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick:d,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function $b(){const{ides:e}=cs(),t=e.find(z=>z.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=wt(),{userName:a}=cs(),[i,c]=o.useState(a||""),[l,d]=o.useState(null),[f,u]=o.useState(null),[x,m]=o.useState(is),[v,S]=o.useState(!1),[p,h]=o.useState(""),[j,b]=o.useState(""),[N,T]=o.useState("127.0.0.1"),[y,C]=o.useState(""),[k,w]=o.useState(""),[g,D]=o.useState(""),[A,I]=o.useState(""),[P,O]=o.useState(""),[V,L]=o.useState(!1),R=async()=>{const F=await(await Et("/auth/session")).json();d(F)},G=async()=>{const F=await(await Et("/api/v1/standalone/preferences")).json();u(F),T(F.standaloneBindHost);const Q=Bt(F.standaloneFontPreferences);m(Q),Zt(Q),ua(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(x)},[x]);const K=z=>{const F=z.target.value.trim();t!=null&&t.id&&F!==a&&n(t.id,"set_user_name",{userName:F}).catch(console.error)},[E,W]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=z=>{W(z);try{localStorage.setItem("adhdev_sound",z?"1":"0")}catch{}},be=async()=>{h(""),b(""),S(!0);try{const z=Bt(x),F=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:z})}),Q=await F.json();if(!F.ok)throw new Error((Q==null?void 0:Q.error)||"Failed to save standalone font preferences");const ue=Bt(Q.standaloneFontPreferences);u(Q),m(ue),Zt(ue),ua(ue),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(z){h(z instanceof Error?z.message:String(z))}finally{S(!1)}},xe=()=>{const z=Bt(f==null?void 0:f.standaloneFontPreferences);h(""),b(""),m(z),Zt(z)},de=()=>{h(""),b(""),m(is),Zt(is)},ye=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})}),F=await z.json();if(!z.ok)throw new Error((F==null?void 0:F.error)||"Failed to save standalone network preference");u(F),T(F.standaloneBindHost),O(F.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)}},ge=async()=>{if(I(""),O(""),k.trim().length<4){I("Password must be at least 4 characters.");return}if(k!==g){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:k})}),F=await z.json();if(!z.ok)throw new Error((F==null?void 0:F.error)||"Failed to save password");d(F),await G(),C(""),w(""),D(""),O(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),wl()}catch(z){I(z instanceof Error?z.message:String(z))}finally{L(!1)}},ve=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})}),F=await z.json();if(!z.ok)throw new Error((F==null?void 0:F.error)||"Failed to clear password");d(F),await G(),C(""),w(""),D(""),O("Standalone password disabled.")}catch(z){I(z instanceof Error?z.message:String(z))}finally{L(!1)}};return s.jsxs(Tc,{icon:s.jsx(Yr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(gr,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&s.jsx(gr,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(St,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.25"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(St,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:N==="127.0.0.1",onChange:()=>T("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:N==="0.0.0.0",onChange:()=>T("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:()=>{ye()},disabled: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"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(St,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),A&&s.jsx(gr,{variant:"error",children:A}),P&&s.jsx(gr,{variant:"success",children:P}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:y,onChange:z=>C(z.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:k,onChange:z=>w(z.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:g,onChange:z=>D(z.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.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…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ve()},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"})]})]})}),s.jsx(St,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(z=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${z.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:z.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:z.type})]},z.type))})}),s.jsx(St,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Qf,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(St,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(sp,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),s.jsx(dp,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),s.jsx(Eb,{value:x,savedValue:Bt(f==null?void 0:f.standaloneFontPreferences),saving:v,error:p,notice:j,onChange:m,onSave:()=>{be()},onResetToSaved:xe,onResetToDefaults:de})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),s.jsx(fp,{})]})]})}),s.jsx(St,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Yf,{}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(qd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:J})]})}),s.jsx(St,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Rd,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:i,onChange:z=>c(z.target.value),onBlur:K,onKeyDown:z=>{z.key==="Enter"&&z.currentTarget.blur()}})]})})})]})}Wf();cp();Ab();const Bb=Ni({baseUrl:"",getToken:Xa});function Kb({children:e}){const[t,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,d]=o.useState(""),[f,u]=o.useState(!1),x=async()=>{a(!0),d("");try{const S=await(await Et("/auth/session")).json();r(S)}catch(v){d(v instanceof Error?v.message:String(v))}finally{a(!1)}};o.useEffect(()=>{x()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let v=!1;return(async()=>{try{const S=await Et("/api/v1/standalone/preferences");if(!S.ok)return;const p=await S.json();if(v)return;const h=Bt(p.standaloneFontPreferences);Zt(h),ua(h)}catch{}})(),()=>{v=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const m=async v=>{v.preventDefault(),u(!0),d("");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(""),wl()}catch(S){d(S instanceof Error?S.message:String(S))}finally{u(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:m,children:[s.jsx("input",{type:"password",value:i,onChange:v=>c(v.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled: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"})]}):s.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&s.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function xi(){const{ides:e,initialLoaded:t}=cs();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx(Vn,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Vn,{to:"/dashboard",replace:!0})}function Ob(){const e=o.useMemo(()=>({sendCommand:Er,sendData:da,sendPtyInput:vb}),[]);return s.jsx(id,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Id,{client:Bb,children:s.jsx(Kb,{children:s.jsx(Sb,{children:s.jsx(Ad,{value:e,children:s.jsx(Lb,{children:s.jsxs(cd,{children:[s.jsx(Yt,{path:"/dashboard",element:s.jsx(Dx,{})}),s.jsx(Yt,{path:"/machine",element:s.jsx(xi,{})}),s.jsx(Yt,{path:"/machines/:id",element:s.jsx(fb,{})}),s.jsx(Yt,{path:"/machines",element:s.jsx(xi,{})}),s.jsx(Yt,{path:"/about",element:s.jsx(Db,{})}),s.jsx(Yt,{path:"/settings",element:s.jsx($b,{})}),s.jsx(Yt,{path:"*",element:s.jsx(Vn,{to:"/dashboard",replace:!0})})]})})})})})})})}af({connectionManager:Wt});ld(document.getElementById("root")).render(s.jsx(Ob,{}));
|