@adhdev/daemon-standalone 0.9.24 → 0.9.26

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.
@@ -0,0 +1,76 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-Bv6gUGuY.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
+ var td=Object.defineProperty;var sd=(e,t,r)=>t in e?td(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ge=(e,t,r)=>sd(e,typeof t!="symbol"?t+"":t,r);import{r as o,j as s,M as ma,a as fa,b as gi,c as yi,u as As,R as kt,d as qs,t as rd,e as nd,D as ad,f as Un,g as zn,h as pa,i as od,k as id,B as cd,l as ld,m as Yt,N as Vn,n as dd}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 ud(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=ud();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 md(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function fd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function vi(e,t){var f;if(!e)return t??null;if(!t)return e??null;const r=fd(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=md(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(t==null?void 0:t.parentSessionId)??null,providerSessionId:e.providerSessionId??(t==null?void 0:t.providerSessionId),providerName:r??(t==null?void 0:t.providerName)??(t==null?void 0:t.cliName)??(t==null?void 0:t.type)??e.providerName??e.providerType,title:e.title??(t==null?void 0:t.title)??r??(t==null?void 0:t.providerName)??e.providerName??e.providerType,workspace:e.workspace??(t==null?void 0:t.workspace)??null,mode:e.mode??(t==null?void 0:t.mode),capabilities:e.capabilities??(t==null?void 0:t.sessionCapabilities)??(t==null?void 0:t.capabilities)??[],cdpConnected:e.cdpConnected??(t==null?void 0:t.cdpConnected),activeChat:vi(e.activeChat,t==null?void 0:t.activeChat),controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel)}}function wi(e,t,r){if(!(t!=null&&t.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const n=t.map(a=>{const i=e.find(c=>c.id===a.id);return i?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 ji=o.createContext({ides:[],updateRouteChats:()=>{},initialLoaded:!1,toasts:[],setToasts:()=>{},wsStatus:"connected",isConnected:!0,connectionStates:{},connectionTransports:{},showReconnected:!1,userName:void 0,setUserName:()=>{},isP2PActive:!1,p2pStates:{},userRole:void 0}),ki=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function 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 Si(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,i=t.serverVersion??e.serverVersion??r.serverVersion,c=t.versionMismatch===!0||e.versionMismatch===!0,l=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,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 pd(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=pd(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 hd(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"?hd(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 xd(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 xd(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Ni(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function bd(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=wi(e.childSessions,t.childSessions,{preserveMissing:n}),c=vi(t.activeChat,e.activeChat);return Si(e,t,{...e,...t,chats:a,childSessions:i,activeChat:c,_lastUpdate:r})}function gd(e,t,r){var a,i;const n={};t.status&&t.status!==e.status&&(n.status=t.status),t.cdpConnected!==void 0&&(n.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(n.childSessions=wi(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((i=e.chats)!=null&&i.length)&&(n.chats=t.chats);for(const c of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion"])bd(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function yd(e,t,r,n){const a=gd(e,t,n),i=Object.keys(a).length>0?Si(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return Yn(e,i,r)}function vd(e){const t=new Set(e.map(a=>a.id)),r=new Set,n=new Set;for(const a of e){const i=Ni(a);i&&r.add(i),i&&a.type!=="adhdev-daemon"&&n.add(i)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n}}function wd(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 jd(e,t,r,n){return!!(r.has(t)&&e.transport&&!n.has(t))}function kd(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}=vd(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=Ni(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,yd(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);wd(m,v,S,c,a,d)&&i.delete(x)}for(const[x,m]of i){const v=m.daemonId||x.split(":")[0];if(jd(m,v,l,d))continue;n-(m._lastUpdate||m.timestamp||0)>3e5&&m.status!=="online"&&i.delete(x)}return Array.from(i.values())}function Sd(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 Nd({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 A=!1;const y=N.map(I=>I.id!==j||I.chats===b?I:(A=!0,{...I,chats:b}));return A?y:N})},[]),m=o.useCallback((j,b)=>{n(N=>{const A=N.length===0?j:kd(j,N,b),y=!Sd(N,A);return y&&ks.record({kind:"dashboard.entries_applied",payload:{incoming:oo(j),next:oo(A)}}),y?A: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(ki.Provider,{value:S,children:s.jsx(ji.Provider,{value:h,children:e})})}function cs(){return o.useContext(ji)}function Ys(){return o.useContext(ki)}function Ci(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function i(l){const 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 Cd=Ci({baseUrl:"http://localhost:3847"}),Id=o.createContext(Cd);function Md({client:e,children:t}){return s.jsx(Id.Provider,{value:e,children:t})}const Ad={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Ii=o.createContext(Ad);function Td({value:e,children:t}){return s.jsx(Ii.Provider,{value:e,children:t})}function wt(){return o.useContext(Ii)}function Ld(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 Rd(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Mi(e){return e?Ld([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Rd(e.content)]):""}const Ee={size: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("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 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:"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 Pd({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 _d({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 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("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 Dd({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 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("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 Ed({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 $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("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 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:"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 _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("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),s.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Di({size:e=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 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("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 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("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 Ei({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 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("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 Wd({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 Hd({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 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("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 Ud({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 zd({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 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("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 Gd({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 qd({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 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("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 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("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 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("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 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("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=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 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:"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 tu({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 $i=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 su(e){if(!Array.isArray(e)||e.length===0)return"0:empty";const t=e[e.length-1];return`${e.length}:${Mi(t)}`}function ru(e,t){return!e&&t}function fo(e,t=$i){return!!e&&e.fromBottom>=t}function nu({hasSelection:e,userScrolledUp:t}){return!(e||t)}function au({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 Bi(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function ou(e,t,r){return Number(e.receivedAt||r[Kr(e,t)]||0)||0}function Ki(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function iu(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}):Ki(e)?s.jsx(ma,{remarkPlugins:[fa,gi,yi],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 cu=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:Bi(t.timestamp)})]})},(e,t)=>e.log===t.log),lu=o.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var I,k,w;const d=(t.role||"").toLowerCase(),f=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),x=iu(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((I=t.meta)==null?void 0:I.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(Hd,{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?"⏳":"✅",E=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:E})]}),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,A=h,y=!A&&Ki(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:Bi(r)})]}),(j||m)&&s.jsx("div",{className:"chat-markdown",children:m&&x?s.jsx(mr,{parts:x,renderAsPreformatted:A}):A?s.jsx("pre",{className:"chat-preformatted",children:N}):y?s.jsx(ma,{remarkPlugins:[fa,gi,yi],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),du=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),A=o.useRef(null),y=o.useRef(0),I=o.useRef(""),k=o.useRef(!1),w=o.useRef(null),g=o.useRef(!1),E=o.useRef(null),M=o.useRef(!1),[C,R]=o.useState(new Set),K=o.useRef(!1),z=o.useRef(!1),T=o.useRef(h),L=()=>{const H=b.current;return H?H.scrollHeight-H.scrollTop-H.clientHeight<$i:!0},Y=o.useCallback((H="auto")=>{const Z=b.current;Z&&Z.scrollTo({top:Z.scrollHeight,behavior:H})},[]),O=o.useCallback(()=>{var fe;const H=b.current,Z=(fe=window.getSelection)==null?void 0:fe.call(window);if(!H||!Z||Z.rangeCount===0||Z.isCollapsed){M.current=!1;return}const me=Z.anchorNode,ne=Z.focusNode;M.current=!!(me&&ne&&H.contains(me)&&H.contains(ne))},[]),D=su(t),W=o.useCallback(()=>{const H=b.current;!H||!l||un.set(l,{top:H.scrollTop,fromBottom:Math.max(0,H.scrollHeight-H.scrollTop-H.clientHeight),messageFingerprint:D})},[l,D]),Q=o.useCallback((H="auto")=>{w.current!=null&&cancelAnimationFrame(w.current),w.current=requestAnimationFrame(()=>{w.current=null,Y(H)})},[Y]),be=o.useCallback(()=>{K.current=!1,g.current=!0,z.current=!0,E.current!=null&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>{g.current=!1,E.current=null},uo)},[]);o.useEffect(()=>{const H=!k.current,Z=I.current!==l;if(I.current=l,H||Z){if(k.current=!0,K.current=!1,g.current=!0,!M.current){const me=l?un.get(l):null;me&&mo(me,D)?requestAnimationFrame(()=>{const ne=b.current;ne&&(po(ne,me),K.current=fo(me),z.current=!0)}):Q("auto")}y.current=t.length;return}t.length>y.current,nu({hasSelection:M.current,userScrolledUp:K.current})&&Q("auto"),y.current=t.length},[D,l,c,t.length,Q]),o.useEffect(()=>{p&&(be(),M.current||Q("auto"))},[be,Q,p]),o.useEffect(()=>{const H=T.current;T.current=h,ru(H,h)&&(be(),M.current||Q("auto"))},[h,be,Q]),o.useEffect(()=>()=>{W(),w.current!=null&&cancelAnimationFrame(w.current),E.current!=null&&window.clearTimeout(E.current)},[W]),o.useEffect(()=>{const H=N.current,Z=b.current;if(!H||!Z)return;const me=()=>{E.current!=null&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>{g.current=!1,E.current=null},uo)},ne=new ResizeObserver(()=>{const fe=g.current;au({hasSelection:M.current,userScrolledUp:K.current,contextAutoScrollActive:fe})&&(Q("auto"),fe&&me())});return ne.observe(H),Z!==H&&ne.observe(Z),()=>{ne.disconnect(),E.current!=null&&(window.clearTimeout(E.current),E.current=null)}},[Q,l]),o.useImperativeHandle(j,()=>({scrollToBottom:(H="smooth")=>{Y(H)}}),[Y]),o.useEffect(()=>{const H=b.current;if(!H)return;let Z;const me=()=>{clearTimeout(Z),Z=setTimeout(()=>{K.current=!L(),W()},50)};return H.addEventListener("scroll",me,{passive:!0}),()=>{H.removeEventListener("scroll",me),clearTimeout(Z)}},[W]),o.useEffect(()=>(document.addEventListener("selectionchange",O),()=>document.removeEventListener("selectionchange",O)),[O]);const pe=o.useRef(0),ue=o.useRef(!1);o.useEffect(()=>{const H=b.current;if(!H||!ue.current||pe.current===0)return;const Z=H.scrollHeight-pe.current;Z>0&&(H.scrollTop=Z),W(),pe.current=0,ue.current=!1},[t.length,W]),o.useEffect(()=>{if(z.current||!l)return;const H=un.get(l),Z=b.current;if(!(!H||!Z)){if(!mo(H,D)){Y("auto"),z.current=!0;return}po(Z,H),K.current=fo(H),z.current=!0}},[l,D,t.length,Y]);const we=()=>{const H=b.current;H&&(pe.current=H.scrollHeight),ue.current=!0,u==null||u()},ye=o.useMemo(()=>{const H=t.map((fe,se)=>({type:"message",data:fe,index:se,ts:ou(fe,se,d)}));if(!r||r.length===0)return H;const Z=[...r].sort((fe,se)=>fe.timestamp-se.timestamp).map((fe,se)=>({type:"action",data:fe,index:se,ts:fe.timestamp})),me=[];let ne=0;for(const fe of H){for(;ne<Z.length&&fe.ts>0&&Z[ne].ts<fe.ts;)me.push(Z[ne++]);me.push(fe)}for(;ne<Z.length;)me.push(Z[ne++]);return me},[t,r,d]),ve=v>0||!!m,V=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:we,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:V})}),ye.length===0&&!ve&&(f||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ye.map(H=>{if(H.type==="action"){const ie=H.data;return s.jsx(cu,{log:ie},`action-${H.index}`)}const Z=H.data,me=H.index,ne=Kr(Z,me),fe=Z.receivedAt||d[ne],se=`${l}-${ne}`,xe=C.has(se);return s.jsx(lu,{message:Z,receivedAt:fe,agentName:n,userName:a,isCliMode:i,isTextExpanded:xe,onToggleTextExpanded:()=>R(ie=>{const ce=new Set(ie);return xe?ce.delete(se):ce.add(se),ce})},`msg-${ne}`)}),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:A})]})})}),uu=o.memo(du,(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),mu="modulepreload",fu=function(e){return"/"+e},xo={},pu=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=fu(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":mu,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 Oi=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 pu(()=>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"}})});Oi.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 hu({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 xu({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 bu({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 gu(){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(!gu())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 yu({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,A]=o.useState(null),y=o.useRef(null),I=o.useRef(null),k=o.useRef(null),w=o.useRef(!1),g=o.useRef(null),E=o.useRef(0),M=o.useRef(null),C=o.useRef(1),R=o.useRef({x:0,y:0}),K=o.useRef(!1),z=o.useRef(n),T=o.useRef(v),L=30,Y=550,O=18,D=60,W=400,Q=12,be=()=>{if(y.current)return;const we={nx:.5,ny:.5};y.current=we,A(we)};return o.useEffect(()=>{z.current=n,n==="mouse"&&be()},[n]),o.useEffect(()=>{T.current=v},[v]),o.useEffect(()=>{const we=e.current;if(!we)return;const ye=ne=>{if(!r.current)return null;const fe=r.current.getBoundingClientRect();return!fe.width||!fe.height?null:{nx:Math.max(0,Math.min(1,(ne.clientX-fe.left)/fe.width)),ny:Math.max(0,Math.min(1,(ne.clientY-fe.top)/fe.height))}},ve=(ne,fe)=>{if(!r.current)return{dnx:0,dny:0};const se=r.current,xe=se.getBoundingClientRect(),ie=se.naturalWidth||xe.width,ce=se.naturalHeight||xe.height,ae=ie/ce,X=xe.width/xe.height;let J,oe;return ae>X?(J=xe.width,oe=xe.width/ae):(oe=xe.height,J=xe.height*ae),{dnx:ne/J,dny:fe/oe}},V=(ne,fe,se)=>{if(se<=1.05)return;const xe=-(ne-.5)*100,ie=-(fe-.5)*100,ce=h(xe,ie,se);(Math.abs(ce.x-l.current)>.1||Math.abs(ce.y-d.current)>.1)&&(f(ce.x),u(ce.y),l.current=ce.x,d.current=ce.y)},H=ne=>{const fe=t.current;if(fe&&ne.target instanceof Node&&fe.contains(ne.target))ne.preventDefault();else return;if(ne.touches.length===1){const se=ne.touches[0];I.current={x:se.clientX,y:se.clientY,time:Date.now()},k.current={x:se.clientX,y:se.clientY},K.current||(w.current=!1),g.current=setTimeout(()=>{if(!w.current&&!K.current)if(w.current=!0,z.current==="mouse"){const xe=y.current||{nx:.5,ny:.5};S("Right Click"),p(xe.nx,xe.ny,"right"),T.current("input_click",{...xe,button:"right"}).catch(()=>{})}else{const xe=ye(se);xe&&(S("Right Click"),p(xe.nx,xe.ny,"right"),T.current("input_click",{...xe,button:"right"}).catch(()=>{}))}},500);return}if(ne.touches.length===2){g.current&&clearTimeout(g.current),w.current=!0,K.current=!0;const se=ne.touches[1].clientX-ne.touches[0].clientX,xe=ne.touches[1].clientY-ne.touches[0].clientY;M.current=Math.sqrt(se*se+xe*xe),C.current=c.current,R.current={x:(ne.touches[0].clientX+ne.touches[1].clientX)/2,y:(ne.touches[0].clientY+ne.touches[1].clientY)/2}}},Z=ne=>{const fe=t.current;if(fe&&ne.target instanceof Node&&fe.contains(ne.target)&&ne.preventDefault(),ne.touches.length===1&&k.current){const se=ne.touches[0],xe=se.clientX-k.current.x,ie=se.clientY-k.current.y;if(!w.current&&I.current){const ce=se.clientX-I.current.x,ae=se.clientY-I.current.y;Math.sqrt(ce*ce+ae*ae)>8&&(w.current=!0,g.current&&clearTimeout(g.current))}if(w.current)if(z.current==="mouse"){const ce=ve(xe,ie),ae=y.current||{nx:.5,ny:.5},X=Math.max(0,Math.min(1,ae.nx+ce.dnx)),J=Math.max(0,Math.min(1,ae.ny+ce.dny));y.current={nx:X,ny:J},A({nx:X,ny:J}),S(`Cursor: ${Math.round(X*100)}%, ${Math.round(J*100)}%`),V(X,J,c.current);const oe=Date.now();oe-m.current>=30&&(m.current=oe,T.current("input_mouseMoved",{nx:X,ny:J}).catch(()=>{}))}else if(c.current>1){const ce=t.current;if(ce){const ae=ce.clientWidth,X=ce.clientHeight,J=l.current+xe/ae*100,oe=d.current+ie/X*100,P=h(J,oe,c.current);f(P.x),u(P.y),l.current=P.x,d.current=P.y}}else{const ce=ye(se);if(ce){const ae=Date.now();ae-m.current>=40&&(m.current=ae,S("Scroll"),T.current("input_wheel",{nx:ce.nx,ny:ce.ny,deltaX:Math.round(-xe*2.5),deltaY:Math.round(-ie*2.5)}).catch(()=>{}))}}k.current={x:se.clientX,y:se.clientY};return}if(ne.touches.length===2&&M.current!==null){const se=ne.touches[1].clientX-ne.touches[0].clientX,xe=ne.touches[1].clientY-ne.touches[0].clientY,ce=Math.sqrt(se*se+xe*xe)/M.current,ae=(ne.touches[0].clientX+ne.touches[1].clientX)/2,X=(ne.touches[0].clientY+ne.touches[1].clientY)/2,J=ae-R.current.x,oe=X-R.current.y,P=Math.abs(ce-1)>.03;if(z.current==="mouse"){if(P){const G=Math.max(i,Math.min(5,C.current*ce));x(G),c.current=G}else if(Math.abs(J)>2||Math.abs(oe)>2){const G=y.current||{nx:.5,ny:.5},U=Date.now();U-m.current>=30&&(m.current=U,S("Scroll"),T.current("input_wheel",{nx:G.nx,ny:G.ny,deltaX:Math.round(-J*3),deltaY:Math.round(-oe*3)}).catch(()=>{}))}}else{const G=Math.max(i,Math.min(5,C.current*ce));x(G),c.current=G;const U=t.current;if(U&&G>1){const de=U.clientWidth,Ne=U.clientHeight,_e=l.current+J/de*100,ge=d.current+oe/Ne*100,Be=h(_e,ge,G);f(Be.x),u(Be.y),l.current=Be.x,d.current=Be.y}}R.current={x:ae,y:X}}},me=ne=>{var fe;if(g.current&&clearTimeout(g.current),M.current=null,ne.touches.length===1&&K.current){const se=ne.touches[0];I.current={x:se.clientX,y:se.clientY,time:Date.now()},k.current={x:se.clientX,y:se.clientY},w.current=!0;return}if(ne.touches.length===0){if(K.current){K.current=!1,w.current=!1;return}if(ne.changedTouches.length===1){const se=ne.changedTouches[0],xe=Date.now(),ie=xe-(((fe=I.current)==null?void 0:fe.time)||0),ce=I.current?se.clientX-I.current.x:0,ae=I.current?se.clientY-I.current.y:0,X=Math.sqrt(ce*ce+ae*ae);if(z.current==="mouse"){if(ie<L||ie>Y||X>O){w.current=!1;return}const J=y.current||ye(se);J&&(S(`Click: ${Math.round(J.nx*100)}%, ${Math.round(J.ny*100)}%`),p(J.nx,J.ny,"left"),T.current("input_click",{...J}).catch(()=>{}))}else{if(w.current){w.current=!1;return}if(ie<D||ie>W||X>Q){w.current=!1;return}const J=ye(se);if(!J)return;xe-E.current<300?(S("Double tap"),p(J.nx,J.ny,"double"),T.current("input_click",{...J,clickCount:2}).catch(()=>{}),E.current=0):(S(`Tap: ${Math.round(J.nx*100)}%, ${Math.round(J.ny*100)}%`),p(J.nx,J.ny,"left"),T.current("input_click",{...J}).catch(()=>{}),E.current=xe)}}w.current=!1}};return we.addEventListener("touchstart",H,{passive:!1}),we.addEventListener("touchmove",Z,{passive:!1}),we.addEventListener("touchend",me,{passive:!1}),()=>{we.removeEventListener("touchstart",H),we.removeEventListener("touchmove",Z),we.removeEventListener("touchend",me),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(we=>{const ye=we==="touch"?"mouse":"touch";return ye==="mouse"&&be(),ye})},handleZoomReset:()=>{const we=j?b:1;x(we),c.current=we,f(0),u(0),l.current=0,d.current=0}}}function Wi({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,A]=o.useState(!1),y=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[I,k]=o.useState(y?"mouse":"touch"),[w,g]=o.useState(1),E=o.useRef(!1),[M,C]=o.useState(1),[R,K]=o.useState(0),[z,T]=o.useState(0);rr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:I,zoom:M,panX:R,panY:z,isMenuOpen:j,isImeOpen:N});const L=o.useRef(0),Y=o.useRef(M),O=o.useRef(R),D=o.useRef(z);o.useEffect(()=>{Y.current=M},[M]),o.useEffect(()=>{O.current=R},[R]),o.useEffect(()=>{D.current=z},[z]),o.useEffect(()=>{var ie;(ie=c.current)==null||ie.focus()},[]);const W=r==="connected",Q=n,be=W?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",pe=W?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!y||E.current||!Q)return;const ie=d.current,ce=l.current;if(!ie||!ce)return;const ae=()=>{const X=ce.clientWidth,J=ce.clientHeight,oe=ie.naturalWidth,P=ie.naturalHeight;if(!oe||!P||!X||!J)return;const G=Math.min(X/oe,J/P),de=Math.max(X/oe,J/P)/G;de>1.01&&(g(de),C(de),Y.current=de),E.current=!0};ie.complete&&ie.naturalWidth?ae():ie.addEventListener("load",ae,{once:!0})},[Q,y]);const ue=.5;o.useEffect(()=>{M<=ue&&(K(0),T(0))},[M,ue]);const we=(ie,ce,ae)=>{if(ae<=ue)return{x:0,y:0};const X=(ae-1)/(2*ae)*100,J=(ae-1)/(2*ae)*100;return{x:Math.max(-X,Math.min(X,ie)),y:Math.max(-J,Math.min(J,ce))}},ye=(ie,ce)=>{if(!d.current)return null;const ae=d.current.getBoundingClientRect();return!ae.width||!ae.height?null:{nx:Math.max(0,Math.min(1,(ie-ae.left)/ae.width)),ny:Math.max(0,Math.min(1,(ce-ae.top)/ae.height))}},ve=(ie,ce,ae)=>{const X=l.current;if(!X)return;const J=X.getBoundingClientRect(),oe=++h.current;p(P=>[...P,{id:oe,x:ie-J.left,y:ce-J.top,type:ae}]),setTimeout(()=>p(P=>P.filter(G=>G.id!==oe)),600)},V=(ie,ce,ae)=>{const X=d.current,J=l.current;if(!X||!J)return;const oe=X.getBoundingClientRect(),P=J.getBoundingClientRect(),G=X.naturalWidth||oe.width,U=X.naturalHeight||oe.height,de=G/U,Ne=oe.width/oe.height;let _e,ge,Be,Oe;de>Ne?(_e=oe.width,ge=oe.width/de,Be=0,Oe=(oe.height-ge)/2):(ge=oe.height,_e=oe.height*de,Be=(oe.width-_e)/2,Oe=0);const Ke=oe.left-P.left+Be+_e*ie,et=oe.top-P.top+Oe+ge*ce,Je=++h.current;p(at=>[...at,{id:Je,x:Ke,y:et,type:ae}]),setTimeout(()=>p(at=>at.filter(dt=>dt.id!==Je)),600)},H=async ie=>{var ae;const ce=ye(ie.clientX,ie.clientY);if(ce){u(`Click: ${Math.round(ce.nx*100)}%, ${Math.round(ce.ny*100)}%`),ve(ie.clientX,ie.clientY,"left"),(ae=c.current)==null||ae.focus();try{const X=await e("input_click",{nx:ce.nx,ny:ce.ny});X!=null&&X.success||t(`❌ Click failed: ${X==null?void 0:X.error}`)}catch(X){t(`❌ Click error: ${X.message||X}`)}}},Z=async(ie,ce,ae,X=0)=>{try{await e("input_key",{type:ae?"char":"keyDown",key:ie,code:ce,text:ae?ie:void 0,unmodifiedText:ae?ie:void 0,modifiers:X})}catch(J){t(`❌ Key error: ${J.message||J}`)}},me=async ie=>{if(ie.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ie.key)&&ie.preventDefault();let ae=0;ie.altKey&&(ae|=1),ie.ctrlKey&&(ae|=2),ie.metaKey&&(ae|=4),ie.shiftKey&&(ae|=8),u(`Key: ${ie.key}`),await Z(ie.key,ie.code,ie.key.length===1,ae)},ne=async ie=>{if(ie.key==="Enter"){if(ie.nativeEvent.isComposing)return;if(x){const ce=x;m(""),u(`IME Sent: ${ce}`);try{const ae=await e("input_type",{text:ce});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 Z("Enter","Enter",!1)}};o.useEffect(()=>{const ie=c.current;if(!ie)return;const ce=ae=>{var X;if((X=d.current)!=null&&X.contains(ae.target)){ae.preventDefault();const J=Date.now();if(J-L.current<40)return;L.current=J;const oe=ye(ae.clientX,ae.clientY);if(!oe)return;u(`Scroll: ${Math.round(ae.deltaY)}`),e("input_wheel",{nx:oe.nx,ny:oe.ny,deltaX:Math.round(ae.deltaX),deltaY:Math.round(ae.deltaY)}).catch(()=>{})}};return ie.addEventListener("wheel",ce,{passive:!1}),()=>ie.removeEventListener("wheel",ce)},[e]);const{cursorPos:fe,handleToggleInputMode:se,handleZoomReset:xe}=yu({containerRef:c,viewportRef:l,imgRef:d,inputMode:I,setInputMode:k,minZoom:ue,zoomRef:Y,panXRef:O,panYRef:D,setPanX:K,setPanY:T,setZoom:C,lastWheelTimeRef:L,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:V,clampPan:we,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:me,onContextMenu:ie=>ie.preventDefault(),onFocus:()=>v(!0),onBlur:()=>v(!1),tabIndex:0,children:[s.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[Q?s.jsx("img",{ref:d,src:Q,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${M}) translate(${R}%, ${z}%)`,transformOrigin:"center center",cursor:I==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:H,onContextMenu:ie=>ie.preventDefault(),onDragStart:ie=>ie.preventDefault()}):s.jsx(bu,{waitingLabel:be,waitingHint:pe,transportType:i}),I==="mouse"&&Q&&s.jsx(hu,{cursorPos:fe,viewportRef:l,imgRef:d}),S.map(ie=>{const ae={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ie.type];return s.jsxs("div",{style:{position:"absolute",left:ie.x,top:ie.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}})]},ie.id)})]}),s.jsx(xu,{inputMode:I,onToggleInputMode:se,isImeOpen:N,setIsImeOpen:A,isMenuOpen:j,setIsMenuOpen:b,imeText:x,setImeText:m,handleImeSubmit:ne,isConnActive:W,zoom:M,isMobile:y,mobileFillZoom:w,onZoomOut:()=>C(ie=>Math.max(.5,ie-.25)),onZoomReset:xe,onZoomIn:()=>C(ie=>Math.min(5,ie+.25)),transportType:i,screenshotUsage:a,lastActionStatus:f}),s.jsx("style",{children:`
5
+ @keyframes slideUp {
6
+ from { opacity: 0; transform: translateY(6px); }
7
+ to { opacity: 1; transform: translateY(0); }
8
+ }
9
+ @keyframes slideUpSidebar {
10
+ from { opacity: 0; transform: translateY(6px); }
11
+ to { opacity: 1; transform: translateY(0); }
12
+ }
13
+ @keyframes click-ripple-ring {
14
+ 0% { transform: scale(0.3); opacity: 1; }
15
+ 100% { transform: scale(2.2); opacity: 0; }
16
+ }
17
+ @keyframes click-ripple-dot {
18
+ 0% { transform: scale(1); opacity: 0.9; }
19
+ 50% { transform: scale(1.8); opacity: 0.6; }
20
+ 100% { transform: scale(0.5); opacity: 0; }
21
+ }
22
+ @keyframes remote-float {
23
+ 0% { transform: translateY(0px); }
24
+ 50% { transform: translateY(-7px); }
25
+ 100% { transform: translateY(0px); }
26
+ }
27
+ `})]})}function 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 Hi=e=>Jr(e);function vu(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 wu(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...vu(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 ju(e,t,r){return Qr(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Fi({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 Ui(){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 ku=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Su(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function bt(e,t){if(Su(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":ku.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 zi(e){return bt(e)==="generating"}function st(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Nu(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 Cu(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 Iu(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Mu(e){return Cu(e.trim().replace(/\.local$/i,""))}function Au(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function Vi(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&&!Iu(c));if(r&&r!=="Unknown")return Mu(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function At(e,t={}){return Au(e)||Vi(e,t)}function Gi(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 qi(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 Gi(e).join(" · ")}function Qs(e){return e.transport==="pty"}function ys(e){return e.transport==="acp"}function Tu(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:st(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=st(r||"").trim().toLowerCase();return n===a||n===i||n===c}function Lu(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Ru(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 Pu(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function _u(e){var r,n;const t=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return t&&Pu(t.receivedAt)||0}function Du(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Jn(e){return Math.max(Du(e),_u(e.activeChat))}function Eu(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 Eu(Jn(e),Jn(t),At(e,{fallbackId:e.id}),At(t,{fallbackId:t.id}),e.id,t.id)}const Yi="adhdev_notification_prefs",ko={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function $u(){try{const e=localStorage.getItem(Yi);if(e){const t=JSON.parse(e);return{...ko,...t}}}catch{}return{...ko}}function Bu(e){try{localStorage.setItem(Yi,JSON.stringify(e))}catch{}}let Ht=$u(),Ar=[];function Ku(){Ar.forEach(e=>e())}function Ou(e){Ht={...Ht,...e},Bu(Ht),Ku()}function Wu(){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=>{Ou(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 Hu={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Xi(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Ji(){return"Notification"in window&&Notification.permission==="granted"}let Xt=null;async function Fu(){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(Ji())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 Uu(e,t={}){const r={...Hu,...t},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{Fu().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||!Ji())&&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")&&zi(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 zu=/^(run|approve|accept|yes|allow|always)/,Vu=/^(run|approve|accept|yes|allow|always|proceed|save)/,Gu=/^(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 qu(e){const t=ja(e).toLowerCase();return zu.test(t)?"primary":Gu.test(t)?"danger":"default"}function Yu(e){return Vu.test(ja(e).toLowerCase())?"approve":"reject"}function Xu(e){return e.map((t,r)=>({label:ja(t),variant:qu(t),action:Yu(t),button:t,buttonIndex:r}))}function Ju(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Qu(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 d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,f=(d==null?void 0:d.type)||"";let u=st(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=Xu(t.modalButtons).map(A=>({label:A.label,variant:A.variant,onClick:()=>{h(p,"resolve_action",{action:A.action,button:A.button,buttonIndex:A.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),b=Ju(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=Qu(j,h,this.viewRequestRespondFn,(A,y)=>console.error(`[EventManager] ${A} 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 Zu,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 em(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 tm(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 sm(e,t){return e&&vs(e.currentValue)?e.currentValue:t}function rm(e,t){return vs(t)?vs(e)?typeof e=="string"&&e.trim()==="":!0:!1}function nm(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 am={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 om(e,t,r){var n;return((n=am[t])==null?void 0:n.has(r.id))===!0}function ka(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!om(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function hn(e,t){return{value:t}}function im(e,t,r){var a;return r?((a=Tr(e,t).find(i=>i.value===r))==null?void 0:a.label)||r:""}const cm={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function lm({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=wt(),d=`${e}:${t||n}`,f=cm[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 L of i||[])L.defaultValue!==void 0&&(p[L.id]=L.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,A]=o.useState(null),[y,I]=o.useState(null),k=o.useCallback(async(L,Y={})=>{const O={...Y,...t&&{targetSessionId:t}};return await l(e,L,O)},[e,t,l]),w=o.useCallback(async(L,Y={})=>{const O=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await k("invoke_provider_script",{...O,scriptName:L,...Y})},[k,n,r,t]),g=o.useCallback((L,Y,O)=>{const D=sm(O,Y);x(W=>({...W,[L.id]:D})),tm(O==null?void 0:O.effects)},[]),E=o.useCallback((L,Y)=>{x(O=>{const D={...O};return Y===void 0?delete D[L.id]:D[L.id]=Y,D}),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 C=async L=>{if(N===L.id){A(null);return}if(Tr(L,j).length>0){A(L.id);return}if(L.dynamic&&L.listScript){I(L.id);try{const O=await w(L.listScript,{}),D=em(O);if(!D){const be=Ps(O);be&&lt.showToast(be,"warning");return}const W=D.options;b(be=>{const pe={...be,[L.id]:W};return So.set(d,pe),pe});const Q=nm(L.id,{localOverrideUntil:S.current,localValues:m.current,controlValues:v.current,defaultValues:p});if(rm(Q,D.currentValue)){const be=D.currentValue;x(pe=>({...pe,[L.id]:be}))}A(L.id)}catch(O){const D=O instanceof Error?O.message:`Could not load ${L.label}`;lt.showToast(D,"warning")}finally{I(null)}}},R=async(L,Y)=>{A(null);const O=(c==null?void 0:c[L.id])??p[L.id];x(D=>({...D,[L.id]:Y})),S.current=Date.now()+5e3;try{if(!L.setScript)return;const D=await w(L.setScript,hn(L,Y)),W=pr(D);if(W&&!W.ok||hr(D))throw new Error((W==null?void 0:W.error)||Ps(D)||`Could not update ${L.label}`);g(L,Y,W)}catch(D){E(L,O);const W=D instanceof Error?D.message:`Could not update ${L.label}`;lt.showToast(W,"warning")}},K=async L=>{const Y=Tr(L,j).map(pe=>pe.value);if(Y.length===0)return;const O=String(h[L.id]||""),W=(Y.indexOf(O)+1)%Y.length,Q=Y[W];if(typeof Q!="string")return;const be=(c==null?void 0:c[L.id])??p[L.id];x(pe=>({...pe,[L.id]:Q})),S.current=Date.now()+5e3;try{if(!L.setScript)return;const pe=await w(L.setScript,hn(L,Q)),ue=pr(pe);if(ue&&!ue.ok||hr(pe))throw new Error((ue==null?void 0:ue.error)||Ps(pe)||`Could not update ${L.label}`);g(L,Q,ue)}catch(pe){E(L,be);const ue=pe instanceof Error?pe.message:`Could not update ${L.label}`;lt.showToast(ue,"warning")}},z=async L=>{const O=!h[L.id],D=(c==null?void 0:c[L.id])??p[L.id];x(W=>({...W,[L.id]:O})),S.current=Date.now()+5e3;try{if(!L.setScript)return;const W=await w(L.setScript,hn(L,O)),Q=pr(W);if(Q&&!Q.ok||hr(W))throw new Error((Q==null?void 0:Q.error)||Ps(W)||`Could not update ${L.label}`);g(L,O,Q)}catch(W){E(L,D);const Q=W instanceof Error?W.message:`Could not update ${L.label}`;lt.showToast(Q,"warning")}},T=async L=>{if(!L.invokeScript)return;if(L.confirmMessage){const O=[L.confirmTitle,L.confirmMessage,L.confirmLabel].filter(W=>typeof W=="string"&&W.trim().length>0);if(!window.confirm(O.join(`
28
+
29
+ `)))return}const Y=(c==null?void 0:c[L.id])??p[L.id];try{const O=await w(L.invokeScript),D=pr(O);if(D&&!D.ok||hr(O))throw new Error((D==null?void 0:D.error)||Ps(O)||`Could not run ${L.label}`);D&&g(L,Y??!0,D)}catch(O){E(L,Y);const D=O instanceof Error?O.message:`Could not run ${L.label}`;lt.showToast(D,"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(L=>{const Y=String(h[L.id]||""),O=im(L,j,Y),D=N===L.id,W=y===L.id,Q=Tr(L,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(L.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:D?`${f}55`:"var(--border-default)",background:D?`${f}10`:"var(--surface-tertiary)",color:Y?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void C(L),title:L.label,children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:W?"Loading…":O||L.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),D&&Q.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>A(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:L.label}),Q.map(pe=>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:pe.value===Y?`${f}14`:"transparent",color:pe.value===Y?"var(--text-primary)":"var(--text-secondary)",borderLeft:pe.value===Y?`2px solid ${f}`:"2px solid transparent"},title:pe.description||pe.label,onMouseEnter:ue=>{ue.currentTarget.style.background=`${f}10`},onMouseLeave:ue=>{ue.currentTarget.style.background=pe.value===Y?`${f}14`:"transparent"},onClick:()=>void R(L,pe.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:pe.label}),pe.value===Y&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:f},children:"✓"})]},pe.value))]})]})]},L.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:Y?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void K(L),title:`Click to cycle: ${Q.map(pe=>pe.label).join(" → ")}`,children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:O||L.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},L.id);case"toggle":return s.jsxs("button",{type:"button",className:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:Y?`${f}44`:"var(--border-default)",background:Y?`${f}14`:"var(--surface-tertiary)",color:Y?f:"var(--text-muted)"},onClick:()=>void z(L),"aria-pressed":!!Y,children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),L.label]},L.id);case"action":return s.jsxs("button",{type:"button",className:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void T(L),children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:L.resultDisplay==="inline"&&Y?`${L.label}: ${Y}`:L.label})]},L.id);case"display":return s.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:Y?"var(--text-primary)":"var(--text-muted)"},children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:Y?`${L.label}: ${Y}`:L.label})]},L.id);default:return null}})]})})}function dm({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:d}){const{isVisible:f}=Ui(),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(lm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:u,controlValues:d})})}function um({hasDraft:e,isBusy:t=!1}){return!e||t}const Qi=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}=Ui();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:um({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})]})}),Ze=e=>e.transport==="pty",Ls=(e,t)=>Ze(e)?e.mode||"terminal":"chat",Zi=(e,t)=>Ze(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 ec(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 tc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function mm(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 fm(e){return No(e==null?void 0:e.receivedAt)||No(e==null?void 0:e.timestamp)||0}function sc(e){const t=mm(e),r=Ss(t==null?void 0:t.content),n=fm(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 pm(e){return sc(e)||e.displaySecondary||""}function rc(e){return[e.displaySecondary,ec(e)].filter(Boolean)}function Cs(e){return e.agentName||st(Kt(e))}function hm(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 st(Hr(e)||Kt(e))}function nc(e){return Vt(e)?e.sessionId:e.nativeSessionId}function Co(e){return Vt(e)?"native":e.tabKey}function xm(e){return e.sessionId}function bm(e,t){if(t)return Vt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function gm(e,t){const r=Kt(e),n=Vt(e),a=Ze(e)||Xe(e),i=n?a?Cs(e)||(t==null?void 0:t.cliName)||st(Hr(e)||r):t!=null&&t.type?st(t.type):st(Hr(e)||r):Cs(e);return{isNativeConversation:n,isCli:Ze(e),isAcp:Xe(e),isCliTerminal:Zi(e),providerType:r,displayLabel:i,targetEntry:bm(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 ac(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 ym(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 vm(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:ac({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=vm(e);return ym(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 oc(e){return es(e)||e.lastUpdated||0}function ic(e,t,r=oc){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 wm(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!ta(e)&&!e.title.trim()}function jm(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:ic(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=jm(a);return n?i&&wm(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 cc(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 lc({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=As(),c=fs(e),l=ec(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=hm(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 km(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function _s(e,t){km()&&console.debug(`[subscription-manager] ${e}`,t)}class Sm{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 Sm;function Nm(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 Cm(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}=Cm(d),x=Nm(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(A=>Ws(A,x.get(A.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(A=>({id:A.id,name:A.providerName||A.providerType,type:A.providerType,status:A.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 Im=15e3,Mm=15e3,Am=6e4,Tm=1200,Mo=12,Lm=8e3,Rm=4e3,bn=new Map,gn=new Map,xr=new Set,Us=new Map;function Pm(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 _m(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)??Am,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(A=>A.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 _m(a,Tm))return}const u=await e(a,"get_status_metadata"),x=Pm(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:Ze(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 Dm(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 Em=60,$m=1e3;function dc(e={}){return e.isCliLike?$m:Em}function Bm(e={}){return dc(e)}const or=60,Km=1e3,Ta=12e4,Om=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:uc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function ra(e){return Mi(e)}function uc(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 Wm(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 Hm{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=uc(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:Km}))}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=Wm(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 mc(e){const t=La(e.daemonId,e.sessionId),r=To.get(t);if(r)return r.updateOptions(e),r;const n=new Hm(e);return To.set(t,n),n}function Fm(e,t){return{...e,loadHistoryPage:t}}function Um(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function zm(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Om.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 Vm(e=Ta){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Gm(e,t={}){const r=new Set,n=[];for(const a of e){if(!zm(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(Um),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function qm(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:mc({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(()=>Fm(x,v),[v,x])}function Ym(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=Vm(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(()=>Gm(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:mc({...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 A of N.keys())v.has(A)||N.delete(A);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 Xm(e){const t=Rs(e),r=e.sessionId||"";return t&&r?`${t}::${r}`:""}function Jm(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 Qm(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 Zm(e,t){const r=(t==null?void 0:t.liveMessages)||[];return r.length>0?r:e.messages}function ef(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=Xm(a);if(!i)return a;const c=((l=t.get(i))==null?void 0:l.liveMessages)||[];return Jm(a,c)?(r=!0,Qm(a,c)):a});return r?n:e}function tf(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function sf(e){return tf(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const rf=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 we,ye,ve,V,H;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(()=>gm(e,t),[e,t]),j=o.useMemo(()=>{var Z;return ka((Z=h.targetEntry)==null?void 0:Z.providerControls,{hostIdeType:e.hostIdeType,providerType:h.providerType})},[e.hostIdeType,h.providerType,(we=h.targetEntry)==null?void 0:we.providerControls]),b=dc({isCliLike:h.isCli||h.isAcp}),N=Bm({isCliLike:h.isCli||h.isAcp}),A=qm(e,{enabled:m&&!!e.sessionId,tailLimit:N}),[y,I]=o.useState(b),k=e.tabKey,w=A.historyMessages,g=A.hasMoreHistory,E=A.historyError,M=Zm(e,A);o.useEffect(()=>{I(b)},[b,k]);const C=Math.max(0,M.length-y),R=Sa(e),K=Rs(e),z=sf(e),T=Aa(e),L=a||T,Y=!!T,[O,D]=o.useState(!1);o.useEffect(()=>{const Z=h.targetEntry;K&&(!Z||Z.providerControls===void 0||Z.controlValues===void 0)&&S(K,{minFreshMs:3e4}).catch(()=>{})},[K,h.isAcp,(ye=h.targetEntry)==null?void 0:ye.providerControls,(ve=h.targetEntry)==null?void 0:ve.controlValues,S]);const W=o.useCallback(async()=>{if(!O){if(M.length>y){I(Z=>Math.min(M.length,Z+rf));return}D(!0);try{await A.loadHistoryPage()}finally{D(!1)}}},[A,O,M.length,y]),{allMessages:Q,receivedAtMap:be}=o.useMemo(()=>{const Z=ef({historyMessages:w,liveMessages:M,visibleLiveCount:y}),me={};return Z.forEach((ne,fe)=>{const se=`${e.tabKey}:${Kr(ne,fe)}`;let xe=Ma(ne)||v.current.get(se)||0;xe||(xe=Date.now(),v.current.set(se,xe)),me[Kr(ne,fe)]=xe}),{allMessages:Z,receivedAtMap:me}},[e.tabKey,C,w,M,y]),pe=o.useMemo(()=>l.filter(Z=>Z.routeId===e.tabKey).sort((Z,me)=>Z.timestamp-me.timestamp),[l,e.tabKey]),ue=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")&&D(!1),e.status==="not_monitored"&&z)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(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 ",R," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&z)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Pi,{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 ",R," 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"&&!O)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,z,i,c,O,M.length,R,p.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[f&&s.jsx(lc,{conversation:e,className:"chat-pane-meta-row"}),s.jsx(uu,{messages:Q,actionLogs:pe,agentName:Cs(e)||R||"Agent",userName:d,isCliMode:h.isCli||h.isAcp,isWorking:p.isGenerating,contextKey:e.tabKey,receivedAtMap:be,onLoadMore:W,isLoadingMore:O,hasMoreHistory:g,hiddenLiveCount:C,loadError:E??void 0,emptyState:ue,scrollToBottomRequestNonce:u,isVisible:m}),s.jsx(dm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:h.providerType,displayLabel:h.displayLabel,controls:(V=h.targetEntry)==null?void 0:V.providerControls,controlValues:(H=h.targetEntry)==null?void 0:H.controlValues,isActive:x,isCliTerminal:h.isCliTerminal}),!h.isCliTerminal&&s.jsx(Qi,{contextKey:e.tabKey,panelLabel:R,isSending:n,isBusy:Y,statusMessage:L,onSend:r,isActive:x,showControlsToggle:j.length>0})]})}let fc=cs;function pc(){return fc()}class nf{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 hc=new nf;class af{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 it=new af;function of(e){e.dashboardWS&&(hc=e.dashboardWS),e.connectionManager&&(it=e.connectionManager),e.useDaemonsHook&&(fc=e.useDaemonsHook)}const cf=.5,lf=1.25;function nt(e){return Sa(e)}function us(e){return rc(e).join(" · ")}function xc(e){const t=sc(e);return t||(e.title?e.title:us(e)||"No messages yet")}function bc(e,t){const{isReconnecting:r,isConnecting:n}=Ts(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function df(e,t){const r=["Chat",...rc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function ts(e){return bc(e)||us(e)}function uf(e){return`${nt(e)} · ${xc(e)}`}function mf(e){const t=Hr(e),r=t?st(t):Cs(e);return`${nt(e)} — ${r||"Agent"}`}function ff(e){return Cs(e)||"CLI"}function gc(e){return tc(e)}function yc(e){return e?`Remote · ${nt(e)||e.workspaceName||"Session"}`:"Remote"}function pf({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}),A=o.useRef(null),y=o.useRef(null),I=o.useRef(!1),k=o.useRef(!1),w=o.useRef(0),g=o.useRef(!1),E=o.useRef(""),M=o.useRef(null),C=o.useRef(!1),R=o.useRef(null),K=32*1024,z=()=>{var X,J,oe,P;return((J=(X=A.current)==null?void 0:X.ownerDocument)==null?void 0:J.defaultView)||((P=(oe=y.current)==null?void 0:oe.ownerDocument)==null?void 0:P.defaultView)||window},T=X=>{const J=z();return{ownerWindow:J,frameId:J.requestAnimationFrame(X)}},L=()=>{const X=R.current;if(X){try{X.ownerWindow.cancelAnimationFrame(X.frameId)}catch{}R.current=null}},Y=()=>{c&&R.current===null&&(R.current=T(()=>{se()}))},O=e.tabKey,D=e.sessionId||"",W=e.daemonId||((ae=e.routeId)==null?void 0:ae.split(":")[0])||e.routeId||"",Q=Aa(e),be=f?i||Q:m,pe=cf,ue=lf,we=.05,ye=()=>{const X=b.width,J=b.height;if(!Number.isFinite(h.width)||h.width<=0||!Number.isFinite(h.height)||h.height<=0||!Number.isFinite(X)||X<=0||!Number.isFinite(J)||J<=0)return 1;const oe=h.width/X,P=h.height/J;return Number(Math.min(ue,Math.max(pe,Math.min(oe,P))).toFixed(2))},ve=ye(),V=I.current&&S>ve,H=Number.isFinite(b.width)&&b.width>0?Math.max(h.width,Math.round(b.width*S)):h.width,Z=Number.isFinite(b.height)&&b.height>0?Math.max(h.height,Math.round(b.height*S)):h.height,me=()=>{T(()=>{const X=y.current;X&&(X.scrollLeft=0,X.scrollTop=X.scrollHeight-X.clientHeight)})},ne=()=>{var X,J;w.current=0,g.current=!1,E.current="",M.current=null,C.current=!1,I.current||(k.current=!1,p(1)),R.current!==null&&L(),u(!1),v("Runtime terminal unavailable"),(J=(X=r.current)==null?void 0:X.reset)==null||J.call(X)},fe=()=>{var X,J;w.current=0,g.current=!1,E.current="",M.current=null,C.current=!1,R.current!==null&&L(),u(!0),v(""),(J=(X=r.current)==null?void 0:X.reset)==null||J.call(X)},se=()=>{var oe;if(R.current=null,!c)return;const X=E.current;if(!X)return;const J=X.slice(0,K);E.current=X.slice(J.length),(oe=r.current)==null||oe.write(J),E.current.length>0&&Y()},xe=X=>{X&&(E.current+=X,Y())},ie=(X,J=0,oe,P)=>{var G,U,de,Ne;J>0&&w.current>=J||J===0&&g.current||(w.current=J,u(!0),v(""),typeof oe=="number"&&typeof P=="number"&&oe>0&&P>0&&((U=(G=r.current)==null?void 0:G.resize)==null||U.call(G,oe,P)),E.current="",(Ne=(de=r.current)==null?void 0:de.reset)==null||Ne.call(de),X&&xe(X))};o.useEffect(()=>{ne()},[D]),o.useEffect(()=>{var J;if(!D)return;const X=((J=it.onRuntimeEvent)==null?void 0:J.call(it,D,oe=>{if(!(!oe||oe.sessionId!==D)){if(oe.type==="runtime_snapshot"){if(!c){M.current={text:oe.text||"",seq:oe.seq||0,cols:oe.cols,rows:oe.rows};return}ie(oe.text||"",oe.seq||0,oe.cols,oe.rows);return}if(oe.type==="session_output"){g.current=!0,typeof oe.seq=="number"&&(w.current=Math.max(w.current,oe.seq)),x.current||u(!0),x.current||v(""),typeof oe.data=="string"&&xe(oe.data);return}if(oe.type==="session_cleared"){if(!c){C.current=!0,E.current="",M.current=null;return}fe();return}if(oe.type==="session_io_error"){const P=typeof oe.error=="string"&&oe.error?oe.error:typeof oe.reason=="string"&&oe.reason?oe.reason:"unknown error";u(!1),v(`Runtime input failed: ${P}`);return}}},W))||(()=>{});return()=>{X()}},[W,D,r,c]);const ce=async()=>{var X;if(!(!W||!D)){v("Loading runtime terminal...");try{const J=await((X=it.requestRuntimeSnapshot)==null?void 0:X.call(it,W,D));J&&J.success===!1&&(u(!1),v(`Runtime terminal unavailable: ${J.error}`))}catch(J){u(!1),v(`Runtime terminal unavailable: ${(J==null?void 0:J.message)||String(J)}`)}}};return o.useEffect(()=>{var J,oe;if(!D)return;W&&((J=it.getState)==null?void 0:J.call(it,W))==="connected"&&ce();const X=(oe=it.onStateChange)==null?void 0:oe.call(it,(P,G)=>{P!==W||G!=="connected"||ce()});return()=>{X==null||X()}},[W,D,r]),o.useEffect(()=>{t&&ne()},[t,O,r]),o.useEffect(()=>{var P,G;const X=A.current,J=(G=(P=X==null?void 0:X.ownerDocument)==null?void 0:P.defaultView)==null?void 0:G.ResizeObserver;if(!X||!J)return;const oe=new J(U=>{const de=U[0];if(!de)return;const{width:Ne,height:_e}=de.contentRect;j(ge=>{const Be=Math.round(Ne),Oe=Math.round(_e);return ge.width===Be&&ge.height===Oe?ge:{width:Be,height:Oe}})});return oe.observe(X),()=>oe.disconnect()},[]),o.useEffect(()=>{if(I.current)return;const X=ye();!Number.isFinite(X)||X<=0||p(J=>k.current?X<J-we?X:J:(k.current=!0,X))},[b.height,b.width,h.height,h.width]),o.useEffect(()=>{V&&me()},[V,Z,H]),o.useEffect(()=>{var J;if(!c)return;C.current&&(C.current=!1,fe());const X=M.current;X&&(M.current=null,ie(X.text,X.seq,X.cols,X.rows)),W&&D&&((J=it.getState)==null?void 0:J.call(it,W))==="connected"&&ce(),E.current&&R.current===null&&Y(),T(()=>{var oe;(oe=r.current)==null||oe.bumpResize()})},[W,c,D]),o.useEffect(()=>()=>{R.current!==null&&L()},[]),o.useEffect(()=>{const X=P=>{var U;const G=P.detail;G!=null&&G.sessionId&&G.sessionId!==D||f&&((U=r.current)==null||U.bumpResize())},J=z(),oe=J===window?[window]:[window,J];for(const P of oe)P.addEventListener("adhdev:fit-cli-terminal",X);return()=>{for(const P of oe)P.removeEventListener("adhdev:fit-cli-terminal",X)}},[f,D,r]),s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:A,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:()=>{I.current=!0,p(X=>{const J=Math.max(ve,Number((X-.1).toFixed(2)));return J>ve&&me(),J})},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:()=>{I.current=!0,p(X=>{const J=Math.min(ue,Number((X+.1).toFixed(2)));return J>ve&&me(),J})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:y,className:V?"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:H>0?`${H}px`:"100%",height:Z>0?`${Z}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(Oi,{ref:r,readOnly:!f||!c,sizingMode:"measured",onViewportMetrics:N,onInput:X=>{!f||(d==null||d(W,D,X))}})})})}),!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(Qi,{contextKey:e.tabKey,panelLabel:nt(e),isSending:a,isBusy:!!Q,statusMessage:be,onSend:async X=>Q?!1:n(X),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const hf=2500;function xf(e){return e==="disconnected"||e==="reconnecting"}function bf({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=hf}){const i=xf(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 gf({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",vc="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 yf({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 vf({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:A,notificationUnreadCount:y,onOpenNotification:I,onMarkNotificationRead:k,onMarkNotificationUnread:w,onDeleteNotification:g}){const{ides:E,p2pStates:M={}}=cs(),C=!!e&&Ze(e)&&!Xe(e),R=!!e&&Xe(e),K=l||(e?Zi(e)?"terminal":"chat":null),[z,T]=o.useState(!1),L=o.useRef(null),Y=o.useRef(null),O=E.filter(V=>V.type==="adhdev-daemon"),D=yf({wsStatus:t,isConnected:r,daemonCount:O.length,p2pStates:M}),W=D.subtitle,Q=D.tone==="connected"?"#22c55e":D.tone==="limited"?"#eab308":"#ef4444",be=D.tone==="connected"?"0 0 4px #22c55e80":D.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",pe=o.useMemo(()=>A.filter(V=>!V.readAt),[A]),ue=o.useMemo(()=>A.filter(V=>!!V.readAt),[A]),we=o.useMemo(()=>pe.slice(0,9),[pe]),ye=y;o.useEffect(()=>{if(!S)return;const V=H=>{var Z;(Z=L.current)!=null&&Z.contains(H.target)||p(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[S,p]),o.useEffect(()=>{if(!h)return;const V=H=>{var Z;(Z=Y.current)!=null&&Z.contains(H.target)||j(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[h,j]),o.useEffect(()=>{if(!h&&!S)return;const V=H=>{if(!H.altKey)return;const Z=H.code.match(/^Digit([1-9])$/);if(!Z)return;const me=Number(Z[1])-1,ne=h?u[me]:void 0,fe=S?we[me]:void 0;if(!(!ne&&!fe)){if(H.preventDefault(),H.stopPropagation(),ne){x==null||x(ne),j(!1);return}fe&&(I(fe),p(!1))}};return window.addEventListener("keydown",V,!0),()=>window.removeEventListener("keydown",V,!0)},[u,h,S,we,j,p,I,x]);const ve=V=>{if(!V)return;const H=n.find(Z=>Z.tabKey===V);H&&(f==null||f(H))};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?nt(e):"Dashboard"}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:Q,boxShadow:be}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[s.jsx("span",{title:D.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:Q,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(Ei,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(C||R||!Xe(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:us(e)||nt(e),children:nt(e)}),(C||R)&&c&&s.jsxs(s.Fragment,{children:[C&&d&&K&&s.jsx(Ra,{mode:K,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:R?"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})}),!C&&!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:L,children:[s.jsxs("div",{className:`dashboard-header-hidden${z?" is-drop-target":""}`,ref:Y,onDragEnter:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),T(!0))},onDragOver:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),V.dataTransfer.dropEffect="move",T(!0))},onDragLeave:V=>{V.currentTarget.contains(V.relatedTarget)||T(!1)},onDrop:V=>{const H=V.dataTransfer.getData("text/tab-key");V.preventDefault(),T(!1),ve(H)},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(_i,{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:nt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(V=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{x==null||x(V),j(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:nt(V)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(V)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(V)+1]}):null,us(V)]})]},V.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}),ye>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ye})]}),S&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[pe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),pe.map(V=>s.jsx(Do,{notification:V,shortcutIndex:we.indexOf(V)>=0?we.indexOf(V)+1:void 0,onOpen:()=>I(V),onMarkRead:()=>k(V.id),onMarkUnread:()=>w(V.id),onDelete:()=>g(V.id)},V.id))]}),ue.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),ue.map(V=>s.jsx(Do,{notification:V,onOpen:()=>I(V),onMarkRead:()=>k(V.id),onMarkUnread:()=>w(V.id),onDelete:()=>g(V.id)},V.id))]}),A.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 wf(e,t){return String(e||"")!==String(t||"")}function jf(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&&!Gi(c.summaryMetadata).map(d=>d.toLowerCase()).join(`
31
+ `).includes(a)))}function kf(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const i=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function wc(e,t={}){return kf(jf(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 Sf(){return"Start fresh"}function jc(e,t=!1){return e==="cli"?Ur(t):e==="ide"?"Start IDE":"Start ACP session"}function kc(e,t=!1){return e==="cli"?Pa(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Nf(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Cf(){return"Open saved history"}function If(){return"Saved History"}function _a(){return"Use saved history when you want continuity in the same provider conversation."}function Mf(){return"No saved history found yet."}function Af(){return"Refresh saved history"}function Tf(){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 Lf(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=Ze(e)&&!Xe(e),[b,N]=o.useState(()=>ht()),A=l||b,y=g=>{if(d){d(g);return}N(g)},I=o.useMemo(()=>wc(a,{textQuery:A.textQuery,workspaceQuery:A.workspaceQuery,modelQuery:A.modelQuery,resumableOnly:A.resumableOnly,sortMode:A.sortMode}),[A.modelQuery,A.resumableOnly,A.sortMode,A.textQuery,A.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?If():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:mf(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:A.textQuery,onChange:g=>y({...A,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:A.workspaceQuery,onChange:g=>y({...A,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:A.modelQuery,onChange:g=>y({...A,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:A.sortMode,onChange:g=>y({...A,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:A.resumableOnly,onChange:g=>y({...A,resumableOnly:g.target.checked})}),"Resume-ready only"]})]}),I.map(g=>{const E=e.providerSessionId===g.providerSessionId,M=E||!g.canResume||!!c;return s.jsxs("button",{type:"button",onClick:()=>{M||!v||v(g)},disabled:M,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${E?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${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 ${E?"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:Lf(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:E?"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&&I.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(Fd,{size:32})}),s.jsx("div",{className:"text-[13px]",children:j?a.length>0?"No saved history matches these filters.":Mf():"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:Tf()})})]}),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?Af():"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 Sc({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 Rf=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Pf(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function _f(e){return e.sessionId||e.instanceId||e.agentType}function yn(e,t){return e||t}function Nc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=At(r,{fallbackId:r.id}));return t}function Cc(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 Df(e,Cc(e,t))}function Df(e,t={}){var u,x,m,v,S,p;const r=[],n=t.machineName,a=t.connectionState,i=Pf(e),c=Tu(e.type,{agentName:e.cliName}),l=Ze(e)||Xe(e)?c:st(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||st(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=Rf(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,A=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 I=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 C=w.find(R=>R.id===k||R.id&&String(R.id)===String(k));C!=null&&C.title&&String(C.title).trim()&&(I=String(C.title).trim())}const g=(Ze(e)||Xe(e),e.type),E=(Ze(e)||Xe(e))&&jo(I,j,g)?"":I,M=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:Ze(e)?e.mode||"terminal":"chat",agentName:j,agentType:g,status:A,title:E,messages:M,resume:e.resume,hostIdeType:!Ze(e)&&!Xe(e)?e.type:void 0,workspaceName:i,displayPrimary:E||i||(Ze(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&&(Ze(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=Lu(h),N=_f(h),A=`${e.id}:${N}`,y=h.title&&String(h.title).trim()||"",I=jo(y,h.agentName,h.agentType)?"":y,k=h.messages||[];(h.transport==="cdp-webview"||h.sessionId||h.providerSessionId||k.length>0||j||I||!["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:I,messages:k,hostIdeType:e.type,workspaceName:i,displayPrimary:I||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,A),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 Ef(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 Ic(e,t){const r=Ef(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Mc=[{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"trae",name:"Trae",icon:"🔮"},{id:"vscode",name:"VS Code",icon:"💙"},{id:"vscodium",name:"VSCodium",icon:"💚"},{id:"windsurf",name:"Windsurf",icon:"🏄"}],Ac=[{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],Tc=[{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:"🟠"}],$f=Mc,Bf=Ac,Kf=Tc;function ms(...e){return rd(nd(e))}function Of({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 Lc({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(Of,{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 Wf(){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"?Wf():e}function Rc(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 Hf(){const e=xs(),t=bs(e);Rc(t),Lr(e,t)}function Ka(){const[e,t]=o.useState(xs),[r,n]=o.useState(()=>bs(xs()));o.useEffect(()=>{Rc(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 Ff({collapsed:e}){const{preference:t,cycleTheme:r}=Ka(),n=t==="dark"?s.jsx(zd,{size:16}):t==="light"?s.jsx(Ud,{size:16}):s.jsx(Vd,{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 Uf({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 A=!N;try{localStorage.setItem(d,A?"1":"0")}catch{}return A})},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(Ff,{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 Pc({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 zf={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"},Vf={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]",zf[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Vf[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 Gf={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"},qf={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Yf({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",Gf[e],r),children:[s.jsx("span",{className:ms("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",qf[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 Xf({onPrefChange:e}){const[t,r]=Wu(),[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:()=>{Xi().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(Gd,{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(qd,{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 Jf(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 _c(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||Jf(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 Qf(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 Zf({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Pc,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:t||"Install ADHDev on a machine and sign in to connect it here."}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>s.jsx(tp,{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 ep(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...$f,...Bf,...Kf].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 tp({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var K,z;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=((K=e.machine)==null?void 0:K.platform)||((z=e.system)==null?void 0:z.platform)||"",j=At(e,{fallbackId:e.id}),b=h==="win32"?"🪟":h==="darwin"?"🍎":"🐧",N=t.filter(T=>T.daemonId===e.id&&T.transport==="cdp-page"),A=t.filter(T=>T.daemonId===e.id&&T.transport==="pty"),y=t.filter(T=>T.daemonId===e.id&&T.transport==="acp"),I=e.p2p,k=async()=>{if(r){c("upgrading"),d("Starting upgrade...");try{const T=Qf(await r(e.id,"daemon_upgrade",{}));T.alreadyLatest?(c("done"),d(`Already on v${T.version||"latest"}.`)):T.upgraded||T.success?(c("done"),d(`Upgrade to v${T.version||"latest"} started. Daemon is restarting...`)):(c("error"),d(T.error||"Upgrade failed"))}catch(T){c("error"),d(wn(T,"Connection lost during upgrade"))}}},w=async()=>{if(u(null),!!n){m("loading");try{await n(e.id),m("done"),S("Machine disconnected.")}catch(T){m("error"),S(wn(T,"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(T){m("error"),S(wn(T,"Failed to revoke token"))}}},E="0.9.26",M=_c(e,E),C=zs(e,E),R=N.length+A.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${E}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${C?"↑ Update now":`↑ Update${` to v${E}`}`}`}),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(Yf,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[I&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${I.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${I.state==="connecting"||I.state==="new"?"animate-pulse":""}`,style:I.state==="connecting"||I.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",I.state==="connected"?"connected":I.state==="connecting"||I.state==="new"?"connecting...":I.state||"off"]}),I.peers!==void 0&&I.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",I.peers," peer",I.peers!==1?"s":"",")"]})]}),I&&R>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),R>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(T=>{const L=ep(T.type),Y=T.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:L.icon}),s.jsx("span",{children:L.name}),Y!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Y?"bg-green-400":"animate-pulse"}`,style:Y?void 0:{background:"var(--status-warning)"},title:Y?"CDP connected":"CDP connecting..."})]},T.id)}),A.map(T=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:T.cliName||"CLI"})]},T.id)),y.map(T=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:T.cliName||"ACP"})]},T.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||v)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||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
+
33
+ This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
34
+
35
+ Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:w,onCancel:()=>u(null)}),f==="revoke"&&s.jsx(Bo,{title:"⚠️ Remove Machine",message:`Remove "${j}" from your dashboard?
36
+
37
+ This will:
38
+ • Immediately disconnect the machine
39
+ • Delete the machine registration
40
+ • Require restarting ADHDev on that machine
41
+
42
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:g,onCancel:()=>u(null)})]})}const sp=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function rp(){const{preference:e,setPreference:t}=Ka();return s.jsx("div",{className:"flex gap-2",children:sp.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 np(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 ap(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}=ap(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 Dc(e){const t=np(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},op=[{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"}}}],Ec="adhdev-chat-theme",$c="adhdev-chat-theme-custom";function Rr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Ec)||"ember"}catch{return"ember"}}function Pt(e){try{const t=localStorage.getItem($c);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($c,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 ip={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=ip[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",Dc(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",Dc(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 cp(e){try{localStorage.setItem(Ec,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 lp(){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 dp({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 up(){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),cp(d)},l=[...op,{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(dp,{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 mp(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 fp(e){try{localStorage.setItem(Wa,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ca,{detail:e}))}function pp(){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),fp(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 hp(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 xp(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 Bc(){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)??Mm,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=hp(f);if(!u)return;const x=r().find(v=>v.id===n),m=xp(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 bp(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 gp(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=bp(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 yp(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)},Rm):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 vp(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Kc(e){const{sendData:t}=wt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=vp(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 Oc="adhdev_hiddenTabs";function wp(){try{const e=localStorage.getItem(Oc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ps(e){try{localStorage.setItem(Oc,JSON.stringify([...e]))}catch{}}function Sn(e){return Ca(e)}function Fa(e,t){return ws(t).some(r=>e.has(r))}function jp(){const[e,t]=o.useState(wp),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 Wc(e){return e instanceof Error?e.message:String(e||"")}function Hc(e){const t=Wc(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 Fc(e){const t=Wc(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Uc({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Ze(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=Fc(l);c&&!d&&a(f=>{const u={...f};return i===zc(r,c)?delete u[c]:u[c]=i,u}),Hc(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 kp(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 zc(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 Sp(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))zc(t,a)===i&&(delete n[a],r=!0);return r?n:e}function Np({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Xi()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:gc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Uu(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 Cp(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 Ip(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?Ip(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 Mp(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 Ap(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 Tp(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 Lp(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Rp(e){const t=Lp(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 Pp({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>Cp(e),[e]),i=o.useMemo(()=>Nc(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 A=new Map,y=[];for(const g of a){const{connectionState:E="new",machineName:M}=Cc(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),C=Mp(g),R=f.current.get(g.id);if(R&&R.ide===g&&R.sourceSignature===C&&R.connectionState===E&&R.machineName===M){A.set(g.id,R),y.push(...R.conversations);continue}const K=Ba(g,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),z={ide:g,sourceSignature:C,connectionState:E,machineName:M,conversations:K};A.set(g.id,z),y.push(...K)}f.current=A;const I=new Map,k=g=>{const E=Rp(g),M=u.current.get(g.tabKey);if(M&&M.signature===E)return I.set(g.tabKey,M),M.timestamp;const C={signature:E,timestamp:oc(g)||(M==null?void 0:M.timestamp)||0};return I.set(g.tabKey,C),C.timestamp},w=[...y].sort((g,E)=>ic(g,E,k));return u.current=I,w},[a,t,i]),m=o.useMemo(()=>{const A=Ap(x,r);return Nn(c.current,A)?c.current:(c.current=A,A)},[x,r]),v=o.useMemo(()=>{const A=new Map,y=Array.from(new Set(m.map(I=>I.routeId)));for(const I of y){const k=_t(m,I);k&&A.set(I,k)}return A},[m]),S=o.useMemo(()=>{const A=new Map;for(const y of m){const I=v.get(y.routeId),k=y.streamSource==="native"&&I?I:y;for(const w of ws({providerSessionId:y.providerSessionId,sessionId:y.sessionId}))A.set(w,k)}return A},[m,v]),p=o.useMemo(()=>Tp(m,v),[m,v]),h=o.useCallback(A=>{if(A)return S.get(A)},[S]),j=o.useCallback(A=>{if(A)return p.get(A)},[p]),b=o.useMemo(()=>{const A=m.filter(y=>!Fa(n,y));return Nn(l.current,A)?l.current:(l.current=A,A)},[m,n]),N=o.useMemo(()=>{const A=b.map(y=>y.tabKey);return Nn(d.current,A)?d.current:(d.current=A,A)},[b]);return{chatIdes:a,conversations:m,visibleConversations:b,visibleTabKeys:N,resolveConversationBySessionId:h,resolveConversationByTarget:j}}function _p({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 Dp({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=hc.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 Ep="adhdev_dashboardLayout_v1",$p="adhdev_dashboardDockview_v1",Bp="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 Kp(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Vc(e){return`${Ep}:${e}`}function Op(e){const t=Vc(e);return Ua(t,null)}function Wp(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=Vc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Gc(e){return`${$p}:${e}`}function Hp(e){const t=Gc(e);return Ua(t,null)}function Fp(e,t){try{const r=Gc(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function qc(e){return`${Bp}:${e}`}function Up(e){const t=qc(e);return Ua(t,{})}function zp(e,t){try{const r=qc(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Vp(){return{groupAssignments:[...$s.groupAssignments],focusedGroup:$s.focusedGroup,groupActiveTabIds:{...$s.groupActiveTabIds},groupTabOrders:{...$s.groupTabOrders},groupSizes:[...$s.groupSizes]}}function Gp(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function qp(){const[e]=o.useState(()=>Kp(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=Op(e)??Vp();r(new Map(g.groupAssignments)),a(g.focusedGroup),c(g.groupActiveTabIds),d(g.groupTabOrders),u(g.groupSizes),S(!0)},[v,e]);o.useEffect(()=>{v&&Wp(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)"),E=M=>m(M.matches);return g.addEventListener("change",E),()=>g.removeEventListener("change",E)},[]);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)},[]),A=o.useCallback(g=>{u(g)},[]),y=o.useCallback(g=>{j(g)},[j]),I=o.useCallback((g,E)=>{c(M=>(M[g]??null)===(E??null)?M:{...M,[g]:E})},[]),k=o.useCallback((g,E)=>{d(M=>{const C=M[g];return Gp(C,E)?M:{...M,[g]:E}})},[]),w=o.useCallback((g,E)=>{const M=E.get(g)??0;return I(M,g),y(M),M},[y,I]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:h,focusedGroup:n,updateFocusedGroup:j,focusGroup:y,groupActiveTabIds:i,updateGroupActiveTabIds:b,setGroupActiveTab:I,groupTabOrders:l,updateGroupTabOrders:N,setGroupTabOrder:k,groupSizes:f,updateGroupSizes:A,isMobile:x,hasHydratedStoredLayout:v,hydrateStoredLayout:p,focusConversationTab:w}}function Yp(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 Xp({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||Yp(j.chats,f))&&(h.current=!0,m())},[d,f,u,x,m]),o.useEffect(()=>{if(!f)return;let j=null,b=0,N=-1,A=0;const y=()=>{j=null;const I=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(w=>w.offsetParent!==null);if(I.length===0){b<18&&(b+=1,j=requestAnimationFrame(y));return}let k=0;for(const w of I)w.scrollTop=w.scrollHeight,k+=w.scrollHeight;k===N?A+=1:(A=0,N=k),b+=1,!(A>=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 Yc({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(A=>setTimeout(A,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 Jp(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 Qp(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 Zp(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 eh(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 th({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,I)=>{t(k=>{const w=new Map(vr(k,f).assignments);return I===0?w.delete(y):w.set(y,I),w}),n(k=>({...k,[I]:y})),r(I)},[t,f,n,r]),h=o.useCallback(y=>{t(I=>{const k=vr(I,f).assignments,w=new Map;for(const[g,E]of k)E!==y&&(E>y?w.set(g,E-1):w.set(g,E));return w}),c(I=>{if(I.length<=1)return[];const k=[...I];k.splice(y,1);const w=k.reduce((g,E)=>g+E,0);return w>0?k.map(g=>g/w*100):[]}),r(0)},[t,f,c,r]),j=o.useCallback((y,I)=>{I.preventDefault();const k=u.current;if(!k)return;const w=I.clientX,g=k.offsetWidth,E=i.length===v?[...i]:Go(v),M=R=>{const z=(R.clientX-w)/g*100,T=[...E];T[y]=Math.max(15,E[y]+z),T[y+1]=Math.max(15,E[y+1]-z),c(T)},C=()=>{document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",C),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",C)},[i,v,c]),b=o.useCallback((y,I,k)=>{if(v>=4)return;const w=k==="left"?I:I+1;t(g=>{const E=vr(g,f).assignments,M=new Map;for(const C of d){const R=E.get(C.tabKey)??0,K=R>=w?R+1:R;K>0&&M.set(C.tabKey,K)}return w>0&&M.set(y,w),M}),c(g=>{const E=g.length===v?[...g]:Go(v),M=E[I]??100/v,C=Math.max(15,M/2),R=Math.max(15,M/2),K=[...E];K[I]=C,K.splice(w,0,R);const z=K.reduce((T,L)=>T+L,0);return K.map(T=>T/z*100)}),n(g=>{const E=Vo(g,w);return E[w]=y,E}),a(g=>{const E=Vo(g,w);return E[w]=[y],E}),r(w)},[v,t,f,d,c,n,a,r]);o.useEffect(()=>{Jp(e,m)||t(m)},[e,m,t]),o.useEffect(()=>{const{mapping:y,usedGroups:I}=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:Zp(k,I,y);return k===w?k:w}),c(k=>{const w=l?[]:eh(k,I,x.groupCount);return Qp(k,w)?k:w})},[x,l,n,a,r,c]);const N=o.useMemo(()=>{const y=Array.from({length:v},()=>[]);for(const I of d){const k=m.get(I.tabKey)??0,w=Math.min(k,v-1);y[w].push(I)}return y},[d,m,v]),A=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:A}}function sh({ides:e,sendDaemonCommand:t}){const r="0.9.26",n=o.useMemo(()=>e.filter(u=>u.type!=="adhdev-daemon"?!1:_c(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 Xc=80;function Pr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function rh(e){return{...e,createdAt:Pr(e.createdAt),updatedAt:Pr(e.updatedAt,e.createdAt),lastEventAt:Pr(e.lastEventAt,e.updatedAt||e.createdAt)}}function nh(e){const t=Ca(e);return t==="unknown:"?e.id:t}function ah(e){return[e.type,ac(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function oh(e,t=Xc){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=nh(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 ih(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=ah({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(rh({id:f,dedupKey:f,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:tc(a),preview:pm(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return oh(n)}function ch(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function lh(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Xc}=e,a=o.useMemo(()=>ih(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>ch(a),[a]);return{notifications:a,unreadCount:i}}function dh({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 uh(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=uh(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 mh(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 fh(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=fh(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 ph(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 hh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function xh({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"||ph(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=cc({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 bh({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 A={cliType:S};(j=p==null?void 0:p.workspacePath)!=null&&j.trim()?A.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(A.workspaceId=p.workspaceId),(b=p==null?void 0:p.resumeSessionId)!=null&&b.trim()&&(A.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(A.cliArgs=p.cliArgs),(N=p==null?void 0:p.initialModel)!=null&&N.trim()&&(A.initialModel=p.initialModel.trim());const y=await e(m,"launch_cli",A),I=(y==null?void 0:y.result)||y,k=(I==null?void 0:I.sessionId)||(I==null?void 0:I.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)||(I==null?void 0:I.error)||`Could not launch ${v.toUpperCase()} session`}}catch(A){return hh(A)?(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:A instanceof Error?A.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 Uc({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 gh(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 yh(e,t,r=Date.now()){return!e||!gh(t)?null:{tabKey:e,nonce:r}}function vh({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=xm(p);return b?j.set("activeTab",b):j.delete("activeTab"),j},{replace:!0})},[c]),S=o.useCallback((p,h)=>{const j=yh(p,h);j&&u(j)},[]);return{activeConv:x,openDesktopConversation:v,requestScrollToBottom:S,scrollToBottomRequest:f,setDesktopActiveTab:m}}function wh({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:d}){var T;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),A=o.useMemo(()=>r||t||e,[e,r,t]),y=!!A&&Ze(A)&&!Xe(A),I=o.useMemo(()=>{if(!A||!y)return null;const L=A.daemonId||A.routeId||"",Y=Kt(A);return`${L}:${Y}`},[A,y]),{isCreatingChat:k,isRefreshingHistory:w,handleSwitchSession:g,handleNewChat:E,handleRefreshHistory:M}=Yc({sendDaemonCommand:a,activeConv:A,chats:(T=n.find(L=>L.id===(A==null?void 0:A.routeId)))==null?void 0:T.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),C=o.useCallback(()=>{u(!0)},[]),R=o.useCallback(()=>{u(!1)},[]),K=o.useCallback(async()=>{if(!(!A||!y||p)){h(!0);try{const L=A.daemonId||A.routeId,Y=Kt(A),O=await a(L,"list_saved_sessions",{agentType:Y,providerType:Y,kind:"cli",limit:50}),D=(O==null?void 0:O.result)??O;m(Array.isArray(D==null?void 0:D.sessions)?D.sessions:[])}catch(L){console.error("Refresh saved sessions failed",L),m([])}finally{h(!1)}}},[A,p,y,a]);o.useEffect(()=>{if(!f){N.current=null;return}if(!y){N.current=null,m([]),h(!1);return}!I||p||N.current!==I&&(N.current=I,K())},[K,f,p,y,I]);const z=o.useCallback(async L=>{if(!A||!y||!L.providerSessionId||!L.workspace)return;const Y=A.daemonId||A.routeId,O=Kt(A);try{b(L.providerSessionId);const D=await a(Y,"launch_cli",{cliType:O,dir:L.workspace,resumeSessionId:L.providerSessionId,initialModel:qi(L.summaryMetadata,"model",{preferShortValue:!0})||void 0}),W=(D==null?void 0:D.result)??D,Q=typeof(W==null?void 0:W.sessionId)=="string"?W.sessionId:typeof(W==null?void 0:W.id)=="string"?W.id:"";Q&&d(be=>{const pe=new URLSearchParams(be);return pe.set("activeTab",Q),pe},{replace:!0}),R()}catch(D){console.error("Resume saved session failed",D)}finally{b(null)}},[R,A,y,a,d]);return{historyModalOpen:f,openHistoryModal:C,closeHistoryModal:R,historyTargetConv:A,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:k,isHistoryRefreshingHistory:w,handleHistorySwitchSession:g,handleHistoryNewChat:E,handleHistoryRefresh:M,savedHistorySessions:x,savedHistoryFilters:v,setSavedHistoryFilters:S,isSavedHistoryLoading:p,resumingSavedHistorySessionId:j,handleRefreshSavedHistory:K,handleResumeSavedHistorySession:z}}function jh({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&&!Ze(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 kh({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}=jh({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),A=o.useCallback(async k=>{const w=k||d;!w||!Ze(w)&&!Xe(w)||(N(w),j(!0))},[d]),y=o.useCallback(()=>{j(!1),N(null)},[]),I=o.useCallback(async k=>{const w=b||d;if(!w||!Ze(w)&&!Xe(w)){y();return}j(!1);try{const g=Kt(w),E=w.routeId||w.daemonId||"";await f(E,"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:A,cancelCliStop:y,confirmCliStop:I}}function Jc(){return"select_session"}function Sh(){return"open_panel"}function Nh({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Ch(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(Nh({hasMessage:!!j,blockedMessage:b,sendInFlight:u.current}))return b&&f(b),!1;const N=Date.now(),A={tabKey:t.tabKey,message:j,timestamp:N};if(Ch(x.current,A))return f(null),!0;u.current=!0,l(!0),f(null),x.current=A;try{const y=Zs(t);if(!y)return x.current=Yo(x.current,A),f("Unable to send message right now."),!1;const I=await e(y,"send_chat",{message:j,...js(t)}),k=Xo(I);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 I=za(y);return I.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",I):console.warn("Send blocked/failed",y),x.current=Yo(x.current,A),f(Dm(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(),A=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),y=Zs(t);if(!y)return;const I=await e(y,"resolve_action",{button:h,action:A?"approve":"reject",...b>=0&&{buttonIndex:b},...js(t)}),k=Xo(I);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,Sh(),{...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),A=o.useRef(n);o.useEffect(()=>{const C=A.current;if(A.current=n,!n){N(!1);return}if(C){N(!0);return}N(!1);let R=0,K=0;return R=window.requestAnimationFrame(()=>{K=window.requestAnimationFrame(()=>{N(!0)})}),()=>{window.cancelAnimationFrame(R),window.cancelAnimationFrame(K)}},[n]);const y=n&&b,I=!n||!b,k=In(j,n),w=In(j,I),g=In(j),E=Kc(t),M=E.status||E.modalMessage||E.modalButtons?{...t,...E.status?{status:E.status}:{},...E.modalMessage!==void 0?{modalMessage:E.modalMessage}:{},...E.modalButtons!==void 0?{modalButtons:E.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Fi,{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(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,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(pf,{activeConv:M,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:I?"visible":"hidden",pointerEvents:I?"auto":"none"},children:s.jsx(na,{activeConv:M,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:M,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 Ih({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:A,handleRelaunch:y}){const I=o.useRef(null),k=Ze(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:nt(e)}),s.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:s.jsx(lc,{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:I,handleModalButton:A,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 Mh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Qc(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(Mh())},[]);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 Zc({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=nt(e.conversation),x=us(e.conversation),m=bc(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:Hi(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 Ah({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,A=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",I=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:A}),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] ${I}`,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(Qc,{})})}):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:vc,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(nt(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:nt(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(Zc,{section:e,onSectionChange:S})]})}function Th(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 el(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=Th(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=mh(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 Lh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Rh(e){return[Lh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Ph(e){return e.lastLaunchedAt?Jr(e.lastLaunchedAt):""}function tl(e){return{metaText:Rh(e),updatedLabel:Ph(e)}}function An(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function _h({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var dt,mt,ot,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(Ie=>({id:Ie.id,path:Ie.path,label:Ie.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([]),[A,y]=o.useState(!1),[I,k]=o.useState(""),[w,g]=o.useState(!1),[E,M]=o.useState(An(f,t.length,r.length)),C=o.useRef(null),[R,K]=o.useState(null),z=o.useRef("__home__"),[T,L]=o.useState("__home__"),[Y,O]=o.useState(""),[D,W]=o.useState(""),[Q,be]=o.useState(""),[pe,ue]=o.useState([]),[we,ye]=o.useState(()=>ht().textQuery),[ve,V]=o.useState(()=>ht().workspaceQuery),[H,Z]=o.useState(()=>ht().modelQuery),[me,ne]=o.useState(()=>ht().resumableOnly),[fe,se]=o.useState(()=>ht().sortMode),[xe,ie]=o.useState(!1),[ce,ae]=o.useState(!1),X=o.useRef(null),J=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const oe=m==="__custom__"?S.trim():((ot=u.find(Ie=>Ie.id===m))==null?void 0:ot.path)||"",P=m==="__custom__"&&!!oe&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),G=m!=="__custom__"&&((ut=u.find(Ie=>Ie.id===m))==null?void 0:ut.path)||"",U=o.useMemo(()=>(e.recentLaunches||[]).map(Ie=>Ie.workspace),[e]),de=o.useCallback(async Ie=>{y(!0),k("");try{const $e=await a(Ie);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]),Ne=o.useCallback(()=>{var $e;v("__custom__"),g(!0);const Ie=sn(e.platform,tn(S.trim(),G,U,e.defaultWorkspacePath,($e=u.find(Ue=>Ue.id===x))==null?void 0:$e.path,u.map(Ue=>Ue.path)));de(Ie)},[S,x,de,U,G,e.platform,u]),_e=o.useCallback(Ie=>{if(Ie!=null&&Ie.workspaceId){v(Ie.workspaceId),p("");return}if(Ie!=null&&Ie.workspacePath){v("__custom__"),p(Ie.workspacePath);return}v(""),p("")},[]),ge=o.useCallback(Ie=>{if(v(Ie),Ie==="__custom__"){Ne();return}p("")},[Ne]),Be=o.useCallback(Ie=>{v("__custom__"),p(Ie)},[]),Oe=o.useCallback((Ie,$e)=>{C.current=$e,z.current=Ie.selectedWorkspaceKey||"__home__",L(Ie.selectedWorkspaceKey||"__home__"),O(Ie.initialArgs||""),W(Ie.initialModel||""),be(""),ue([]);const Ue=Ie.providerType?`${e.id}:${Ie.providerType}`:null;if(wf(J.current,Ue)){const Ve=ht();ye(Ve.textQuery),V(Ve.workspaceQuery),Z(Ve.modelQuery),ne(Ve.resumableOnly),se(Ve.sortMode)}J.current=Ue,K(Ie),Ie.providerType&&i&&(ie(!0),i(Ie.providerType).then(Ve=>ue(Ve||[])).catch(Ve=>console.warn("Failed to load saved sessions",Ve)).finally(()=>ie(!1)))},[i,e.id]),Ke=o.useMemo(()=>wc(pe,{textQuery:we,workspaceQuery:ve,modelQuery:H,resumableOnly:me,sortMode:fe}),[H,me,pe,fe,we,ve]);o.useEffect(()=>{Q&&(Ke.some(Ie=>Ie.providerSessionId===Q)||be(""))},[Ke,Q]);const et=o.useCallback(()=>{C.current&&(ae(!0),C.current().finally(()=>{C.current=null,ae(!1),K(null)}))},[]),Je=o.useCallback(()=>{C.current=null,K(null)},[]),at=o.useCallback(Ie=>{z.current=Ie,L(Ie)},[]);return o.useEffect(()=>{var Ie;X.current!==e.id&&(X.current=e.id,v(x||((Ie=u[0])==null?void 0:Ie.id)||"__custom__"),p(""),j(""),N([]),k(""),g(!1),ye(ht().textQuery),V(ht().workspaceQuery),Z(ht().modelQuery),ne(ht().resumableOnly),se(ht().sortMode),J.current=null,M(An(f,t.length,r.length)))},[r.length,t.length,x,f,e.id,u]),o.useEffect(()=>{var Ie;m!=="__custom__"&&(m&&u.some($e=>$e.id===m)||v(x||((Ie=u[0])==null?void 0:Ie.id)||"__custom__"))},[x,m,u]),o.useEffect(()=>{E==="ide"&&f||E==="cli"&&t.length>0||E==="acp"&&r.length>0||M(An(f,t.length,r.length))},[E,r.length,t.length,f]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:f,workspaceRows:u,defaultWorkspaceId:x,workspaceChoice:m,customWorkspacePath:S,browseCurrentPath:h,browseDirectories:b,browseBusy:A,browseError:I,browseDialogOpen:w,activeLauncherKind:E,launchConfirm:R,launchConfirmWorkspaceKeyRef:z,launchConfirmWorkspaceKey:T,launchConfirmArgs:Y,launchConfirmModel:D,launchConfirmResumeId:Q,launchConfirmSavedSessions:pe,launchConfirmTextFilter:we,launchConfirmWorkspaceFilter:ve,launchConfirmModelFilter:H,launchConfirmResumableOnly:me,launchConfirmSortMode:fe,filteredLaunchConfirmSavedSessions:Ke,launchConfirmSessionsLoading:xe,launchConfirmBusy:ce,resolvedWorkspacePath:oe,canCreateMissingWorkspace:P,openBrowseDialog:Ne,loadBrowsePath:de,handleWorkspaceChoiceChange:ge,chooseCustomWorkspacePath:Be,setCustomWorkspacePath:p,setBrowseDialogOpen:g,setActiveLauncherKind:M,openLaunchConfirm:Oe,handleConfirmLaunch:et,closeLaunchConfirm:Je,setWorkspaceSelectionFromOption:_e,setLaunchConfirmWorkspaceKeyAndSync:at,setLaunchConfirmArgs:O,setLaunchConfirmModel:W,setLaunchConfirmResumeId:be,setLaunchConfirmTextFilter:ye,setLaunchConfirmWorkspaceFilter:V,setLaunchConfirmModelFilter:Z,setLaunchConfirmResumableOnly:ne,setLaunchConfirmSortMode:se}}function Dh({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:A,onListSavedSessions:y}){const I=T=>T==="ide"?"IDE":T==="cli"?"CLI":"ACP",k=r.slice(0,4),w=t.slice(0,3),g=_h({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:y}),E=o.useMemo(()=>k.map(T=>{const{metaText:L,updatedLabel:Y}=tl(T);return{key:`recent-launch:${T.id}`,primary:T.label,secondary:L,updatedLabel:Y,onClick:()=>{const{options:O,selectedKey:D}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspacePath:T.workspace});g.openLaunchConfirm({title:T.kind==="ide"?ss("restart-ide",T.label):T.providerSessionId?Da(T.label):ss("start-fresh",T.label),description:T.kind==="ide"?rs("restart-ide"):T.providerSessionId?Ea():rs("start-fresh"),confirmLabel:T.kind==="ide"?Is("restart-ide"):T.providerSessionId?Ur(!0):Is("start-fresh"),busyLabel:T.kind==="ide"?Ms("restart-ide"):T.providerSessionId?Pa(!0):Ms("start-fresh"),workspaceOptions:O,selectedWorkspaceKey:D,details:[{label:"Mode",value:I(T.kind)},...T.providerType?[{label:"Provider",value:T.providerType}]:[]]},async()=>{const W=O.find(Q=>Q.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(W),await S({...T,workspace:(W==null?void 0:W.workspacePath)??null})})}}}),[g,S,k]),M=o.useMemo(()=>w.map(T=>({key:`recent-chat:${T.conversation.tabKey}`,primary:nt(T.conversation),secondary:df(T.conversation,{timestampLabel:T.timestamp?Hi(T.timestamp):null}),unread:T.unread,onClick:()=>v(T.conversation)})),[v,w]),C=g.showAllRecent?E:E.slice(0,4),R=E.length>0,K=M.length>0,z=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 ${z} 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:[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(T=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${T.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:T.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:T.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:T.secondary})]},T.key))})]}),R&&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:C.map(T=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:T.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:T.primary}),T.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:T.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:T.secondary})]},T.key))}),E.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(T=>!T),children:g.showAllRecent?"Show fewer":`Show ${E.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:T=>g.handleWorkspaceChoiceChange(T.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:g.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[g.workspaceRows.map(T=>s.jsxs("option",{value:T.id,children:[T.id===g.defaultWorkspaceId?"⭐ ":"",Zr(T.path,T.label)||T.path]},T.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(T=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:L,selectedKey:Y}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${T.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:L,selectedWorkspaceKey:Y,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:T.name}]},async()=>{const O=L.find(D=>D.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(O),j(T.type,{workspacePath:(O==null?void 0:O.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:T.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},T.type)):(g.activeLauncherKind==="cli"?n:a).map(T=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const L=g.activeLauncherKind==="cli"?"cli":"acp",{options:Y,selectedKey:O}=os({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.openLaunchConfirm({title:`Launch ${T.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${L.toUpperCase()}`,workspaceOptions:Y,selectedWorkspaceKey:O,details:[{label:"Mode",value:L.toUpperCase()},{label:"Provider",value:T.displayName}],showArgsInput:!0,showModelInput:L==="acp",initialArgs:"",initialModel:"",providerType:T.type},async()=>{const D=Y.find(W=>W.key===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(D),A(L,T.type,{workspaceId:(D==null?void 0:D.workspaceId)??null,workspacePath:(D==null?void 0:D.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:[T.icon?`${T.icon} `:"",T.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath||"Use selected workspace"})]},T.type))})]}),l.message&&s.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,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:T=>{g.loadBrowsePath(T)},onConfirm:T=>{g.chooseCustomWorkspacePath(T),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:T=>g.setLaunchConfirmTextFilter(T.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:g.launchConfirmWorkspaceFilter,onChange:T=>g.setLaunchConfirmWorkspaceFilter(T.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:g.launchConfirmModelFilter,onChange:T=>g.setLaunchConfirmModelFilter(T.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),s.jsxs("select",{value:g.launchConfirmSortMode,onChange:T=>g.setLaunchConfirmSortMode(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled: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:T=>g.setLaunchConfirmResumableOnly(T.target.checked),disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:g.launchConfirmResumeId,onChange:T=>g.setLaunchConfirmResumeId(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Sf()}),g.filteredLaunchConfirmSavedSessions.map(T=>s.jsxs("option",{value:T.providerSessionId,disabled:!T.canResume,children:[T.title||T.providerSessionId," ",T.canResume?"":"(workspace missing)"]},T.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 T=g.filteredLaunchConfirmSavedSessions.find(Y=>Y.providerSessionId===g.launchConfirmResumeId);if(!T)return null;const L=el(T);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:L.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:L.providerSessionId}),s.jsx("div",{className:"mt-1",children:L.metaLine}),L.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:L.updatedLabel}),L.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:L.preview})]})})()]}),onConfirm:g.handleConfirmLaunch,onCancel:g.closeLaunchConfirm}),u&&s.jsx(Zc,{section:f,onSectionChange:m})]})}function Eh(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 $h(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 Bh(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=Eh(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?uf(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 Kh(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 Oh({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 A=o.useRef(null),y=o.useCallback(I=>{if(!(I!=null&&I.sessionId))return;const k=Or(I,c),w=Math.max(Date.now(),es(I),k.lastUpdated||0);kr("mark_read:start",{tabKey:I.tabKey,sessionId:I.sessionId,displayPrimary:nt(I),inboxBucket:k.inboxBucket,unread:k.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:es(I),readAt:w}),l(fs(I)||I.routeId,"mark_session_seen",{sessionId:I.sessionId,seenAt:w}).then(g=>{kr("mark_read:result",{tabKey:I.tabKey,sessionId:I.sessionId,result:g})}).catch(g=>{kr("mark_read:error",{tabKey:I.tabKey,sessionId:I.sessionId,error:g instanceof Error?g.message:String(g)})})},[c,l]);return o.useEffect(()=>{var k;if(!n){Kh(i)&&p("inbox"),S(((k=e[0])==null?void 0:k.tabKey)||null),A.current=null;return}if(i!=="chat"){A.current=null;return}const I=`${n.tabKey}:${n.sessionId||""}`;A.current!==I&&(A.current=I,y(n))},[e,y,i,n,p,S]),o.useEffect(()=>{if(!d)return;const I=e.find(k=>k.tabKey===d);I&&(S(I.tabKey),p("chat"),f==null||f())},[e,f,d,p,S]),o.useEffect(()=>{if(!u)return;const I=t.find(k=>k.id===u);I&&(h(I.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 I=r.filter(k=>k.inboxBucket==="task_complete"||k.unread);I.length!==0&&kr("inbox_state",{screen:i,selectedTabKey:a,items:I.map(k=>{const w=Or(k.conversation,c);return{liveState:w,tabKey:k.conversation.tabKey,sessionId:k.conversation.sessionId,displayPrimary:nt(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 Wh(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 Hh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Fh({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,A)=>{var y;try{i("loading"),l(`Launching ${N}…`);const I={ideType:N,enableCdp:!0};(y=A==null?void 0:A.workspacePath)!=null&&y.trim()&&(I.workspace=A.workspacePath.trim()),await e(b,"launch_ide",I),i("done"),l(`${N} launch requested`)}catch(I){i("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),m=o.useCallback(async(b,N,A)=>{if(N.trim())try{i("loading"),l(A!=null&&A.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(b,"workspace_add",{path:N.trim(),createIfMissing:(A==null?void 0:A.createIfMissing)===!0});if(y!=null&&y.success){i("done"),l(A!=null&&A.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,A,y,I,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${((A=g==null?void 0:g.result)==null?void 0:A.version)||"latest"}.`);return}if((y=g==null?void 0:g.result)!=null&&y.upgraded||(I=g==null?void 0:g.result)!=null&&I.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,A,y)=>{var w,g,E;const I=Date.now(),k={machineId:b,kind:N,providerType:A,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:I};try{i("loading"),l(`Launching ${A}…`),f(k);const M={cliType:A};(w=y==null?void 0:y.workspacePath)!=null&&w.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)),(E=y==null?void 0:y.model)!=null&&E.trim()&&(M.initialModel=y.model.trim());const C=await e(b,"launch_cli",M),R=(C==null?void 0:C.result)||C,K=(R==null?void 0:R.sessionId)||(R==null?void 0:R.id);if(C!=null&&C.success&&K){f(null),i("done"),l(`${A} launched`),t(Gt(K));return}if(C!=null&&C.success){i("loading"),l(`${A} launch requested — waiting for session…`);return}f(null),i("error"),l((C==null?void 0:C.error)||(R==null?void 0:R.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(M){if(Hh(M)){i("loading"),l(`${A} 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 A=await e(b,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),y=(A==null?void 0:A.result)??A;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(A){return console.error("Failed to list saved sessions on mobile:",A),[]}},[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 M,C,R,K;if(!y||y.type==="adhdev-daemon"||Wh(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 z=ti(y.workspace||y.runtimeWorkspaceLabel);return z?z===b:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((K=(R=(C=(M=y.activeChat)==null?void 0:M.messages)==null?void 0:C.at)==null?void 0:R.call(C,-1))==null?void 0:K.timestamp)||0)>=d.startedAt-5e3});if(!N)return;const A=cc({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});A&&(f(null),i("done"),l(`${d.providerType} launched`),t(Gt(A)))},[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 Uh({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 zh(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 Vh({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:A,onHideConversation:y,onOpenNewSession:I,liveSessionInboxState:k,setCliViewModeOverrides:w}){const[g,E]=o.useState(()=>{var G;return((G=e[0])==null?void 0:G.tabKey)||null}),[M,C]=o.useState(()=>e[0]?"chat":"inbox"),[R,K]=o.useState("chats"),[z,T]=o.useState(null),[L,Y]=o.useState("inbox"),O=As(),D="0.9.26",W=o.useMemo(()=>e.find(G=>G.tabKey===g)||e[0]||null,[e,g]),Q=o.useMemo(()=>W?r.find(G=>G.id===W.routeId):void 0,[r,W]),be=o.useMemo(()=>!W||Xe(W)||!Ze(W)?null:Ls(W),[W]),pe=o.useMemo(()=>r.filter(G=>G.type==="adhdev-daemon").sort(wa),[r]),ue=o.useMemo(()=>pe.find(G=>G.id===z)||null,[pe,z]),we=nn({sendDaemonCommand:a,activeConv:W||void 0,setActionLogs:i,isStandalone:c}),ye=Fh({sendDaemonCommand:a,navigate:O,ides:r,conversations:e}),ve=o.useMemo(()=>e.map(G=>{const U=M==="chat"&&(W==null?void 0:W.tabKey)===G.tabKey,de=Qr(G,k,{hideOpenTaskCompleteUnread:!0,isOpenConversation:U}),Ne=es(G),_e=xc(G);return{conversation:G,timestamp:Ne,preview:_e,unread:de.unread,requiresAction:de.requiresAction,isWorking:de.isWorking,inboxBucket:de.inboxBucket}}),[e,k,M,W]),{markConversationRead:V}=Oh({conversations:e,machineEntries:pe,items:ve,selectedConversation:W,selectedTabKey:g,screen:M,liveSessionInboxState:k,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:x,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,setSelectedTabKey:E,setScreen:C,setSelectedMachineId:T,setSection:K,setMachineBackTarget:Y,resetMachineAction:ye.resetMachineAction}),H=Uh({conversations:e,selectedConversation:W,machineBackTarget:L,markConversationRead:V,resetMachineAction:ye.resetMachineAction,setSelectedTabKey:E,setScreen:C,setSelectedMachineId:T,setSection:K,setMachineBackTarget:Y}),Z=o.useMemo(()=>Sr(ve.filter(G=>G.requiresAction)),[ve]),me=o.useMemo(()=>Sr(ve.filter(G=>G.unread&&!G.requiresAction)),[ve]),ne=o.useMemo(()=>Sr(ve.filter(G=>!G.unread&&!G.requiresAction&&G.isWorking)),[ve]),fe=o.useMemo(()=>Sr(ve.filter(G=>!G.unread&&!G.requiresAction&&!G.isWorking)),[ve]),se=o.useMemo(()=>ue?ve.filter(G=>fs(G.conversation)===ue.id):[],[ve,ue]),xe=o.useMemo(()=>$h(ue,r),[r,ue]),ie=(ue==null?void 0:ue.version)||null,ce=!!ue&&!!ie&&!0&&ie!==D,ae=o.useMemo(()=>(ue==null?void 0:ue.availableProviders)||[],[ue]),X=o.useMemo(()=>ae.filter(G=>G.category==="cli"&&G.installed!==!1).map(G=>({type:G.type,displayName:G.displayName||G.type,icon:G.icon})),[ae]),J=o.useMemo(()=>ae.filter(G=>G.category==="acp"&&G.installed!==!1).map(G=>({type:G.type,displayName:G.displayName||G.type,icon:G.icon})),[ae]),oe=o.useMemo(()=>Bh(pe,ve),[ve,pe]),P=o.useCallback(async G=>{ue&&await ye.handleOpenRecent(ue.id,G)},[ye,ue]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&W?s.jsx(Ih,{selectedConversation:W,isAcp:Xe(W),isStandalone:c,selectedIdeEntry:Q,actionLogs:n,userName:l,isSendingChat:we.isSendingChat,sendFeedbackMessage:we.sendFeedbackMessage,isFocusingAgent:we.isFocusingAgent,handleModalButton:we.handleModalButton,handleRelaunch:we.handleRelaunch,onBack:H.backFromConversation,onOpenNativeConversation:H.openNativeConversation,onOpenMachine:H.openConversationMachine,onHideConversation:y,onOpenHistory:S,onOpenRemote:p,onStopCli:h,cliViewMode:be,onSetCliViewMode:async G=>{await Uc({conversation:W,mode:G,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:w})},handleSendChat:we.handleSendChat,handleFocusAgent:we.handleFocusAgent}):M==="machine"&&ue?s.jsx(Dh,{selectedMachineEntry:ue,selectedMachineConversations:se,selectedMachineRecentLaunches:xe,cliProviders:X,acpProviders:J,selectedMachineNeedsUpgrade:ce,appVersion:D,machineAction:ye.machineAction,isStandalone:c,section:R,showBottomNav:L==="inbox",onBack:H.backFromMachine,onSectionChange:H.changeMachineSection,onOpenConversation:H.openConversation,onOpenRecent:P,onOpenMachineDetails:()=>O(`/machines/${ue.id}`),onMachineUpgrade:()=>ye.handleMachineUpgrade(ue.id),onLaunchDetectedIde:(G,U)=>ye.handleLaunchDetectedIde(ue.id,G,U),onAddWorkspace:(G,U)=>ye.handleAddWorkspace(ue.id,G,U),onBrowseDirectory:G=>ye.handleBrowseDirectory(ue.id,G),onLaunchWorkspaceProvider:(G,U,de)=>ye.handleLaunchWorkspaceProvider(ue.id,G,U,de),onListSavedSessions:G=>ye.handleListSavedSessions(ue.id,G)}):s.jsx(Ah,{section:R,attentionItems:Z,unreadItems:me,workingItems:ne,completedItems:fe,hiddenConversations:t,machineCards:oe,getAvatarText:zh,onOpenConversation:H.openConversation,onShowConversation:N,onShowAllHidden:A,onOpenNewSession:I,onOpenMachine:H.openMachine,onOpenSettings:()=>O("/settings"),onSectionChange:K,wsStatus:j,isConnected:b,isStandalone:c})})}function Tn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Gh({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(A=>A.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 qh(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 Yh({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=qh(k,e);return w.length===k.length&&w.every((g,E)=>g===k[E])?k:w})},[e]);const p=o.useMemo(()=>{const k=f??l;if(k.length===0)return e;const w=new Map(k.map((g,E)=>[g,E]));return[...e].sort((g,E)=>{const M=w.get(g.tabKey)??999,C=w.get(E.tabKey)??999;return M-C})},[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(E=>E.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(E=>{var K;const M=E.filter(z=>z!==k),C=M.indexOf(w);if(C<0)return E;const R=g==="left"?C:C+1;return M.splice(R,0,k),(K=S.current)==null||K.call(S,M),M}),u(null)},[]),N=o.useCallback((k,w,g)=>{const M=(l.length>0?l:e.map(K=>K.tabKey)).filter(K=>K!==k),C=M.indexOf(w);if(C<0)return;const R=g==="left"?C:C+1;M.splice(R,0,k),x.current=M,u(M)},[l,e]),A=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)},[]),I=o.useCallback(k=>{d(w=>{var E;const g=w.filter(M=>M!==k);return g.push(k),(E=S.current)==null||E.call(S,g),g})},[]);return{activeTabId:i,activeConv:h,sortedConversations:p,previewOrderRef:x,draggingTabRef:m,selectTab:j,handleTabReorder:b,updatePreviewOrder:N,commitPreviewOrder:A,clearPreviewOrder:y,moveTabToEnd:I,setDraggingTabKey:k=>{m.current=k}}}function Xh({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?vc: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(Ei,{size:14}),s.jsx("span",{children:$t})]})}),c&&s.jsx(Qc,{}),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 sl="adhdev-tab-shortcuts";function rl(){try{return JSON.parse(localStorage.getItem(sl)||"{}")}catch{return{}}}function nl({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>rl()),[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(sl,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 Jh=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:A}){const y=Ts(t),I=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",k=y.isReconnecting,w=o.useCallback(L=>{l.current=t.tabKey,h(t.tabKey),L.dataTransfer.setData("text/tab-key",t.tabKey),L.dataTransfer.effectAllowed="move"},[t.tabKey,l,h]),g=o.useCallback(()=>{l.current=null,h(null),v(),S(),p()},[l,h,v,S,p]),E=o.useCallback(L=>{const Y=l.current;if(!(!Y||Y===t.tabKey)&&L.dataTransfer.types.includes("text/tab-key")){L.preventDefault(),L.stopPropagation();const O=L.currentTarget.getBoundingClientRect(),D=L.clientX<O.left+O.width/2?"left":"right";x(Y,t.tabKey,D)}},[t.tabKey,l,x]),M=o.useCallback(L=>{L.preventDefault(),L.stopPropagation();const Y=L.dataTransfer.getData("text/tab-key");if(Y&&Y!==t.tabKey){const O=L.currentTarget.getBoundingClientRect(),D=L.clientX<O.left+O.width/2?"left":"right";c.includes(Y)?m(Y,t.tabKey,D):j&&j(Y)}S()},[t.tabKey,c,m,j,S]),C=o.useCallback(L=>{L.stopPropagation(),d(),f(t.tabKey),u(t)},[t,u,d,f]),R=o.useCallback(L=>{L.preventDefault(),b(L.clientX,L.clientY,t.tabKey)},[t.tabKey,b]),K=o.useCallback(L=>{const Y=L.touches[0];N.current=setTimeout(()=>{b(Y.clientX,Y.clientY,t.tabKey)},600)},[t.tabKey,N,b]),z=o.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),T=["adhdev-dockview-tab",I,r&&"is-active",A&&"is-group-active",k&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:T,draggable:!0,onDragStart:w,onDragEnd:g,onDragOver:E,onDrop:M,onClick:C,onContextMenu:R,onTouchStart:K,onTouchEnd:z,onTouchMove:z,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:nt(t),children:nt(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 Qh({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),A=o.useRef(null),y=o.useRef(null),I=o.useMemo(()=>e.map(R=>R.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:E,saveShortcuts:M}=nl({enabled:j,sortedTabKeys:e.map(R=>R.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!b)return;const R=K=>{const z=document.querySelector("[data-pane-context-menu]");z&&z.contains(K.target)||N(null)};return window.addEventListener("mousedown",R,!0),()=>window.removeEventListener("mousedown",R,!0)},[b]),o.useEffect(()=>{const R=y.current;if(!R)return;const K=z=>{Math.abs(z.deltaY)<=Math.abs(z.deltaX)||(z.preventDefault(),R.scrollLeft+=z.deltaY)};return R.addEventListener("wheel",K,{passive:!1}),()=>R.removeEventListener("wheel",K)},[]);const C=o.useCallback((R,K,z)=>{N({x:R,y:K,tabKey:z})},[]);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(R=>s.jsx(Jh,{conv:R,isActive:t===R.tabKey,isDraggedTab:a.current===R.tabKey,isTaskCompleteUnread:n.has(R.tabKey),shortcut:j?w[R.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:x,onDragStateReset:m,onDragTabKeyChange:v,onReceiveTab:S,onOpenContextMenu:C,longPressTimer:A,isGroupActive:h},R.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:R=>{R.stopPropagation(),E(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 R={...w};delete R[b.tabKey],M(R),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:()=>E(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:R=>R.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 Zh({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:A,isFocused:y,allowTabShortcuts:I=!0,onOpenNewSession:k,liveSessionInboxState:w}){const{sendCommand:g}=wt(),E=o.useRef(null),{activeTabId:M,activeConv:C,sortedConversations:R,draggingTabRef:K,selectTab:z,handleTabReorder:T,updatePreviewOrder:L,commitPreviewOrder:Y,clearPreviewOrder:O,moveTabToEnd:D,setDraggingTabKey:W}=Yh({conversations:e,initialActiveTabId:j,initialTabOrder:b,onActiveTabChange:h,onTabOrderChange:N}),Q=nn({sendDaemonCommand:a,activeConv:C,setActionLogs:i,isStandalone:c}),{dragOver:be,dropAction:pe,resetDragState:ue,handleDragEnter:we,handleDragOver:ye,handleDragLeave:ve,handleDrop:V}=Gh({conversations:e,numGroups:m,onMoveTab:v,onReceiveTab:S,onOwnTabDrop:D,onClearPreviewOrder:O}),H=C&&!Xe(C)&&Ls(C)==="terminal",Z=o.useMemo(()=>C?t.find(se=>se.id===C.routeId):void 0,[t,C]),me=o.useMemo(()=>C?n.filter(se=>se.routeId===C.tabKey):[],[n,C]),ne=o.useMemo(()=>new Set(R.filter(se=>ju(se,w,{isOpenConversation:se.tabKey===M})).map(se=>se.tabKey)),[M,w,R]);rr("PaneGroup",{groupIndex:f,conversationCount:e.length,activeTabId:M,dragOver:be});const fe=o.useCallback(se=>{se.streamSource==="agent-stream"&&se.agentType&&g(se.routeId,Jc(),{agentType:se.agentType,...se.sessionId&&{targetSessionId:se.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(Qh,{conversations:R,activeTabId:M,groupIndex:f,numGroups:m,unreadTabKeys:ne,draggingTabRef:K,onFocus:u,onSelectTab:z,onConversationActivated:fe,onPreviewReorder:L,onReorderTab:T,onCommitPreviewOrder:Y,onClearPreviewOrder:O,onDragStateReset:ue,onDragTabKeyChange:W,onMoveTab:v,onReceiveTab:S,onHideTab:A,isGroupActive:y??!1,allowTabShortcuts:I}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:we,onDragOver:ye,onDragLeave:ve,onDrop:V,children:[be&&s.jsx(Xh,{dropAction:pe,canSplit:!!(m<4&&v)}),C?s.jsx(Va,{activeConv:C,clearToken:r[C.tabKey]||0,isCliTerminal:!!H,ideEntry:Z,terminalRef:E,handleModalButton:Q.handleModalButton,handleRelaunch:Q.handleRelaunch,handleSendChat:Q.handleSendChat,isSendingChat:Q.isSendingChat,sendFeedbackMessage:Q.sendFeedbackMessage,handleFocusAgent:Q.handleFocusAgent,isFocusingAgent:Q.isFocusingAgent,actionLogs:me,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 ex({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:A,groupTabOrders:y,setGroupTabOrder:I,toggleHiddenTab:k,onOpenNewSession:w,allowTabShortcuts:g=!0,liveSessionInboxState:E}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((M,C)=>{const R=t&&n.length===r?`${n[C]}%`:void 0;return s.jsxs(kt.Fragment,{children:[t&&C>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(C-1,K),onDoubleClick:()=>j(C),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(Zh,{style:t?{flexBasis:R??`${100/r}%`,flexGrow:R?0:1,flexShrink:R?0:1}:void 0,conversations:M,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:f,isStandalone:u,hasRegisteredMachines:x,userName:m,groupIndex:C,isFocused:t&&v===C,onFocus:()=>S(C),isSplitMode:t,numGroups:r,onMoveTab:(K,z)=>{z==="left"&&C>0?p(K,C-1):z==="right"&&C<r-1?p(K,C+1):z==="split-left"&&r<4?h(K,C,"left"):z==="split-right"&&r<4&&h(K,C,"right")},onReceiveTab:K=>p(K,C),onActiveTabChange:K=>A(C,K),initialActiveTabId:N[C],initialTabOrder:y[C],onTabOrderChange:K=>I(C,K),onHideTab:k,onOpenNewSession:w,allowTabShortcuts:g,liveSessionInboxState:E})]},C)})})}function al({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?it.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=it.onStatus)==null?void 0:u.call(it,(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?it.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?it.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 ol="adhdev-dashboard-action-shortcuts",tx=1200,sx={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function rx(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function tt(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 il(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:tt("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:tt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:tt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:tt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:tt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:tt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:tt("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:tt("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:tt("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:tt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:tt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:tt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:tt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:tt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:tt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:tt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:tt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:tt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:tt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:tt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:tt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:tt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:tt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:tt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:tt("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(il(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(ol)||"{}"),n={...t,...r};for(const[a,i]of Object.entries(sx))n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function cl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function nx({enabled:e=!0,onTrigger:t}){const r=rx(),[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(cl(p.key)),h.join("+"))},[r]),x=o.useCallback(p=>{a(p);try{localStorage.setItem(ol,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}},tx))},[]);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(" "),I={...n};for(const[k,w]of Object.entries(I))w===y&&delete I[k];I[i]=y,x(I),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,A=b?[j]:[...N.slice(-1),j].slice(-2),y=A.join(" "),I=A[A.length-1],k=Object.entries(n).filter(([,C])=>!!C),w=k.find(([,C])=>C===y);if(w){h.preventDefault(),m(),t(w[0]);return}if(k.some(([,C])=>C.startsWith(`${y} `))){h.preventDefault(),f.current.parts=A,v();return}const E=k.find(([,C])=>C===I);if(E){h.preventDefault(),m(),t(E[0]);return}if(k.some(([,C])=>C.startsWith(`${I} `))){h.preventDefault(),f.current.parts=[I],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(()=>il(r),[r]);return{isMac:r,actionDefinitions:S,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:x}}function ax({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 ll(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?!ll(n):!0}function ox({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:ll(r)}const dl=o.createContext(null);function on(){const e=o.useContext(dl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function _r(e){return nt(e)||e.tabKey}function ix(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function ri(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}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 cx(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 lx(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?ix(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=yc(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 dx({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 ux({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}=al({doId:a,targetSessionId:r?nc(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(Wi,{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 mx(){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 fx(e){var v,S;cx(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:nt(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:nt(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 px({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:A,layoutProfile:y}){var ft,Tt,yt;const{theme:I}=Ka(),{sendCommand:k}=wt(),w=o.useRef(null),g=o.useRef(null),E=o.useRef(!1),M=o.useRef(!1),C=o.useRef(!1),R=o.useRef(null),K=o.useRef([]),[z,T]=o.useState(null),[L,Y]=o.useState(!1),[O,D]=o.useState(!1),[W,Q]=o.useState(0),be=o.useRef(null),pe=o.useRef(typeof window>"u"?{}:Up(y)),ue=o.useMemo(()=>new Map(e.map(B=>[B.tabKey,B])),[e]),we=o.useMemo(()=>{const B=w.current;return B?B.groups.some($=>{try{const F=$.model.location.type;return F!=="floating"&&F!=="popout"?!1:$.panels.some(q=>ue.has(q.id))}catch{return!1}}):!1},[ue,W,e]),ye=o.useCallback(()=>{var B;(B=w.current)==null||B.focus()},[]),ve=o.useCallback((B,$)=>{p==null||p(B,$)},[p]),V=o.useCallback(B=>{const $=document,F=B.document;for(const Ce of $.querySelectorAll('link[rel="stylesheet"]')){const re=F.createElement("link");re.rel="stylesheet",re.href=Ce.href,Ce.crossOrigin&&(re.crossOrigin=Ce.crossOrigin),F.head.appendChild(re)}for(const Ce of $.querySelectorAll("style")){const re=F.createElement("style");re.textContent=Ce.textContent,F.head.appendChild(re)}const q=[];for(const Ce of $.styleSheets)try{for(const re of Ce.cssRules)re instanceof CSSStyleRule&&(re.selectorText===":root"||re.selectorText==="html")&&q.push(re.cssText)}catch{}if(q.length>0){const Ce=F.createElement("style");Ce.textContent=q.join(`
43
+ `),F.head.appendChild(Ce)}const le=$.documentElement.getAttribute("data-theme");le&&F.documentElement.setAttribute("data-theme",le),F.documentElement.style.colorScheme=le==="light"?"light":"dark",F.body.className=$.body.className;const ke=$.documentElement.getAttribute("style");ke&&F.documentElement.setAttribute("style",ke);const Me=F.getElementById("dv-popout-window");Me instanceof HTMLElement&&(Me.classList.add("adhdev-dockview"),Nr(Me,I))},[I]),H=o.useCallback(()=>{var $;const B=w.current;if(B)for(const F of B.groups)try{const q=($=F.element)==null?void 0:$.ownerDocument;if(!q||q===document)continue;const le=q.getElementById("dv-popout-window");le instanceof HTMLElement&&(le.classList.add("adhdev-dockview"),Nr(le,I));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 Me=document.documentElement.getAttribute("style");Me?q.documentElement.setAttribute("style",Me):q.documentElement.removeAttribute("style")}catch{}},[I]),Z=o.useCallback(()=>{var $;const B=w.current;if(B)for(const F of B.groups)try{const q=($=F.element)==null?void 0:$.ownerDocument;if(!q||q===document)continue;const le=q.getElementById("dv-popout-window");if(!(le instanceof HTMLElement))continue;le.classList.add("adhdev-dockview"),Nr(le,I),le.classList.toggle("is-showing-dockview-overlay",O),le.classList.toggle("is-dragging-dockview",L)}catch{}},[L,O,I]),me=o.useCallback(B=>{const $=w.current;if(!$)return;const F=$.getPanel(B);F&&$.addPopoutGroup(F,{popoutUrl:"/popout.html",onDidOpen:({window:q})=>{V(q),J();const le=ue.get(B);q.document.title=le?`${nt(le)} — ADHDev`:"ADHDev — Popout"}})},[ue,V]),ne=o.useCallback(B=>{const $=w.current,F=$==null?void 0:$.getPanel(B);if(!$||!F)return;const q=$.groups.filter(le=>{var ke;try{return((ke=le.element)==null?void 0:ke.ownerDocument)===document}catch{return!0}});q.length>0?F.api.moveTo({group:q[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),fe=o.useCallback(B=>{var q;const $=w.current;if(!$)return!1;const F=$.getPanel(B);if(!F)return!1;try{return((q=F.group.element)==null?void 0:q.ownerDocument)!==document}catch{return!1}},[]),se=o.useCallback(B=>{fe(B)&&ne(B),u(B)},[fe,ne,u]),xe=o.useCallback(B=>{const $=w.current,F=$==null?void 0:$.getPanel(B);!$||!F||$.addFloatingGroup(F,{width:600,height:500})},[]),ie=o.useCallback(B=>{var F;const $=(F=w.current)==null?void 0:F.getPanel(B);if(!$)return!1;try{return $.group.model.location.type==="floating"}catch{return!1}},[]),ce=o.useCallback(()=>{var $,F;const B=(F=($=w.current)==null?void 0:$.activePanel)==null?void 0:F.id;return!B||Lt(B)?null:ue.has(B)?B:null},[ue]),ae=o.useCallback(B=>{const $=w.current,F=$==null?void 0:$.getPanel(B);if(!$||!F)return;const q=$.groups.filter(le=>{try{return le.model.location.type==="grid"}catch{return!0}});q.length>0?F.api.moveTo({group:q[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),X=o.useCallback(()=>{var ke;const B=w.current;if(!B)return;const F=B.groups.filter(Me=>{var Ce;try{return((Ce=Me.element)==null?void 0:Ce.ownerDocument)===document&&Me.model.location.type==="grid"}catch{return!1}})[0]||null,q=[...B.panels];for(const Me of q){const Ce=(ke=Me.group.element)==null?void 0:ke.ownerDocument,re=Me.group.model.location.type;Ce===document&&re==="grid"||(F&&F.id!==Me.group.id?Me.api.moveTo({group:F,position:"center"}):Me.api.moveTo({position:"center"}))}const le=B.activePanel;le&&(le.group.model.openPanel(le),le.api.setActive()),Ln(document)},[]),J=o.useCallback(()=>{var $,F;const B=w.current;if(B)for(const q of B.groups){const le=($=q.element)==null?void 0:$.ownerDocument;if(!le||le===document)continue;const ke=le.getElementById("dv-popout-window");if(!(ke instanceof HTMLElement))continue;let Me=null,Ce=le.title||"ADHDev",re="Popout workspace";const je=q.activePanel;if(je)if(Me=je.id,Lt(je.id)){const Pe=((F=je.params)==null?void 0:F.routeId)||je.id.slice(7),_=_t([...ue.values()],Pe);Ce=yc(_),re=_!=null&&_.machineName?`Remote view · ${_.machineName}`:"Remote view"}else{const Pe=ue.get(je.id);Ce=Pe?nt(Pe):je.title||je.id,re=Pe?ts(Pe):"Dockview panel"}le.title=`${Ce} — ADHDev`;const We=Array.from(le.querySelectorAll("#adhdev-popout-header"));for(const Pe of We)Pe.remove();const Fe=le.createElement("div");Fe.id="adhdev-popout-header",le.body.appendChild(Fe),Fe.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(";")),Fe.innerHTML=`
44
+ <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
45
+ <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
46
+ <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${ri(Ce)}</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(re)}</div>
48
+ </div>
49
+ <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
50
+ <button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
51
+ <button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
52
+ </div>
53
+ `,ke.style.top="52px",ke.style.height="calc(100% - 52px)";const Ye=Fe.querySelector("[data-adhdev-popout-focus]");Ye&&(Ye.onclick=()=>{window.focus()});const ze=Fe.querySelector("[data-adhdev-popout-dock]");ze&&(ze.disabled=!Me,ze.style.opacity=Me?"1":"0.5",ze.style.cursor=Me?"pointer":"default",ze.onclick=()=>{var Pe;Me&&ne(Me),(Pe=le.defaultView)==null||Pe.focus()})}},[ue,ne]),oe=o.useCallback(B=>{var q;const $=w.current,F=$==null?void 0:$.getPanel(B);if(!(!$||!F)){F.group.model.openPanel(F),F.api.setActive(),ve(B,"dockview-shortcut");try{const le=F.group.model.location;le.type==="popout"?le.getWindow().focus():Ln((q=F.group.element)==null?void 0:q.ownerDocument)}catch{}}},[ve]),P=o.useCallback(B=>{const $=w.current,F=$==null?void 0:$.activePanel,q=($==null?void 0:$.activeGroup)||(F==null?void 0:F.group);if(!$||!F||!q)return;const le=q.panels||[];if(le.length<=1)return;const ke=le.findIndex(re=>re.id===F.id);if(ke<0)return;const Me=(ke+B+le.length)%le.length,Ce=le[Me];Ce&&(Ce.group.model.openPanel(Ce),Ce.api.setActive(),Lt(Ce.id)||ve(Ce.id,"dockview-shortcut"))},[ve]),G=o.useCallback(B=>{var Ye;const $=w.current,F=($==null?void 0:$.activeGroup)||((Ye=$==null?void 0:$.activePanel)==null?void 0:Ye.group);if(!$||!F)return;const q=$.groups||[],le=q.find(ze=>ze.id===F.id);if(!le)return;const ke=le.element.getBoundingClientRect(),Me=ke.left+ke.width/2,Ce=ke.top+ke.height/2,re=(ze,Pe,_,te)=>Math.max(0,Math.min(Pe,te)-Math.max(ze,_)),je=ze=>{const Pe=ze.element.getBoundingClientRect(),_=Pe.left+Pe.width/2,te=Pe.top+Pe.height/2;let he=0,Re=0,Se=0,Ae=!1;if(B==="left"?(Ae=_<Me,he=Math.max(0,ke.left-Pe.right),Re=Math.abs(te-Ce),Se=re(ke.top,ke.bottom,Pe.top,Pe.bottom)):B==="right"?(Ae=_>Me,he=Math.max(0,Pe.left-ke.right),Re=Math.abs(te-Ce),Se=re(ke.top,ke.bottom,Pe.top,Pe.bottom)):B==="above"?(Ae=te<Ce,he=Math.max(0,ke.top-Pe.bottom),Re=Math.abs(_-Me),Se=re(ke.left,ke.right,Pe.left,Pe.right)):(Ae=te>Ce,he=Math.max(0,Pe.top-ke.bottom),Re=Math.abs(_-Me),Se=re(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 We=null,Fe=Number.POSITIVE_INFINITY;for(const ze of q){if(ze.id===le.id)continue;const Pe=je(ze);Number.isFinite(Pe)&&(Pe>=Fe||(Fe=Pe,We=ze))}return We||void 0},[]),U=o.useCallback(B=>{var q;const $=G(B);if(!$)return;const F=$.activePanel||$.panels[0];F&&($.model.openPanel(F),F.api.setActive(),Lt(F.id)||ve(F.id,"dockview-focus"),Ln((q=$.element)==null?void 0:q.ownerDocument))},[G,ve]),de=o.useCallback((B,$)=>{const F=w.current,q=F==null?void 0:F.activePanel,le=(F==null?void 0:F.activeGroup)||(q==null?void 0:q.group);if(!F||!q||!le)return;let ke=G(B);!ke&&($!=null&&$.createGroupIfMissing)&&(ke=F.addGroup({referenceGroup:le,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"))},[G,ve]),{isMac:Ne,tabShortcuts:_e,shortcutListening:ge,setShortcutListening:Be,saveShortcuts:Oe}=nl({sortedTabKeys:e.map(B=>B.tabKey),onFocus:ye,onSelectTab:oe}),Ke=o.useCallback(()=>{var F;const B=w.current;if(!B)return;const $=B.activePanel;if($){if(Lt($.id)){const q=((F=$.params)==null?void 0:F.routeId)||$.id.slice(7),le=_t(e,q);le!=null&&le.tabKey&&Be(le.tabKey);return}ue.has($.id)&&Be($.id)}},[ue,oe,Be,e]),et=o.useCallback(B=>{const $=[];return B.metaKey&&$.push(Ne?"⌘":"Meta"),B.ctrlKey&&$.push("Ctrl"),B.altKey&&$.push(Ne?"⌥":"Alt"),B.shiftKey&&B.key.length!==1&&$.push(Ne?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(B.key)?null:($.push(cl(B.key)),$.join("+"))},[Ne]),Je=o.useCallback(B=>{var $,F;switch(B){case"splitActiveTabRight":de("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":de("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const q=ce();q&&xe(q);return}case"popoutActiveTab":{const q=ce();q&&me(q);return}case"dockActiveTab":{const q=ce();if(!q)return;fe(q)?ne(q):ie(q)&&ae(q);return}case"focusLeftPane":U("left");return;case"focusRightPane":U("right");return;case"focusUpPane":U("above");return;case"focusDownPane":U("below");return;case"moveActiveTabToLeftPane":de("left");return;case"moveActiveTabToRightPane":de("right");return;case"moveActiveTabToUpPane":de("above");return;case"moveActiveTabToDownPane":de("below");return;case"selectPreviousGroupTab":P(-1);return;case"selectNextGroupTab":P(1);return;case"setActiveTabShortcut":Ke();return;case"hideCurrentTab":{const q=(F=($=w.current)==null?void 0:$.activePanel)==null?void 0:F.id;q&&!Lt(q)&&se(q);return}default:return}},[P,ae,U,xe,ce,se,ie,fe,ne,de,me,Ke]);o.useEffect(()=>{if(!z)return;const B=z.sourceDocument,$=B.defaultView??window,F=q=>{const le=B.querySelector("[data-dockview-tab-context-menu]");le&&le.contains(q.target)||T(null)};return $.addEventListener("mousedown",F,!0),$!==window&&window.addEventListener("mousedown",()=>T(null),!0),()=>{$.removeEventListener("mousedown",F,!0),$!==window&&window.removeEventListener("mousedown",()=>T(null),!0)}},[z]);const at=o.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:ue,hasDetachedConversationPanels:we,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:S,liveSessionInboxState:A,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:se,userName:f,scrollToBottomRequest:N,tabShortcuts:_e,openTabContextMenu:({x:B,y:$,tabKey:F,sourceDocument:q})=>T({x:B,y:$,tabKey:F,sourceDocument:q??document}),popoutTab:me,moveTabBackToMain:ne,isTabInPopout:fe,floatTab:xe,isTabFloating:ie}),[n,t,ue,we,r,c,l,S,A,a,i,se,f,N,_e,me,ne,fe,xe,ie]),dt=z?ax({isTabInPopout:fe(z.tabKey),isTabFloating:ie(z.tabKey),tabShortcut:_e[z.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()},[]),ot=o.useCallback((B,$="requested-tab")=>{if(!B)return!1;const F=w.current;if(!F)return!1;const q=F.getPanel(B);return q?(mt(q),ve(B,$),b==null||b(),!0):!1},[mt,b,ve]),ut=o.useCallback(()=>{if(C.current)return!1;const B=ot(R.current,"stored-layout-restore");return B&&(C.current=!0),B},[ot]),Ie=o.useCallback(()=>{var $;const B=w.current;B&&Fp(y,{activeTabId:(($=B.activePanel)==null?void 0:$.id)??null,layout:B.toJSON()})},[y]),$e=o.useCallback(()=>{zp(y,pe.current)},[y]),Ue=o.useCallback(B=>{var q,le,ke,Me;const $=w.current;if(!$)return{kind:"grid"};const F=$.toJSON();for(const Ce of F.floatingGroups||[])if((le=(q=Ce.data)==null?void 0:q.views)!=null&&le.includes(B)&&Ce.position)return{kind:"floating",position:Ce.position};for(const Ce of F.popoutGroups||[])if((Me=(ke=Ce.data)==null?void 0:ke.views)!=null&&Me.includes(B))return{kind:"popout",position:Ce.position,popoutUrl:Ce.url};return{kind:"grid"}},[]),Ve=o.useCallback(B=>{const $=w.current;if(!$)return;const F=$.getPanel(B),q=pe.current[B];if(!F||!q||q.kind==="grid")return;if(F.group.model.location.type===q.kind){delete pe.current[B],$e();return}if(q.kind==="floating"){$.addFloatingGroup(F,{x:q.position.left??24,y:q.position.top??24,width:q.position.width,height:q.position.height}),delete pe.current[B],$e();return}delete pe.current[B],$e()},[$e]);o.useEffect(()=>(m==null||m({setShortcutForActiveTab:Ke,restoreHiddenTabToSavedLocation:Ve,activateConversationTab:oe,resetAllPanelsToMain:X,activatePreviousTabInGroup:()=>P(-1),activateNextTabInGroup:()=>P(1),floatActiveTab:()=>{const B=ce();B&&xe(B)},popoutActiveTab:()=>{const B=ce();B&&me(B)},dockActiveTab:()=>{const B=ce();B&&(fe(B)?ne(B):ie(B)&&ae(B))},splitActiveTabRight:()=>de("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>de("below",{createGroupIfMissing:!0}),focusLeftPane:()=>U("left"),focusRightPane:()=>U("right"),focusUpPane:()=>U("above"),focusDownPane:()=>U("below"),moveActiveTabToLeftPane:()=>de("left"),moveActiveTabToRightPane:()=>de("right"),moveActiveTabToUpPane:()=>de("above"),moveActiveTabToDownPane:()=>de("below")}),()=>m==null?void 0:m(null)),[P,ae,xe,U,ce,ie,fe,de,ne,me,m,X,Ve,oe,Ke]);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 F of $)F.setAttribute("data-adhdev-force-hidden","true")},[]),Qe=o.useCallback(()=>{const B=g.current;if(!B)return;const $=B.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const F of $)F.removeAttribute("data-adhdev-force-hidden")},[]),ee=o.useCallback(()=>{const B=g.current;if(!B)return;const $=B.querySelectorAll(".dv-drop-target-container");for(const le of $)le.remove();const F=B.querySelectorAll(".dv-drop-target-dropzone");for(const le of F)le.remove();const q=B.querySelectorAll(".dv-drop-target");for(const le of q)le.classList.remove("dv-drop-target")},[]),Le=o.useCallback(()=>{Y(!1),D(!1),Qe(),qe(),ee(),!(typeof window>"u")&&(be.current!=null&&window.clearTimeout(be.current),window.requestAnimationFrame(()=>{qe(),ee()}),be.current=window.setTimeout(()=>{qe(),ee(),be.current=null},80))},[Qe,qe,ee]),De=o.useCallback(B=>{var F;w.current=B.api;const $=Hp(y);if(R.current=($==null?void 0:$.activeTabId)??null,$!=null&&$.layout&&B.api.fromJSON($.layout,{reuseExistingPanels:!1}),M.current=si({hasStoredLayout:!!($!=null&&$.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),M.current||(ai(B.api,e),oi(B.api,e,j)),B.api.totalPanels===0&&e.length>0){const q=lx(B.api,e,h);if(q){const le=B.api.getPanel(q);le&&mt(le)}}else!M.current&&!ot(h)&&ut();E.current=!0,B.api.onDidActivePanelChange(q=>{var ke;if(R.current=(q==null?void 0:q.id)??null,C.current=!0,J(),q&&Lt(q.id)){const Me=((ke=q.params)==null?void 0:ke.routeId)||q.id.slice(7),Ce=_t(e,Me);v((Ce==null?void 0:Ce.tabKey)??null),Ie();return}if(v((q==null?void 0:q.id)??null),Ie(),!q)return;const le=ue.get(q.id);(le==null?void 0:le.streamSource)==="agent-stream"&&le.agentType&&k(le.routeId,Jc(),{agentType:le.agentType,...le.sessionId&&{targetSessionId:le.sessionId}}).catch(()=>{})}),B.api.onDidLayoutChange(()=>{Ie(),J(),Q(q=>q+1)}),B.api.onWillDragPanel(()=>{Y(!0),D(!1),qe()}),B.api.onWillDragGroup(()=>{Y(!0),D(!1),qe()}),B.api.onWillShowOverlay(()=>{Qe(),D(!0)}),B.api.onDidMovePanel(Le),B.api.onDidDrop(Le),B.api.onDidAddGroup(q=>{requestAnimationFrame(()=>{var le,ke;try{const Me=(le=q.element)==null?void 0:le.ownerDocument;if(!Me||Me===document)return;(ke=Me.getElementById("dv-popout-window"))==null||ke.classList.add("adhdev-dockview");const Ce=document.documentElement.getAttribute("data-theme");Ce&&Me.documentElement.setAttribute("data-theme",Ce),Me.body.className=document.body.className;const re=document.documentElement.getAttribute("style");re&&Me.documentElement.setAttribute("style",re)}catch{}J(),Q(Me=>Me+1)})}),v(((F=B.api.activePanel)==null?void 0:F.id)??null)},[mt,ot,Le,Qe,ue,r,d,y,qe,v,Ie,h,j,k,J,e]);o.useLayoutEffect(()=>{const B=w.current;if(!B||!E.current||M.current&&si({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;M.current&&(M.current=!1);const $=K.current,F=new Set($),q=e.map(We=>We.tabKey),le=new Set(q),ke=ox({previousVisibleConversationCount:$.length,visibleConversationCount:e.length,ides:r});let Me=!1;for(const We of $)le.has(We)||ke||(pe.current[We]=Ue(We),Me=!0);Me&&$e(),ke||(ai(B,e),oi(B,e,j));const Ce=q.filter(We=>!F.has(We));let re=!1;for(const We of Ce){const Fe=B.getPanel(We),Ye=pe.current[We];if(!Fe||!Ye||Ye.kind==="grid")continue;if(Fe.group.model.location.type===Ye.kind){delete pe.current[We],re=!0;continue}if(Ye.kind==="floating"){B.addFloatingGroup(Fe,{x:Ye.position.left??24,y:Ye.position.top??24,width:Ye.position.width,height:Ye.position.height}),delete pe.current[We],re=!0;continue}}if(re&&$e(),K.current=q,h&&ot(h))return;!B.activePanel&&B.panels[0]&&mt(B.panels[0]),!!(B.activePanel&&B.getPanel(B.activePanel.id))||ut()},[mt,ot,ut,r,d,$e,Ue,h,j,e]),o.useEffect(()=>{E.current&&ot(h)},[ot,h]),o.useEffect(()=>{if(!L||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,L]),o.useEffect(()=>()=>{typeof window>"u"||be.current!=null&&window.clearTimeout(be.current)},[]),o.useEffect(()=>{const B=F=>{const q=F.target;if(!q)return;const le=q.querySelector("[data-tab-key]")||q.closest("[data-tab-key]");if(le){const ke=le.getAttribute("data-tab-key");if(ke&&F.dataTransfer){const Me=q.closest(".dv-tab")||le.closest(".dv-tab")||le;F.dataTransfer.effectAllowed="move",F.dataTransfer.setData("text/tab-key",ke),Me instanceof HTMLElement&&F.dataTransfer.setDragImage(Me,Math.max(12,Math.round(Me.clientWidth/2)),Math.max(10,Math.round(Me.clientHeight/2)))}}};window.addEventListener("dragstart",B);const $=ni(w.current);for(const F of $)F.addEventListener("dragstart",B);return()=>{window.removeEventListener("dragstart",B);for(const F of $)F.removeEventListener("dragstart",B)}},[W]),o.useEffect(()=>{var $;const B=($=g.current)==null?void 0:$.querySelector(".adhdev-dockview");B instanceof HTMLElement&&Nr(B,I),H(),J(),Z()},[J,Z,H,I]),o.useEffect(()=>{J(),Z()},[J,Z]),o.useEffect(()=>{const B=$=>{if($.defaultPrevented||ge)return;const F=et($);if(!F)return;const q=$.metaKey||$.ctrlKey||$.altKey;la($.target)&&!q||Gr(Ne).setActiveTabShortcut!==F||($.preventDefault(),$.stopPropagation(),Ke())};return window.addEventListener("keydown",B,!0),()=>window.removeEventListener("keydown",B,!0)},[et,Ne,ge,Ke]),o.useEffect(()=>{const B=g.current;if(!B)return;const $=F=>{var Ce,re;if(!F.isTrusted)return;const q=(re=(Ce=F.target)==null?void 0:Ce.closest)==null?void 0:re.call(Ce,".dv-scrollable");if(!q)return;F.preventDefault(),F.stopPropagation();const le=Math.abs(F.deltaX),ke=Math.abs(F.deltaY),Me=le>ke?F.deltaX:F.deltaY;q.dispatchEvent(new WheelEvent("wheel",{deltaY:Me,deltaMode:F.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(F=>{let q=[],le=null;const ke=()=>{le!=null&&F.clearTimeout(le),le=null,q=[]},Me=()=>{le!=null&&F.clearTimeout(le),le=F.setTimeout(()=>{le=null,q=[]},1200)},Ce=je=>{if(!je.ctrlKey&&!je.metaKey&&!je.altKey)return;const We=et(je);if(!We)return;const Fe=rl();for(const[Ye,ze]of Object.entries(Fe))if(e.some(Pe=>Pe.tabKey===Ye)&&ze===We){je.preventDefault(),oe(Ye);return}},re=je=>{if(je.defaultPrevented||ge)return;const We=et(je);if(!We)return;const Fe=je.metaKey||je.ctrlKey||je.altKey;if(la(je.target)&&!Fe)return;const Ye=Gr(Ne),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=Fe?[We]:[...q.slice(-1),We].slice(-2),_=Pe.join(" "),te=Pe[Pe.length-1],he=ze.find(([,Te])=>Te===_);if(he){je.preventDefault(),ke(),Je(he[0]);return}if(ze.some(([,Te])=>Te.startsWith(`${_} `))){je.preventDefault(),q=Pe,Me();return}const Se=ze.find(([,Te])=>Te===te);if(Se){je.preventDefault(),ke(),Je(Se[0]);return}if(ze.some(([,Te])=>Te.startsWith(`${te} `))){je.preventDefault(),q=[te],Me();return}ke()};return F.addEventListener("keydown",Ce),F.addEventListener("keydown",re),()=>{ke(),F.removeEventListener("keydown",Ce),F.removeEventListener("keydown",re)}});return()=>{for(const F of $)F()}},[et,Ne,W,oe,ge,Je,e]);const rt=I==="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(dl.Provider,{value:at,children:[s.jsx("div",{ref:g,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(ad,{className:`h-full min-h-0 min-w-0 adhdev-dockview${L?" is-dragging-dockview":""}${O?" is-showing-dockview-overlay":""}`,components:{conversation:dx,remote:ux},defaultTabComponent:fx,watermarkComponent:mx,onReady:De,singleTabMode:"default",tabAnimation:"smooth",theme:rt,popoutUrl:"/popout.html"})}),z&&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:z.x,top:z.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(Zd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{};switch(B.id){case"dockInWindow":case"dockBackToGrid":$=s.jsx(tu,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ae(z.tabKey),T(null)};break;case"moveBackToMain":$=s.jsx(Qd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ne(z.tabKey),T(null)};break;case"floatAsPanel":$=s.jsx(eu,{size:13,className:"shrink-0 opacity-70"}),F=()=>{xe(z.tabKey),T(null)};break;case"openInNewWindow":$=s.jsx(Jd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{me(z.tabKey),T(null)};break;case"setShortcut":F=q=>{q.stopPropagation(),Be(z.tabKey),T(null)};break;case"removeShortcut":$=s.jsx(vt,{size:13,className:"shrink-0 opacity-70"}),F=()=>{const q={..._e};delete q[z.tabKey],Oe(q),T(null)};break;case"hideTab":$=s.jsx(_i,{size:13,className:"shrink-0 opacity-70"}),F=()=>{se(z.tabKey),T(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:F,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)})}),z.sourceDocument.body),ge&&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. ",Ne?"⌘+1":"Ctrl+1",", ",Ne?"⌥+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 ul="adhdev-recent-launch-args-v1",hx=8;function xx(e){return String(e||"").trim().replace(/\s+/g," ")}function ml(e,t){return`${e.trim()}::${t.trim()}`}function fl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(ul)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function bx(e){if(!(typeof window>"u"))try{window.localStorage.setItem(ul,JSON.stringify(e))}catch{}}function pl(e,t){var i;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((i=fl().byKey[ml(r,n)])==null?void 0:i.items)||[]}function hl(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),i=xx(r);if(!n||!a||!i)return;const c=fl(),l=ml(n,a),d=((u=c.byKey[l])==null?void 0:u.items)||[],f=[i,...d.filter(x=>x!==i)].slice(0,hx);c.byKey[l]={items:f},bx(c)}function xl(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 bl({busy:e,savedSessionsLoading:t,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?el(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:Cf()})]}),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 gx({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:c,onListSavedSessions:l}){var qe,Qe;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(ee=>ee.id===u)||f[0],[u,f]),v=o.useMemo(()=>((m==null?void 0:m.workspaces)||[]).map(ee=>({id:ee.id,path:ee.path,label:ee.label})),[m]),S=(m==null?void 0:m.defaultWorkspaceId)||null,[p,h]=o.useState(""),[j,b]=o.useState(""),[N,A]=o.useState(Rn(f[0])),[y,I]=o.useState(""),[k,w]=o.useState(""),[g,E]=o.useState([]),[M,C]=o.useState(""),[R,K]=o.useState([]),[z,T]=o.useState(!1),[L,Y]=o.useState(!1),[O,D]=o.useState(""),[W,Q]=o.useState(!1),[be,pe]=o.useState(()=>ht()),[ue,we]=o.useState(null),[ye,ve]=o.useState(!1),[V,H]=o.useState(""),[Z,me]=o.useState(!1),[ne,fe]=o.useState(""),[se,xe]=o.useState([]),[ie,ce]=o.useState(!1),[ae,X]=o.useState(""),[J,oe]=o.useState(!1),P=o.useRef(null),G=o.useRef(0);o.useEffect(()=>{var ee;!u&&((ee=f[0])!=null&&ee.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 U=o.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(ee=>ee.category==="cli"&&ee.installed!==!1),[m]),de=o.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(ee=>ee.category==="acp"&&ee.installed!==!1),[m]),Ne=o.useMemo(()=>((m==null?void 0:m.detectedIdes)||[]).map(ee=>({id:ee.type,label:ee.name||ee.type,meta:ee.running?"Detected locally":"Available to open"})),[m]),_e=o.useMemo(()=>N==="cli"?U.map(ee=>({id:ee.type,label:ee.displayName||ee.type,meta:"CLI provider"})):N==="acp"?de.map(ee=>({id:ee.type,label:ee.displayName||ee.type,meta:"ACP provider"})):Ne,[de,N,U,Ne]);o.useEffect(()=>{var Le;if(!m)return;if(P.current!==m.id){P.current=m.id,h(S||((Le=v[0])==null?void 0:Le.id)||"__home__"),b(""),A(Rn(m)),I(""),w(""),C(""),K([]),Y(!1),D(""),pe(ht()),H("");return}h(De=>{var rt;return De==="__custom__"||De==="__home__"||v.some(Ct=>Ct.id===De)?De:S||((rt=v[0])==null?void 0:rt.id)||"__home__"}),A(De=>De==="ide"&&Ne.length>0||De==="cli"&&U.length>0||De==="acp"&&de.length>0?De:Rn(m))},[de.length,U.length,S,Ne.length,m,v]),o.useEffect(()=>{var ee;N&&(_e.some(Le=>Le.id===y)||I(((ee=_e[0])==null?void 0:ee.id)||""))},[N,_e,y]);const ge=o.useCallback(async(ee,Le)=>{const De=G.current+1;return G.current=De,T(!0),D(""),l(ee,Le).then(rt=>{G.current===De&&K(rt)}).catch(rt=>{G.current===De&&(K([]),D(rt instanceof Error?rt.message:"Could not load saved sessions"))}).finally(()=>{G.current===De&&(T(!1),Y(!0))})},[l]),Be=o.useCallback((ee,Le)=>{E(pl(ee,Le))},[]);o.useEffect(()=>{G.current+=1,C(""),pe(ht()),!m||!y||N==="ide"?E([]):Be(m.id,y),Y(!1),K([]),D(""),T(!1)},[N,Be,ge,m,y]),o.useEffect(()=>{if(!M)return;const ee=R.find(Le=>Le.providerSessionId===M);ee!=null&&ee.canResume||C("")},[R,M]);const Oe=p==="__custom__"?j.trim():p==="__home__"?"":((Qe=v.find(ee=>ee.id===p))==null?void 0:Qe.path)||"",Ke=o.useMemo(()=>m?t.filter(ee=>ee.id!==m.id&&ee.daemonId===m.id).map(ee=>ee.workspace):[],[t,m]),et=o.useMemo(()=>((m==null?void 0:m.recentLaunches)||[]).map(ee=>ee.workspace),[m]),Je=o.useCallback(ee=>{const Le=String(ee.workspace||"").trim();if(!Le)return;const De=v.find(rt=>Cr(rt.path)===Cr(Le));if(De){h(De.id),b("");return}h("__custom__"),b(Le)},[v]),at=o.useCallback(ee=>{const Le=String(ee.workspace||"").trim();if(!Le)return{workspaceId:null,workspacePath:null};const De=v.find(rt=>Cr(rt.path)===Cr(Le));return De?{workspaceId:De.id,workspacePath:null}:{workspaceId:null,workspacePath:Le}},[v]),dt=o.useMemo(()=>R.find(ee=>ee.providerSessionId===M)||null,[R,M]),mt=o.useMemo(()=>{var Le;if(N!=="cli"||!m||!y)return null;const ee=((Le=U.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:ee,agentType:y,status:"idle",title:ee,messages:[],ideType:y,workspaceName:Oe,displayPrimary:ee,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${m.id}:${y}`,machineName:At(m,{fallbackId:m.id})}},[N,U,Oe,m,M,y]),ot=o.useCallback(()=>{var Le;if(!m)return;h("__custom__"),me(!0),X("");const ee=sn(m.platform,tn(j.trim(),Oe,Ke,et,m.defaultWorkspacePath,(Le=v.find(De=>De.id===S))==null?void 0:Le.path,v.map(De=>De.path)));ce(!0),n(m.id,ee).then(De=>{fe(De.path),b(De.path),xe(De.directories)}).catch(De=>{X(De instanceof Error?De.message:"Could not load folder")}).finally(()=>ce(!1))},[j,S,et,Ke,n,Oe,m,v]),ut=o.useCallback(ee=>{m&&(ce(!0),X(""),n(m.id,ee).then(Le=>{fe(Le.path),b(Le.path),xe(Le.directories)}).catch(Le=>{X(Le instanceof Error?Le.message:"Could not load folder")}).finally(()=>ce(!1)))},[n,m]),Ie=o.useCallback(async()=>{if(!m||!Oe)return;oe(!0),H("");const ee=await a(m.id,Oe);if(oe(!1),!ee.ok){H(ee.error||"Could not save workspace");return}H("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,Oe,m]),$e=o.useCallback(async()=>{if(!m||!N||!y)return;ve(!0),H("");const ee=k.trim()?k.trim().split(/\s+/).filter(Boolean):[],Le=N==="ide"?await i(m.id,y,{workspacePath:Oe||null}):await c(m.id,N,y,{workspaceId:p!=="__home__"&&p!=="__custom__"?p:null,workspacePath:p==="__custom__"&&Oe||null,resumeSessionId:N==="cli"&&M?M:null,cliArgs:ee});if(ve(!1),!Le.ok){H(Le.error||"Could not start session");return}N!=="ide"&&k.trim()&&(hl(m.id,y,k),Be(m.id,y)),r()},[N,k,Be,r,i,c,Oe,m,M,y,p]),Ue=N?jc(N,N==="cli"&&!!M):"Start",Ve=N?kc(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(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:ee=>x(ee.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:ye,children:f.map(ee=>s.jsx("option",{value:ee.id,children:At(ee,{fallbackId:ee.id})},ee.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:ot,disabled:ye,children:"Browse…"}),children:[s.jsxs("select",{value:p,onChange:ee=>{const Le=ee.target.value;h(Le),Le==="__custom__"?ot():H("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ye,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),v.map(ee=>s.jsxs("option",{value:ee.id,children:[ee.id===S?"⭐ ":"",Zr(ee.path,ee.label)||ee.path]},ee.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.":Oe||"Select a workspace folder."}),p==="__custom__"&&Oe&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ot,disabled:ye,children:[s.jsx(Ns,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ie,disabled:ye||J,children:J?"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:U.length>0},{id:"ide",label:"IDE",enabled:Ne.length>0},{id:"acp",label:"ACP",enabled:de.length>0}].map(ee=>s.jsx("button",{type:"button",className:`btn btn-sm ${N===ee.id?"btn-primary":"btn-secondary"}`,onClick:()=>A(ee.id),disabled:!ee.enabled||ye,children:ee.label},ee.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(ee=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${y===ee.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>I(ee.id),disabled:ye,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ee.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ee.meta})]},ee.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:ee=>w(ee.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:ye}),g.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:g.map(ee=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>w(ee),disabled:ye,title:ee,children:ee},ee))})]}),N==="cli"&&s.jsx(bl,{busy:ye,savedSessionsLoading:z,savedSessionsError:O,selectedSession:dt,onRefresh:()=>{!m||!y||ge(m.id,y)},onOpenHistory:()=>{!m||!y||(Q(!0),xl({hasLoadedInitialResults:L,isLoading:z})&&ge(m.id,y))},onClearSelection:()=>C("")}),V&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${V.includes("saved")||V.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:V})]}),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:ye,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:ye||!N||!y||p==="__custom__"&&!Oe,children:[s.jsx(ya,{size:14}),ye?Ve:Ue]})]})]})}),Z&&s.jsx(an,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:ne,directories:se,busy:ie,error:ae,onClose:()=>me(!1),onNavigate:ut,onConfirm:ee=>{b(ee),fe(ee),h("__custom__"),me(!1)}}),W&&mt&&s.jsx($a,{activeConv:mt,ides:[],isCreatingChat:!1,isRefreshingHistory:z,savedSessions:R,isSavedSessionsLoading:z,isResumingSavedSessionId:ue,savedHistoryFilters:be,onSavedHistoryFiltersChange:pe,onClose:()=>Q(!1),onNewChat:()=>{C(""),Q(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!m||!y||ge(m.id,y)},onResumeSavedSession:ee=>{if(!m||!y||ue||!ee.canResume)return;const Le=at(ee);C(ee.providerSessionId),Je(ee),we(ee.providerSessionId),Q(!1),ve(!0),H(""),c(m.id,"cli",y,{workspaceId:Le.workspaceId,workspacePath:Le.workspacePath,resumeSessionId:ee.providerSessionId}).then(De=>{if(!De.ok){H(De.error||"Could not resume session");return}r()}).finally(()=>{ve(!1),we(De=>De===ee.providerSessionId?null:De)})}})]}):null}function yx({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)},[]),A=o.useCallback(()=>{S(r===0?"quickstart":"shortcuts"),h("workspace"),d(!0),a(!1),c(!1)},[r]),y=o.useCallback(()=>{d(!1)},[]),I=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:A,closeShortcutHelp:y,openNewSession:I,closeNewSession:k}}function vx(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 wx(e){return e instanceof Error?e.message:String(e||"")}function jx(e){const t=wx(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function kx({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:A,onRequestedMobileTabConsumed:y,requestedMachineId:I,onRequestedMachineConsumed:k,requestedMobileSection:w,onRequestedMobileSectionConsumed:g,containerRef:E,isSplitMode:M,numGroups:C,groupSizes:R,groupedConvs:K,clearedTabs:z,focusedGroup:T,focusGroup:L,moveTabToGroup:Y,splitTabRelative:O,closeGroup:D,handleResizeStart:W,groupActiveTabIds:Q,setGroupActiveTab:be,groupTabOrders:pe,setGroupTabOrder:ue,toggleHiddenTab:we,visibleConversations:ye,requestedDesktopTabKey:ve,onRequestedDesktopTabConsumed:V,onDesktopActiveTabChange:H,onRequestScrollToBottom:Z,onHideConversation:me,onShowHiddenConversation:ne,onShowAllHiddenConversations:fe,scrollToBottomRequest:se,machineEntries:xe,layoutProfile:ie,onBrowseMachineDirectory:ce,onSaveMachineWorkspace:ae,onLaunchMachineIde:X,onLaunchMachineProvider:J,onListMachineSavedSessions:oe,notifications:P,notificationUnreadCount:G,liveSessionInboxState:U,onMarkNotificationRead:de,onMarkNotificationUnread:Ne,onDeleteNotification:_e}){const ge=kt.useRef(null),{inboxOpen:Be,hiddenOpen:Oe,shortcutHelpOpen:Ke,newSessionOpen:et,guideNudgeVisible:Je,guideTab:at,shortcutSection:dt,isDesktopDashboard:mt,setGuideTab:ot,setShortcutSection:ut,handleInboxOpenChange:Ie,handleHiddenOpenChange:$e,handleOpenShortcutHelp:Ue,closeShortcutHelp:Ve,openNewSession:qe,closeNewSession:Qe}=yx({isMobile:t,showMobileChatMode:e,visibleConversationCount:ye.length}),ee=kt.useCallback(re=>{var je;qs.flushSync(()=>{ne(re)}),(je=ge.current)==null||je.restoreHiddenTabToSavedLocation(re.tabKey)},[ne]),Le=kt.useCallback(re=>{var We;const je=u.find(Fe=>Zn(Fe,re))||x.find(Fe=>Zn(Fe,re));je&&(x.some(Fe=>Fe.tabKey===je.tabKey)&&ee(je),H(je.tabKey),(We=ge.current)==null||We.activateConversationTab(je.tabKey),Z(je.tabKey,"notification-open")),de(re.id),Ie(!1)},[ee,x,u,H,de,Z]),De=kt.useCallback(()=>{var je;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((je=ge.current)==null||je.resetAllPanelsToMain(),$e(!1))},[$e]),rt=kt.useCallback(async re=>{var ze;if(!r)return;const je=(ze=r.modalButtons)==null?void 0:ze[re];if(!je)return;const We=Zs(r);if(!We)return;const Fe=je.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Ye=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Fe);try{await S(We,"resolve_action",{button:je,action:Ye?"approve":"reject",buttonIndex:re,...js(r)})}catch(Pe){jx(Pe)||console.error("[Shortcut approval] Failed:",Pe)}},[r,S]),{isMac:Ct,actionDefinitions:ft,actionShortcuts:Tt,shortcutListening:yt,shortcutListeningDraft:B,setShortcutListening:$,setShortcutListeningDraft:F,saveShortcuts:q}=nx({enabled:mt&&!Ke,onTrigger:re=>{var je,We,Fe,Ye,ze,Pe,_,te,he,Re,Se,Ae,Te,pt,ct,Ot;if(re==="openShortcutHelp"){Ue();return}if(re==="hideCurrentTab"){r&&me(r);return}if(re==="toggleHiddenTabs"){$e(!Oe);return}if(re==="openHistoryForActiveTab"){r&&!Xe(r)&&i(r);return}if(re==="openRemoteForActiveTab"){r&&!Ze(r)&&!Xe(r)&&c(r);return}if(re==="splitActiveTabRight"){(je=ge.current)==null||je.splitActiveTabRight();return}if(re==="splitActiveTabDown"){(We=ge.current)==null||We.splitActiveTabDown();return}if(re==="floatActiveTab"){(Fe=ge.current)==null||Fe.floatActiveTab();return}if(re==="popoutActiveTab"){(Ye=ge.current)==null||Ye.popoutActiveTab();return}if(re==="dockActiveTab"){(ze=ge.current)==null||ze.dockActiveTab();return}if(re==="focusLeftPane"){(Pe=ge.current)==null||Pe.focusLeftPane();return}if(re==="focusRightPane"){(_=ge.current)==null||_.focusRightPane();return}if(re==="focusUpPane"){(te=ge.current)==null||te.focusUpPane();return}if(re==="focusDownPane"){(he=ge.current)==null||he.focusDownPane();return}if(re==="moveActiveTabToLeftPane"){(Re=ge.current)==null||Re.moveActiveTabToLeftPane();return}if(re==="moveActiveTabToRightPane"){(Se=ge.current)==null||Se.moveActiveTabToRightPane();return}if(re==="moveActiveTabToUpPane"){(Ae=ge.current)==null||Ae.moveActiveTabToUpPane();return}if(re==="moveActiveTabToDownPane"){(Te=ge.current)==null||Te.moveActiveTabToDownPane();return}if(re==="triggerPrimaryApprovalAction"){rt(0);return}if(re==="triggerSecondaryApprovalAction"){rt(1);return}if(re==="triggerTertiaryApprovalAction"){rt(2);return}if(re==="setActiveTabShortcut"){(pt=ge.current)==null||pt.setShortcutForActiveTab();return}if(re==="selectPreviousGroupTab"){(ct=ge.current)==null||ct.activatePreviousTabInGroup();return}if(re==="selectNextGroupTab"){(Ot=ge.current)==null||Ot.activateNextTabInGroup();return}!r||!Ze(r)||Xe(r)||re==="toggleCliView"&&f(d==="chat"?"terminal":"chat")}}),le=kt.useCallback(()=>{Ve(),$(null),F([])},[Ve,$,F]),ke=kt.useMemo(()=>dt==="all"?ft:ft.filter(re=>vx(re)===dt),[ft,dt]),Me=kt.useCallback(()=>{const re=Object.fromEntries(ft.map(je=>[je.id,""]));q(re)},[ft,q]),Ce=kt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const re=Object.fromEntries(ft.map(je=>[je.id,je.defaultShortcut]));q(re)},[ft,q]);return kt.useEffect(()=>{const re=je=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?je.metaKey&&je.key.toLowerCase()==="w":je.ctrlKey&&je.key.toLowerCase()==="w")&&(je.preventDefault(),r&&me&&me(r))};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[r,me]),kt.useEffect(()=>{if(!Ke||yt)return;const re=je=>{je.key==="Escape"&&(je.preventDefault(),le())};return window.addEventListener("keydown",re,!0),()=>window.removeEventListener("keydown",re,!0)},[le,Ke,yt]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(vf,{activeConv:r,wsStatus:n,isConnected:a,conversations:ye,hiddenConversations:x,onOpenHistory:i,onHideConversation:me,onShowConversation:ee,onShowAllHidden:fe,onResetPanelsToMain:De,notifications:P,notificationUnreadCount:G,onOpenNotification:Le,onMarkNotificationRead:de,onMarkNotificationUnread:Ne,onDeleteNotification:_e,inboxOpen:Be,onInboxOpenChange:Ie,hiddenOpen:Oe,onHiddenOpenChange:$e,onOpenNewSession:t?void 0:qe,actionShortcuts:Tt,onOpenRemote:()=>{!r||Ze(r)||Xe(r)||c(r)},onStopCli:l,activeCliViewMode:d,onSetCliViewMode:f}),e?s.jsx(Vh,{conversations:u,hiddenConversations:x,ides:m,actionLogs:v,sendDaemonCommand:S,setActionLogs:p,setCliViewModeOverrides:h,isStandalone:j,userName:N,requestedActiveTabKey:A,onRequestedActiveTabConsumed:y,requestedMachineId:I,onRequestedMachineConsumed:k,requestedMobileSection:w,onRequestedMobileSectionConsumed:g,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowHiddenConversation:ee,onShowAllHiddenConversations:fe,onOpenNewSession:qe,liveSessionInboxState:U}):t?s.jsx(ex,{containerRef:E,isSplitMode:M,numGroups:C,groupSizes:R,groupedConvs:K,clearedTabs:z,ides:m,actionLogs:v,sendDaemonCommand:S,setActionLogs:p,isStandalone:j,hasRegisteredMachines:xe.length>0,userName:N,focusedGroup:T,focusGroup:L,moveTabToGroup:Y,splitTabRelative:O,closeGroup:D,handleResizeStart:W,groupActiveTabIds:Q,setGroupActiveTab:be,groupTabOrders:pe,setGroupTabOrder:ue,toggleHiddenTab:we,onOpenNewSession:qe,allowTabShortcuts:!1,liveSessionInboxState:U}):s.jsx(px,{visibleConversations:ye,clearedTabs:z,ides:m,actionLogs:v,sendDaemonCommand:S,setActionLogs:p,isStandalone:j,hasRegisteredMachines:xe.length>0,initialDataLoaded:b,userName:N,toggleHiddenTab:we,actionShortcuts:Tt,registerActionHandlers:re=>{ge.current=re},onActiveTabChange:H,requestedActiveTabKey:ve,onRequestedActiveTabConsumed:V,onRequestScrollToBottom:Z,scrollToBottomRequest:se,onOpenNewSession:qe,liveSessionInboxState:U,layoutProfile:ie}),et&&s.jsx(gx,{machines:xe,ides:m,onClose:Qe,onBrowseDirectory:ce,onSaveWorkspace:ae,onLaunchIde:X,onLaunchProvider:J,onListSavedSessions:oe}),Ke&&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:le,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:re=>re.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:le,"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(re=>s.jsx("button",{type:"button",className:`btn btn-sm ${at===re.id?"btn-primary":"btn-secondary"}`,onClick:()=>ot(re.id),children:re.label},re.id))}),at==="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."]})]})]})]}),at==="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."]})]})]})]}),at==="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(re=>s.jsx("button",{type:"button",className:`btn btn-sm ${dt===re.id?"btn-primary":"btn-secondary"}`,onClick:()=>ut(re.id),children:re.label},re.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Me,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:ke.map(re=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${yt===re.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:re.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:re.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:re.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===re.id?B.length>0?`${B.join(" ")} ...`:"Listening...":Tt[re.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{$(re.id),F([])},children:yt===re.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const je={...Tt};je[re.id]="",q(je)},children:"Disable"})]})]})},re.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 ${Je?"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:"?"}),Je&&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 Sx({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
+ @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
55
+ @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
56
+ `})]})}function Nx({hasExtensions:e,ideName: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 Cx({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,c]=o.useState(()=>a||"native"),l=o.useMemo(()=>Nc(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:gc(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 Ix({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(L=>L.id===e.routeId),[e.routeId,t,r]),b=o.useMemo(()=>st((j==null?void 0:j.type)||""),[j==null?void 0:j.type]),{conversations:N,extensionTabs:A,hasExtensions:y}=Cx({ideData:j,allIdes:r,connectionStates:n,ideName:b||"IDE",preferredTabKey:Vt(e)?void 0:e.tabKey}),I=o.useMemo(()=>j?_t(N,j.id):null,[j,N]);o.useEffect(()=>{const L=h.current,Y={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(h.current=Y,!(L&&L.routeId===Y.routeId&&L.tabKey===Y.tabKey&&L.streamSource===Y.streamSource)){if(Vt(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(S==="native"){if(N.some(L=>L.streamSource==="native"))return;(I==null?void 0:I.streamSource)==="agent-stream"&&p(I.tabKey);return}if(!N.some(L=>L.tabKey===S)){if((I==null?void 0:I.streamSource)==="agent-stream"){p(I.tabKey);return}p("native")}},[N,S,I]);const k=o.useMemo(()=>S==="native"?N.find(L=>L.streamSource==="native")||e:N.find(L=>L.tabKey===S)||e,[e,N,S]),w=Kc(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]),E=Rs(g),M=nn({sendDaemonCommand:i,activeConv:g,setActionLogs:c,isStandalone:l}),{connScreenshot:C,screenshotUsage:R,handleRemoteAction:K}=al({doId:E,targetSessionId:nc(g),connState:g.connectionState||"new",viewMode:m}),z=o.useMemo(()=>a.filter(L=>L.routeId===g.tabKey),[a,g.tabKey]);o.useEffect(()=>{u==null||u(g)},[g,u]),o.useEffect(()=>{const L=Y=>{Y.key==="Escape"&&x()};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[x]);const T=o.useCallback(L=>{L.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick: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:T,children:[s.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(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(L=>{const Y=m===L;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${Y?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>v(L),title:L==="split"?"Split view":"Remote only",children:L==="split"?s.jsx(Kd,{size:15}):s.jsx(Nt,{size:15})},L)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>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(Nx,{hasExtensions:y,ideName:b||"IDE",activeChatTab:S,extensionTabs:A,onSelectTab:p}),s.jsx(Fi,{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:z,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(Wi,{addLog:()=>{},connState:g.connectionState||"new",connScreenshot:C,screenshotUsage:R,transportType:g.transport,onAction:K})})]})]})})}function Mx({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=ff(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 Ax({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(bf,{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(Ix,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),r.open&&r.targetConv&&(Ze(r.targetConv)||Xe(r.targetConv))&&s.jsx(Mx,{activeConv:r.targetConv,canSaveAndStop:Ze(r.targetConv)&&!Xe(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(Sc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&s.jsx(Sx,{onClose:i.onClose})]})}function Tx({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 Lx(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Rx(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 Px(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 _x(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 Dx(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>_x(t)).map(t=>t.id)}}function Ex(){var eo,to,so,ro;const{sendCommand:e}=wt(),t=ar(),r=Bc(),n=pa(),a=As(),[i,c]=od(),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=pc(),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",A=x.isConnected??!0,y=x.connectionStates||{},I=x.showReconnected||!1,{layoutProfile:k,groupAssignments:w,updateGroupAssignments:g,focusedGroup:E,updateFocusedGroup:M,focusGroup:C,groupActiveTabIds:R,updateGroupActiveTabIds:K,setGroupActiveTab:z,groupTabOrders:T,updateGroupTabOrders:L,setGroupTabOrder:Y,groupSizes:O,updateGroupSizes:D,isMobile:W,hasHydratedStoredLayout:Q,hydrateStoredLayout:be,focusConversationTab:pe}=qp(),[ue,we]=o.useState(()=>Ha());o.useEffect(()=>mp(we),[]);const ye=o.useMemo(()=>Lx({isMobile:W,mobileViewMode:ue}),[W,ue]),[ve,V]=o.useState([]),[H,Z]=o.useState({}),[me,ne]=o.useState({});rr("Dashboard",{ideCount:m.length,toastCount:b.length,focusedGroup:E,groupCount:Object.keys(w).length,actionLogCount:ve.length});const fe=o.useMemo(()=>m.filter(He=>He.type==="adhdev-daemon").sort(wa),[m]),se=fe[0],xe=!!se;o.useEffect(()=>{const{metadataDaemonIds:He,runtimeDaemonIds:jt}=Dx(fe);for(const Dt of He)t(Dt,{minFreshMs:3e4}).catch(()=>{});for(const Dt of jt)r(Dt,{minFreshMs:3e4}).catch(()=>{})},[t,r,fe]);const ie=(se==null?void 0:se.terminalBackend)||null,ce=se?At(se,{fallbackId:se.id}):null,ae=(se==null?void 0:se.id)||null,X=o.useMemo(()=>kp(m,H),[m,H]),{hiddenTabs:J,hideTarget:oe,toggleTarget:P,showTarget:G,showAllTabs:U}=jp(),{conversations:de,visibleConversations:Ne,visibleTabKeys:_e,resolveConversationBySessionId:ge,resolveConversationByTarget:Be}=Pp({ides:X,connectionStates:y,clearedTabs:me,hiddenTabs:J}),Oe=o.useMemo(()=>new Map(de.map(He=>[He.tabKey,He])),[de]),Ke=Ym(Ne,ye),et=o.useMemo(()=>Po(de,Ke),[de,Ke]),Je=o.useMemo(()=>Po(Ne,Ke),[Ne,Ke]);o.useEffect(()=>{Object.keys(H).length!==0&&Z(He=>Sp(He,m))},[m,H]);const at=o.useMemo(()=>wu(m),[m]),{notifications:dt,unreadCount:mt}=lh({conversations:et,liveSessionInboxState:at}),{handleMarkDashboardNotificationRead:ot,handleMarkDashboardNotificationUnread:ut,handleDeleteDashboardNotification:Ie}=dh({notifications:dt,sendDaemonCommand:e}),$e=o.useRef(null),Ue=o.useRef(null),Ve=o.useRef(null),qe=o.useRef(null),Qe=o.useRef(null),{containerRef:ee,normalizedGroupAssignments:Le,numGroups:De,isSplitMode:rt,groupedConvs:Ct,moveTabToGroup:ft,closeGroup:Tt,handleResizeStart:yt,splitTabRelative:B}=th({groupAssignments:w,updateGroupAssignments:g,updateFocusedGroup:M,updateGroupActiveTabIds:K,updateGroupTabOrders:L,groupSizes:O,updateGroupSizes:D,isMobile:W,visibleConversations:Je,visibleTabKeys:_e}),{activeConv:$,openDesktopConversation:F,requestScrollToBottom:q,scrollToBottomRequest:le,setDesktopActiveTab:ke}=vh({isMobile:W,conversations:et,visibleConversations:Je,groupActiveTabIds:R,focusedGroup:E,groupedConvs:Ct,setSearchParams:c});o.useEffect(()=>{const He=()=>{Ve.current&&(clearTimeout(Ve.current),Ve.current=null),qe.current&&(clearTimeout(qe.current),qe.current=null),Qe.current&&(document.removeEventListener("visibilitychange",Qe.current),Qe.current=null),Ue.current=null};if(W){He(),$e.current=null;return}if(!($!=null&&$.sessionId)){He(),$e.current=null;return}const jt=Or($,at),Dt=Px({tabKey:$.tabKey,historySessionId:nr($)||"",lastMessageHash:$.lastMessageHash||"",lastMessageAt:Number($.lastMessageAt||0),timestamp:es($),liveState:jt}),cr=Dt.autoReadKey,lr=Rx({autoReadKey:cr,shouldMarkSeen:Dt.shouldMarkSeen,completedKey:$e.current,pendingKey:Ue.current});if(!Dt.shouldMarkSeen){lr.shouldCancelPending&&He(),$e.current=cr;return}if(!lr.shouldSchedule)return;lr.shouldCancelPending&&He();const no=()=>{if(document.visibilityState!=="visible"||$e.current===cr)return;$e.current=cr,Ue.current=null,Ve.current=null,qe.current=null,Qe.current&&(document.removeEventListener("visibilitychange",Qe.current),Qe.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)};Qe.current=dr,document.addEventListener("visibilitychange",dr);return}const ao=()=>{document.visibilityState==="visible"&&(qe.current&&clearTimeout(qe.current),qe.current=setTimeout(no,800),Qe.current&&(document.removeEventListener("visibilitychange",Qe.current),Qe.current=null))};Qe.current=ao,document.addEventListener("visibilitychange",ao)},[$,W,at,e]),o.useEffect(()=>()=>{Ve.current&&clearTimeout(Ve.current),qe.current&&clearTimeout(qe.current),Qe.current&&document.removeEventListener("visibilitychange",Qe.current)},[]);const{requestedDesktopTabKey:Me,requestedMobileTabKey:Ce,consumeRequestedActiveTab:re}=_p({isMobile:W,urlActiveTab:l,resolveConversationBySessionId:ge,setSearchParams:c}),{remoteDialogConv:je,remoteDialogIdeEntry:We,remoteDialogActiveConv:Fe,setRemoteDialogActiveConv:Ye,openRemoteDialog:ze,closeRemoteDialog:Pe,cliStopDialogOpen:_,cliStopTargetConv:te,requestCliStop:he,cancelCliStop:Re,confirmCliStop:Se}=kh({isMobile:W,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:Me,conversations:de,ides:m,resolveConversationByTarget:Be,activeConv:$,sendDaemonCommand:e}),{historyModalOpen:Ae,openHistoryModal:Te,closeHistoryModal:pt,historyTargetConv:ct,isSavedSessionHistoryTarget:Ot,isHistoryCreatingChat:Sl,isHistoryRefreshingHistory:Nl,handleHistorySwitchSession:Cl,handleHistoryNewChat:Il,handleHistoryRefresh:Ml,savedHistorySessions:Al,savedHistoryFilters:Tl,setSavedHistoryFilters:Ll,isSavedHistoryLoading:Rl,resumingSavedHistorySessionId:Pl,handleRefreshSavedHistory:_l,handleResumeSavedHistorySession:Dl}=wh({activeConv:$,remoteDialogConv:je,remoteDialogActiveConv:Fe,ides:m,sendDaemonCommand:e,updateRouteChats:S,setToasts:p,setClearedTabs:ne,setSearchParams:c}),El=o.useMemo(()=>Je,[Je]),ir=W&&ue==="chat",$l=o.useMemo(()=>et.filter(He=>Fa(J,He)),[et,J]),Ja=o.useCallback(He=>{const jt=new URLSearchParams(i);jt.set("activeTab",He),c(jt,{replace:!0})},[i,c]),{trackPendingLaunch:Bl}=xh({ides:m,conversations:de,onOpenSession:Ja}),{handleBrowseMachineDirectory:Kl,handleSaveMachineWorkspace:Ol,handleLaunchMachineIde:Wl,handleLaunchMachineProvider:Hl,handleListMachineSavedSessions:Fl,setActiveCliViewMode:Ul}=bh({sendDaemonCommand:e,trackPendingLaunch:Bl,onOpenSession:Ja,activeConv:$,ides:m,setCliViewModeOverrides:Z});Np({visibleConversations:Ne,clearedTabs:me,setClearedTabs:ne,setActionLogs:V}),Dp({ides:m,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Be});const{isRefreshingHistory:zl,handleRefreshHistory:Vl}=Yc({sendDaemonCommand:e,activeConv:$,chats:(ro=m.find(He=>He.id===($==null?void 0:$.routeId)))==null?void 0:ro.chats,updateRouteChats:S,setToasts:p,setClearedTabs:ne});Xp({urlActiveTab:W&&!ir?l:null,conversations:de,resolveConversationBySessionId:ge,normalizedGroupAssignments:Le,hasHydratedStoredLayout:W&&!ir?Q:!0,hydrateStoredLayout:W&&!ir?be:()=>{},focusConversationTab:pe,setSearchParams:c,historyModalOpen:Ae,activeConv:$,isRefreshingHistory:zl,ides:m,handleRefreshHistory:Vl});const Gl=o.useMemo(()=>!$||!Ze($)||Xe($)?null:Ls($),[$]),{versionMismatchDaemons:ql,hasRequiredVersionDaemons:Qa,appVersion:Yl,versionBannerDismissed:Xl,setVersionBannerDismissed:Jl,upgradingDaemons:Ql,handleBannerUpgrade:Zl}=sh({ides:m,sendDaemonCommand:e}),Za=o.useCallback(He=>{G(He),F(He)},[F,G]),ed=o.useCallback(He=>{oe(He)},[oe]);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(gf,{terminalBackend:ie,isStandalone:xe,machineLabel:ce,machineKey:ae}),(!Xl||Qa)&&s.jsx(Tx,{daemons:ql,targetVersion:Yl,required:Qa,upgradingDaemons:Ql,onUpgrade:Zl,onDismiss:()=>Jl(!0)}),s.jsx(kx,{showMobileChatMode:ir,isMobile:W,activeConv:$,wsStatus:N,isConnected:A,onOpenHistory:He=>{He&&Ye(He),Te()},onOpenRemote:ze,onStopCli:he,activeCliViewMode:Gl,onSetActiveCliViewMode:Ul,mobileChatConversations:El,ides:m,actionLogs:ve,sendDaemonCommand:e,setActionLogs:V,setCliViewModeOverrides:Z,isStandalone:xe,initialDataLoaded:v,userName:x.userName,requestedMobileTabKey:Ce,onRequestedMobileTabConsumed:re,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:ee,isSplitMode:rt,numGroups:De,groupSizes:O,groupedConvs:Ct,clearedTabs:me,focusedGroup:E,focusGroup:C,moveTabToGroup:ft,splitTabRelative:B,closeGroup:Tt,handleResizeStart:yt,groupActiveTabIds:R,setGroupActiveTab:z,groupTabOrders:T,setGroupTabOrder:Y,toggleHiddenTab:He=>P(Oe.get(He)||{tabKey:He}),visibleConversations:Je,hiddenConversations:$l,requestedDesktopTabKey:Me,onRequestedDesktopTabConsumed:re,onDesktopActiveTabChange:ke,onRequestScrollToBottom:q,onHideConversation:ed,onShowHiddenConversation:Za,onShowAllHiddenConversations:U,scrollToBottomRequest:le,machineEntries:fe,layoutProfile:k,onBrowseMachineDirectory:Kl,onSaveMachineWorkspace:Ol,onLaunchMachineIde:Wl,onLaunchMachineProvider:Hl,onListMachineSavedSessions:Fl,notifications:dt,notificationUnreadCount:mt,liveSessionInboxState:at,onMarkNotificationRead:ot,onMarkNotificationUnread:ut,onDeleteNotification:Ie}),s.jsx("style",{children:`
57
+ body { overflow: hidden; overscroll-behavior: none; }
58
+ `}),s.jsx(Ax,{historyModal:{open:Ae,targetConv:ct,ides:m,isCreatingChat:Sl,isRefreshingHistory:Ot?!1:Nl,savedSessions:Al,savedHistoryFilters:Tl,onSavedHistoryFiltersChange:Ll,isSavedSessionsLoading:Rl,isResumingSavedSessionId:Pl,onClose:pt,onNewChat:Il,onSwitchSession:Cl,onRefreshHistory:Ot?_l:Ml,onResumeSavedSession:Dl},remoteDialog:{conversation:je,ideEntry:We,ides:m,connectionStates:y,actionLogs:ve,sendDaemonCommand:e,setActionLogs:V,isStandalone:xe,userName:x.userName,onOpenHistory:He=>{He&&Ye(He),Te()},onConversationChange:Ye,onClose:Pe},cliStopDialog:{open:_,targetConv:te,onCancel:Re,onStopNow:async()=>{await Se("hard")},onSaveAndStop:async()=>{await Se("save")}},connectionBanner:{wsStatus:N,showReconnected:I,loginUrl:x.connectionLoginUrl,onReconnect:x.retryServerConnection},toastOverlay:{toasts:b,onDismiss:He=>p(jt=>jt.filter(Dt=>Dt.id!==He)),onClick:He=>{if(He.targetKey){const jt=Be(He.targetKey);jt&&(pe(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 $x({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),A=o.useCallback(O=>{N.current=O},[]),y=o.useCallback((O,D,W=!1)=>{c(Q=>[...Q.slice(-100),{timestamp:Date.now(),level:O,message:D}]),setTimeout(()=>{var Q;return(Q=a.current)==null?void 0:Q.scrollIntoView({behavior:"smooth"})},100),W&&lt.showToast(D,O==="error"||O==="warn"?"warning":"success")},[a]),I=o.useCallback(O=>{const D=O instanceof Error?O.message:String(O||"");return D.includes("P2P command timeout")||D.includes("P2P not connected")||D.includes("P2P not available")},[]),k=o.useCallback(async(O,D)=>{var W;if(!e||l)return!1;d(O),y("info",`Launching ${st(O)}${D!=null&&D.workspace?` in ${D.workspace}`:""}...`);try{const Q={ideType:O,enableCdp:!0};(W=D==null?void 0:D.workspace)!=null&&W.trim()?Q.workspace=D.workspace.trim():D!=null&&D.useDefaultWorkspace&&(Q.useDefaultWorkspace=!0);const be=await r(e,"launch_ide",Q);return y(be!=null&&be.success?"info":"error",be!=null&&be.success?`${st(O)} launched`:`Failed: ${be==null?void 0:be.error}`,!0),!!(be!=null&&be.success)}catch(Q){return y("error",`Launch error: ${Q.message}`,!0),!1}finally{d(null)}},[e,l,y,r]),w=o.useCallback(async O=>{if(!e)return{success:!1};const{cliType:D,dir:W,workspaceId:Q,useDefaultWorkspace:be,useHome:pe,argsStr:ue,model:we,resumeSessionId:ye}=O;if(!D)return y("warn","Select a CLI or ACP provider first",!0),{success:!1};const ve=ue?ue.split(/\s+/).filter(Boolean):void 0,V=(W==null?void 0:W.trim())||(Q?"(saved id)":be?"(default workspace)":pe?"(home)":"");y("info",`Launching ${D}${V?` in ${V}`:""}${we?` (model: ${we})`:""}...`),u(D);try{const H={cliType:D,cliArgs:ve,initialModel:we||void 0};W!=null&&W.trim()?H.dir=W.trim():Q?H.workspaceId=Q:be?H.useDefaultWorkspace=!0:pe&&(H.useHome=!0),ye&&(H.resumeSessionId=ye);const Z=await r(e,"launch_cli",H),me=(Z==null?void 0:Z.result)||Z;return Z!=null&&Z.success?(y("info",`${D} launched`,!0),(me==null?void 0:me.launchSource)==="home"?y("info","📂 Running in home directory (explicit choice)"):(me==null?void 0:me.launchSource)==="defaultWorkspace"&&y("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:me==null?void 0:me.sessionId}):(y("error",`Failed: ${(Z==null?void 0:Z.error)||(me==null?void 0:me.error)}`,!0),(Z==null?void 0:Z.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&S({cliType:D,argsStr:ue,model:we}),{success:!1,sessionId:me==null?void 0:me.sessionId})}catch(H){return I(H)?(y("warn",`${D} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(y("error",`Launch error: ${H.message}`,!0),{success:!1})}finally{u(null)}},[e,y,I,r]),g=o.useCallback(async(O,D,W,Q)=>e?O?D.trim()?w({cliType:O,dir:D,argsStr:W,model:Q}):(S({cliType:O,argsStr:W,model:Q}),{success:!1}):(y("warn","Select a provider",!0),{success:!1}):{success:!1},[e,y,w]),E=o.useCallback(async(O,D,W)=>{if(e&&window.confirm(`Stop ${O}?
59
+ This will terminate the process.`))try{const Q=await r(e,"stop_cli",{cliType:O,dir:D,targetSessionId:W});Q!=null&&Q.success?y("info",`${O} stopped`,!0):y("error",`Stop failed: ${(Q==null?void 0:Q.error)||"Unknown error"}`,!0)}catch(Q){y("error",`Stop failed: ${Q.message}`,!0)}},[e,y,r]),M=o.useCallback(async O=>{try{await r(O.daemonId,"restart_ide",{ideType:O.type}),y("info",`${st(O.type)} restart initiated`,!0)}catch(D){y("error",`Restart failed: ${D.message}`,!0)}},[y,r]),C=o.useCallback(async O=>{if(window.confirm(`Stop ${st(O.type)}?
60
+ This will disconnect CDP and optionally kill the process.`))try{const D=await r(O.daemonId,"stop_ide",{ideType:O.type,killProcess:!0});D!=null&&D.success?y("info",`${st(O.type)} stopped`,!0):y("error",`Stop failed: ${(D==null?void 0:D.error)||"Unknown error"}`,!0)}catch(D){y("error",`Stop failed: ${D.message}`,!0)}},[y,r]),R=o.useCallback(async()=>{if(e)try{const O=await r(e,"detect_ides",{});y("info",`Found ${((O==null?void 0:O.result)||[]).length} IDE(s)`,!0)}catch(O){y("error",`Detection failed: ${O.message}`,!0)}},[e,y,r]),K=o.useCallback(async O=>{if(!e||!O.trim())return!1;m(!0);try{const D=await r(e,"workspace_add",{path:O.trim()});return D!=null&&D.success?(y("info",`Workspace added: ${O.trim()}`),!0):(y("error",(D==null?void 0:D.error)||"workspace_add failed"),!1)}catch(D){return y("error",D.message),!1}finally{m(!1)}},[e,y,r]),z=o.useCallback(async O=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){m(!0);try{const D=await r(e,"workspace_remove",{id:O});D!=null&&D.success?y("info","Workspace removed",!0):y("error",(D==null?void 0:D.error)||"workspace_remove failed",!0)}catch(D){y("error",D.message,!0)}finally{m(!1)}}},[e,y,r]),T=o.useCallback(async O=>{var D;if(e){m(!0);try{const W=await r(e,"workspace_set_default",O===null?{clear:!0}:{id:O});if(W!=null&&W.success){y("info",O?"Default workspace updated":"Default workspace cleared",!0);const Q=typeof W.defaultWorkspacePath=="string"?W.defaultWorkspacePath:"";Q&&((D=N.current)==null||D.call(N,Q))}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]),L=o.useCallback(async O=>{var W;if(!e||!O.trim())return;const D=O.trim();m(!0);try{const Q=await r(e,"workspace_set_default",{path:D});Q!=null&&Q.success?(y("info","Default workspace set from history"),(W=N.current)==null||W.call(N,D)):y("error",(Q==null?void 0:Q.error)||"Could not set default (path missing on disk?)")}catch(Q){y("error",Q.message)}finally{m(!1)}},[e,y,r]),Y=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(O){y("warn",`Live nickname updated, but account sync failed: ${O.message}`)}y("info",`Nickname set to "${j||"(cleared)"}"`),h(!1)}catch(O){y("error",`Failed: ${O.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:E,handleRestartIde:M,handleStopIde:C,handleDetectIdes:R,handleWorkspaceAdd:K,handleWorkspaceRemove:z,handleWorkspaceSetDefault:T,handleWorkspaceResumePath:L,handleSaveNickname:Y,setOnDefaultWorkspaceChanged:A}}function Bx({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var M;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,A]=o.useState(""),y=o.useCallback(async C=>{b(!0),A("");try{const R=await rn(c,e,C);S(R.path),h(R.directories)}catch(R){A(R instanceof Error?R.message:"Could not load folder")}finally{b(!1)}},[e,c]),I=o.useCallback(()=>{m(!0);const C=[...r.map(K=>K.workspace),...n.map(K=>K.workspace),...a.map(K=>K.workspace)],R=sn(t.platform,tn(C,t.defaultWorkspacePath,(t.workspaces||[]).map(K=>K.path)));y(R)},[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,E=((M=t.loadavg)==null?void 0:M[0])||0;return s.jsxs("div",{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[s.jsx(fr,{icon:s.jsx(Di,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?Nu(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(Wd,{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(E/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:k?`${E.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:C=>void u(C.target.value===""?null:C.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(C=>s.jsx("option",{value:C.id,children:C.label||C.path},C.id))]}),t.defaultWorkspacePath&&s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:t.defaultWorkspacePath,children:t.defaultWorkspacePath})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:l,onClick:I,children:"Select workspace…"}),s.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(t.workspaces||[]).length>0&&s.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(t.workspaces||[]).map(C=>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:[C.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:Zr(C.path,C.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:C.path,children:C.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void f(C.id),children:"Remove"})]},C.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:C=>{y(C)},onConfirm:C=>{(async()=>{if(!C)return;await d(C)&&m(!1)})()}})]})}function Kx(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 Ox(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 Wx(e){const t=e.trim();return t||null}const ci=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Hx=[{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 Fx({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(E=>E!==w):[...g,w])},N=()=>f([...ci]),A=()=>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]),I=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:Hx.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:A,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:I,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 Ux({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var y;const i=t.filter(I=>I.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=I=>{const k=I.toLowerCase().replace(/[^a-z0-9-]/g,"");f(k),(!u||u===N(d))&&x(N(k))},N=I=>I.split("-").map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(" "),A=async()=>{if(!(!d||!u||!c)){v(!0),p("");try{const I=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:c});I!=null&&I.success||I!=null&&I.created?(j(!0),a==null||a(d)):p((I==null?void 0:I.error)||"Failed to create provider")}catch(I){p((I==null?void 0:I.message)||"Connection failed")}v(!1)}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:I=>I.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children: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(I=>s.jsxs("button",{onClick:()=>l(I.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===I.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===I.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:I.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===I.type?"#a78bfa":"var(--text-secondary)"},children:I.displayName})]},I.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:d,onChange:I=>b(I.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",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:I=>x(I.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),S&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:S})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children: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:A,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 zx({machineId:e,providers:t,sendDaemonCommand:r}){var M;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,A]=o.useState(""),[y,I]=o.useState(!1),k=o.useCallback(async()=>{if(e)try{const C=await r(e,"get_provider_source_config",{}),R=ii(C);R&&(h(R),b(R.sourceMode),A(R.explicitProviderDir||""))}catch{}},[e,r]),w=o.useCallback(async()=>{if(e){c(!0);try{const C=await r(e,"get_provider_settings",{}),R=Kx(C);if(R){const K=Ox(R,t);K.sort((z,T)=>z.category.localeCompare(T.category)||z.displayName.localeCompare(T.displayName)),a(K)}}catch{}c(!1)}},[e,t,r]);o.useEffect(()=>{n.length===0&&w(),p||k()},[]);const g=async(C,R,K)=>{d(`${C}.${R}`),a(z=>z.map(T=>T.type===C?{...T,values:{...T.values,[R]:K}}:T));try{const z=await r(e,"set_provider_setting",{providerType:C,key:R,value:K});z!=null&&z.success||w()}catch{w()}d(null)},E=async()=>{I(!0);try{const C=await r(e,"set_provider_source_config",{providerSourceMode:j,providerDir:Wx(N)}),R=ii(C);R?(h(R),b(R.sourceMode),A(R.explicitProviderDir||"")):await k(),await w()}catch{await k()}I(!1)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between items-center mb-4",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(C=>s.jsx("button",{onClick:()=>u(C),className:`machine-btn text-[10px] px-2 py-0.5 ${f===C?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:C.toUpperCase()},C))]}),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:C=>b(C.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:C=>A(C.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void E(),disabled:y,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:y?"Applying…":"Apply + Reload"})]}),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(C=>C.category===f).length>1&&(()=>{const C=n.filter(T=>T.category===f),R=new Map;for(const T of C)for(const L of T.schema){if(L.type!=="boolean")continue;const Y=R.get(L.key),O=!!(T.values[L.key]??L.default);Y?(Y.onCount+=O?1:0,Y.total+=1):R.set(L.key,{label:L.label||L.key,onCount:O?1:0,total:1})}const K=[...R.entries()].filter(([,T])=>T.total===C.length);if(K.length===0)return null;const z=async(T,L)=>{for(const Y of C)await g(Y.type,T,L)};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 (",C.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:K.map(([T,L])=>{const Y=L.onCount===L.total,O=L.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:L.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",L.onCount,"/",L.total,")"]}),s.jsx("button",{onClick:()=>void z(T,!0),disabled:Y,className:`machine-btn text-[9px] px-1.5 py-px ${Y?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void z(T,!1),disabled:O,className:`machine-btn text-[9px] px-1.5 py-px ${O?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},T)})})]})})(),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(C=>f==="all"||C.category===f).map(C=>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:C.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:C.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:C.category==="acp"?"rgba(139,92,246,0.08)":C.category==="cli"?"rgba(59,130,246,0.08)":C.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:C.category==="acp"?"#a78bfa":C.category==="cli"?"#60a5fa":C.category==="ide"?"#86efac":"var(--status-warning)"},children:C.category}),C.category==="ide"&&s.jsx("button",{onClick:()=>m(t.find(R=>R.type===C.type)||{type:C.type,name:C.displayName,displayName:C.displayName,icon:C.icon,category:C.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:C.schema.map(R=>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:[R.label||R.key,l===`${C.type}.${R.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),R.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:R.description})]}),s.jsx("div",{className:"shrink-0",children:R.type==="boolean"?s.jsx("button",{onClick:()=>g(C.type,R.key,!(C.values[R.key]??R.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:C.values[R.key]??R.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:C.values[R.key]??R.default?21:3}})}):R.type==="number"?s.jsx("input",{type:"number",value:Number(C.values[R.key]??R.default??0)||0,min:R.min,max:R.max,onChange:K=>{const z=parseInt(K.target.value)||0;R.min!==void 0&&z<R.min||R.max!==void 0&&z>R.max||g(C.type,R.key,z)},className:"machine-input w-20 text-center text-[11px]"}):R.type==="select"&&R.options?s.jsx("select",{value:String(C.values[R.key]??R.default??""),onChange:K=>g(C.type,R.key,K.target.value),className:"machine-input text-[11px]",children:R.options.map(K=>s.jsx("option",{value:K,children:K},K))}):s.jsx("input",{type:"text",value:String(C.values[R.key]??R.default??""),onBlur:K=>g(C.type,R.key,K.target.value),className:"machine-input w-[120px] text-[11px]"})})]},R.key))})]},C.type))}),x&&s.jsx(Fx,{machineId:e,provider:x,sendDaemonCommand:r,onClose:()=>m(null)}),v&&s.jsx(Ux,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>S(!1),onCreated:()=>{S(!1),w()}})]})}const Vx=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Gx({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function qx(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function Yx(e){return e.trim().toLowerCase()}function cn(e,t){const r=Yx(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 Xx(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 gl(e,t){return e.filter(r=>cn([r.level,r.message],t))}function li(e){return`${e.timestamp}:${e.level}:${e.message}`}function Jx(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const c of e.entries)n.set(li(c),c);for(const c of t.entries)n.set(li(c),c);const a=Array.from(n.values()).sort((c,l)=>c.timestamp-l.timestamp).slice(-r),i=a.reduce((c,l)=>Math.max(c,Number(l.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:i}}return t.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:t.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function Qx(e,t,r=120){if(t.length===0)return e;const n=new Map;for(const a of e)n.set(a.id,a);for(const a of t)n.set(a.id,a);return Array.from(n.values()).sort((a,i)=>a.ts-i.ts).slice(-r)}function Zx(e,t){return e.split(`
63
+ `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>cn([r],t))}function yl(e,t){return e.filter(r=>cn([r.level,r.category,r.stage,r.interactionId,Ya(r.payload)],t))}function vl(e,t){return e.filter(r=>cn([r.kind,r.topic,r.interactionId,Ya(r.payload)],t))}function di(e){return e==="warn"||e==="error"}function eb({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=>di(a.level)).length+r.filter(a=>di(a.level)).length}}function tb({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(i=>`${new Date(i.timestamp).toISOString()} ${i.level.toUpperCase()} ${i.message}`)].join(`
64
+ `)):t.length>0&&a.push(["[daemon logs]",...t].join(`
65
+ `)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${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
+ `)),a.join(`
68
+
69
+ `)}function sb({daemonLogs:e,trace:t,webEvents:r,daemonLogKind:n,daemonFetchError:a,traceFetchError:i,searchQuery:c}){const l=gl(e,c),d=yl(t,c),f=vl(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 ui(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function mi(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 rb({machineId:e,sendDaemonCommand:t}){var P,G;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(null),[S,p]=o.useState(!0),[h,j]=o.useState("info"),[b,N]=o.useState("info"),[A,y]=o.useState("all"),[I,k]=o.useState(""),[w,g]=o.useState(!0),[E,M]=o.useState(!0),[C,R]=o.useState(""),[K,z]=o.useState(""),[T,L]=o.useState(0),[Y,O]=o.useState({daemon:!0,trace:!1,web:!1}),D=o.useRef(null),W=o.useRef(!1),Q=o.useRef(0),be=o.useRef(0),pe=o.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),ue=o.useRef([]),we=o.useCallback(()=>{const U={entries:[],kind:"empty",rawText:"",lastTs:0};pe.current=U,Q.current=0,n([]),l(""),i("empty"),g(!0)},[]),ye=o.useCallback(()=>{ue.current=[],be.current=0,f([]),M(!0)},[]),ve=o.useMemo(()=>qx(d,A),[d,A]),V=o.useMemo(()=>gl(r,I),[r,I]),H=o.useMemo(()=>Zx(c,I),[c,I]),Z=o.useMemo(()=>yl(ve,I),[ve,I]),me=o.useMemo(()=>vl(u,I),[u,I]),ne=o.useMemo(()=>b==="issues"?V.filter(U=>U.level==="warn"||U.level==="error"):b==="info"?V.filter(U=>U.level!=="debug"):V,[V,b]),fe=o.useMemo(()=>b==="all"?H:[],[H,b]),se=o.useMemo(()=>b==="issues"?Z.filter(U=>U.level==="warn"||U.level==="error"):b==="info"?Z.filter(U=>U.level!=="debug"):Z,[Z,b]),xe=o.useMemo(()=>b==="issues"?[]:me,[me,b]),ie=o.useMemo(()=>eb({daemonLogs:V,daemonRawLines:H,trace:Z,webEvents:me}),[V,H,Z,me]),ce=o.useMemo(()=>sb({daemonLogs:r,trace:ve,webEvents:u,daemonLogKind:a,daemonFetchError:C,traceFetchError:K,searchQuery:I}),[C,a,r,ve,I,K,u]),ae=o.useCallback(async()=>{if(!e)return;const U=Q.current,de=be.current,[Ne,_e]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:h,since:U}),t(e,"get_debug_trace",Gx({count:120,since:de,category:A}))]);if(Ne.status==="fulfilled"){const ge=Ne.value,Be=(ge==null?void 0:ge.result)||ge,Oe=Xx(Be),Ke=Jx(pe.current,Oe,300);pe.current=Ke,Q.current=Ke.lastTs,g(!1),R((ge==null?void 0:ge.success)===!1?String((ge==null?void 0:ge.error)||"Could not load daemon logs"):""),i(Ke.kind),l(Ke.rawText),n(Ke.entries)}else g(!1),R(Ne.reason instanceof Error?Ne.reason.message:"Could not load daemon logs");if(_e.status==="fulfilled"){const ge=_e.value,Be=(ge==null?void 0:ge.result)||ge;if((ge==null?void 0:ge.success)===!1)z(String((ge==null?void 0:ge.error)||"Could not load daemon trace"));else if(Array.isArray(Be==null?void 0:Be.trace)){const Oe=Be.trace,Ke=Qx(ue.current,Oe,120),et=Oe.reduce((Je,at)=>Math.max(Je,Number(at.ts||0)),de);ue.current=Ke,et>de&&(be.current=et),z(""),f(Ke)}else z("");M(!1)}else M(!1),z(_e.reason instanceof Error?_e.reason.message:"Could not load daemon trace");x(ks.list({limit:120})),v(Date.now())},[h,e,t,A]);o.useEffect(()=>{ye()},[ye,A]),o.useEffect(()=>{if(!e||(ae(),!S))return;const U=setInterval(()=>{ae()},3e3);return()=>clearInterval(U)},[S,ae,e,T]),o.useEffect(()=>{if(S&&(ne.length>0||fe.length>0||se.length>0||xe.length>0)){const U=W.current?"smooth":"instant";setTimeout(()=>{var de;(de=D.current)==null||de.scrollIntoView({behavior:U}),W.current=!0},50)}},[ne.length,fe.length,se.length,xe.length,S]);const X=((P=ce.latestIssue)==null?void 0:P.level)==="error"?"danger":((G=ce.latestIssue)==null?void 0:G.level)==="warn"?"warning":"good",J=C||K?"danger":S?"good":"neutral",oe=o.useCallback(async()=>{var de;const U=tb({daemonLogs:ne,daemonRawLines:fe,trace:se,webEvents:xe});if(!U.trim()){lt.showToast("No visible logs to copy.","info");return}try{await((de=navigator.clipboard)==null?void 0:de.writeText(U)),lt.showToast("Copied visible logs to clipboard.","success")}catch(Ne){lt.showToast(Ne instanceof Error?Ne.message:"Could not copy visible logs","warning")}},[ne,fe,se,xe]);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(U=>s.jsx("button",{onClick:()=>{U!==h&&(j(U),we())},className:`machine-btn text-[10px] px-2 py-0.5 ${h===U?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:U.toUpperCase()},U)),s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider ml-3 mr-1",children:"Trace"}),Vx.map(U=>s.jsx("button",{onClick:()=>{U.value!==A&&y(U.value)},className:`machine-btn text-[10px] px-2 py-0.5 ${A===U.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:U.label},U.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+ (${ie.info})`},{id:"issues",label:`Issues (${ie.issues})`},{id:"all",label:`All (${ie.all})`}].map(U=>s.jsx("button",{type:"button",onClick:()=>N(U.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${b===U.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:U.label},U.id))}),s.jsx("input",{value:I,onChange:U=>k(U.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:()=>{oe()},className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:()=>p(U=>!U),className:`machine-btn ${S?"text-green-500 border-green-500/30":""}`,children:S?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:()=>L(U=>U+1),className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:()=>{we(),ye(),x([]),v(null),R(""),z(""),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(ce.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 ",ne.length+fe.length," · trace ",se.length," · web ",xe.length]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:I.trim()?`Filtered by “${I.trim()}”`:"Showing the latest buffered entries"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Dn(X)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Attention needed"}),ce.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[ce.latestIssue.source," · ",ce.latestIssue.label]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:ce.latestIssue.detail}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:[ce.issueCount," warn/error signal(s) · ",ui(ce.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(J)}`,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:C||K?"Needs attention":S?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",ui(m)]}),(C||K)&&s.jsxs("div",{className:"text-[11px] text-red-300 mt-2 space-y-1",children:[C&&s.jsxs("div",{children:["Daemon logs: ",C]}),K&&s.jsxs("div",{children:["Daemon trace: ",K]})]})]})]}),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:()=>O(U=>({...U,daemon:!U.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"?`${fe.length} visible raw line(s) from file fallback`:`${ne.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:Y.daemon?"Hide":"Show"})]}),Y.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:[w&&!ce.hasAnyData&&!C&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!w&&C&&a==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:C}),!w&&a==="empty"&&!C&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),a==="text"&&fe.length===0&&c&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:b==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),a==="structured"&&ne.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"&&fe.map((U,de)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:U},`raw-${de}`)),a!=="text"&&ne.map((U,de)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${mi(U.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(U.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:U.level==="error"?"ERR":U.level==="warn"?"WRN":U.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:U.message})]},`log-${de}`))]})]}),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:()=>O(U=>({...U,trace:!U.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",A==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[se.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:Y.trace?"Hide":"Show"})]}),Y.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[E&&se.length===0&&!K&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!E&&K&&se.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:K}),!E&&se.length===0&&!K&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:I.trim()?"No trace entries match the current search.":A==="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."}),se.map(U=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${mi(U.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(U.ts).toLocaleTimeString()}),s.jsx("span",{children:U.level.toUpperCase()}),s.jsxs("span",{children:[U.category,".",U.stage]}),U.interactionId&&s.jsxs("span",{children:["ix=",U.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:er(U.payload,360)||"No payload"})]},U.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>O(U=>({...U,web:!U.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:[xe.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:Y.web?"Hide":"Show"})]}),Y.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:[xe.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:I.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),xe.map(U=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(U.ts).toLocaleTimeString()}),s.jsx("span",{children:U.kind}),U.topic&&s.jsxs("span",{children:["topic=",U.topic]}),U.interactionId&&s.jsxs("span",{children:["ix=",U.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:er(U.payload,360)||"No payload"})]},U.id))]})]})]}),s.jsx("div",{ref:D})]})}function nb(e){return e.diagnostics?{label:"Managed",toneClass:"bg-green-500/[0.08] text-green-500"}:e.loading||e.refreshing?{label:"Checking…",toneClass:"bg-sky-500/[0.08] text-sky-400"}:e.error?{label:"Diagnostics issue",toneClass:"bg-amber-500/[0.08] text-amber-400"}:{label:"Unavailable",toneClass:"bg-red-500/[0.08] text-red-400"}}function wl(e){const t=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return t?t==="auto_resumed"?"restored after restart":t==="resume_failed"?"restore failed":t==="host_restart_interrupted"?"host restart interrupted":t==="orphan_snapshot"?"snapshot recovered":t.replace(/_/g," "):null}function ab(e){var a;const t=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=wl((i==null?void 0:i.meta)||void 0),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 ob(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 fi(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 ib(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function cb(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 lb(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 db({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,d]=o.useState(!1),f=yp(e,{enabled:!!e,includeSessions:!0,limit:Mo,intervalMs:Lm}),u=f.diagnostics,x=f.loading,m=f.applyDiagnostics,v=o.useMemo(()=>nb({diagnostics:u,loading:x,refreshing:l,error:n}),[u,x,l,n]),S=o.useMemo(()=>new Map(t.map(M=>[M.sessionId||M.id,M])),[t]),p=o.useCallback(async()=>{if(e){d(!0);try{const M=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Mo}),C=$n(M);if(!(C!=null&&C.success))throw new Error((C==null?void 0:C.error)||"Could not load hosted runtime diagnostics");m(C.diagnostics||C.result||null),a("")}catch(M){const C=M instanceof Error?M.message:"Could not load hosted runtime diagnostics";a(C)}finally{d(!1)}}},[m,e,r]);o.useEffect(()=>{!e||u||x||l||p()},[u,x,e,p,l]);const h=o.useCallback(async(M,C)=>{const R=`${M}:${C.sessionId}`;if(!(M==="session_host_stop_session"&&!window.confirm(`Stop ${C.displayName}?
70
+ This will terminate the hosted runtime.`))){c(R);try{const K=await r(e,M,{sessionId:C.sessionId}),z=$n(K);if(!(z!=null&&z.success))throw new Error((z==null?void 0:z.error)||"Session host action failed");const T=M==="session_host_resume_session"?"resumed":M==="session_host_restart_session"?"restarted":"stopped";lt.showToast(`Session host ${T}: ${C.displayName}`,"success"),await p()}catch(K){const z=K instanceof Error?K.message:"Session host action failed";lt.showToast(z,"warning"),a(z)}finally{c(K=>K===R?null:K)}}},[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 C=await r(e,"session_host_prune_duplicate_sessions",{}),R=$n(C);if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Duplicate prune failed");const K=R.result||{},z=Array.isArray(K.prunedSessionIds)?K.prunedSessionIds.length:0,T=typeof K.duplicateGroupCount=="number"?K.duplicateGroupCount:0;lt.showToast(`Pruned ${z} duplicate runtime(s) across ${T} group(s)`,"success"),await p()}catch(C){const R=C instanceof Error?C.message:"Duplicate prune failed";lt.showToast(R,"warning"),a(R)}finally{c(C=>C==="session_host_prune_duplicate_sessions"?null:C)}}},[e,p,r]),b=o.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((M,C)=>(C.lastActivityAt||0)-(M.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)||[]}:ab(b),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,b]),A=N.liveRuntimes,y=N.recoverySnapshots,I=N.inactiveRecords,k=o.useMemo(()=>lb(A),[A]),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(M=>M.level==="warn"||M.level==="error")||null,[u==null?void 0:u.recentLogs]),E=(M,C)=>{var W;const R=i===`session_host_resume_session:${M.sessionId}`,K=i===`session_host_restart_session:${M.sessionId}`,z=i===`session_host_stop_session:${M.sessionId}`,T=wl(M.meta),L=S.get(M.sessionId),Y=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,O=C==="recovery"?"Recover":"Resume",D=ob(C);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||(L==null?void 0:L.cliName)||M.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${cb(M.lifecycle)}`,children:M.lifecycle}),T&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:T})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:M.workspaceLabel||(L==null?void 0:L.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:ib(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(Ti,{size:11})," ",Y]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",fi(M.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",D]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[C==="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:()=>{h("session_host_resume_session",M)},children:R?`${O}ing…`:O}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{h("session_host_restart_session",M)},children:K?"Restarting…":"Restart"}),C==="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:()=>{h("session_host_stop_session",M)},children:z?"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:Nf()})]}),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:fi(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")}),A.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:A.map(M=>E(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=>E(M,"recovery"))})]}),I.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:En("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:I.map(M=>E(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"}),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(M=>{var R;const C=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:(C==null?void 0:C.displayName)||((R=S.get(M.sessionId))==null?void 0:R.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:u.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function ub({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 mb({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.26");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:nt(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(Di,{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}=tl(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 fb(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const pb={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,A]=o.useState(null),y=o.useCallback(_=>{_&&u(Gt(_))},[u]),I=pb[e],k=e==="ide",w=e==="acp",g=o.useMemo(()=>n.filter(_=>_.category===e&&(e==="ide"||_.installed!==!1)),[e,n]),E=o.useMemo(()=>new Map(g.map(_=>[_.type,_.displayName||_.type])),[g]),[M,C]=o.useState(""),[R,K]=o.useState(""),[z,T]=o.useState([]),[L,Y]=o.useState(""),[O,D]=o.useState(""),[W,Q]=o.useState([]),[be,pe]=o.useState(!1),[ue,we]=o.useState(!1),[ye,ve]=o.useState(""),[V,H]=o.useState(!1),[Z,me]=o.useState(()=>ht()),[ne,fe]=o.useState(null),[se,xe]=o.useState(f?"__custom__":d||t.defaultWorkspaceId||""),[ie,ce]=o.useState(f||""),[ae,X]=o.useState([]),[J,oe]=o.useState(!1),[P,G]=o.useState(""),[U,de]=o.useState([]),[Ne,_e]=o.useState(!1),[ge,Be]=o.useState(""),Oe=o.useRef(null),[Ke,et]=o.useState(null),Je=o.useRef("__home__"),[at,dt]=o.useState("__home__"),[mt,ot]=o.useState(!1),ut=o.useRef(0),Ie=ae.filter(_=>!a.some(te=>te.type===_&&bt(te.status)!=="stopped")),$e=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!se&&xe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(f){xe("__custom__"),ce(f);return}d&&(xe(d),ce(""))},[d,f]),o.useEffect(()=>{k||M&&(g.some(_=>_.type===M)||(C(""),D("")))},[g,k,M]);const Ue=(()=>{if(se==="__custom__")return ie.trim();if(!se)return"";const _=(t.workspaces||[]).find(te=>te.id===se);return(_==null?void 0:_.path)||""})(),Ve=o.useCallback(_=>{const te=$e.current[_];te&&(clearTimeout(te),delete $e.current[_]),X(he=>he.includes(_)?he.filter(Re=>Re!==_):he)},[]),qe=o.useRef(new Set),Qe=o.useCallback(async _=>{if(l){_e(!0),Be("");try{const te=await rn(l,r,_);G(te.path),ce(te.path),de(te.directories)}catch(te){Be(te instanceof Error?te.message:"Could not load folder")}finally{_e(!1)}}},[r,l]),ee=o.useCallback(()=>{if(!l)return;xe("__custom__"),oe(!0);const _=a.map(he=>he.workspace),te=sn(t.platform,tn(ie.trim(),Ue,f,_,t.defaultWorkspacePath,(t.workspaces||[]).map(he=>he.path)));Qe(te)},[ie,f,Qe,t.defaultWorkspacePath,t.platform,t.workspaces,a,Ue,l]),Le=o.useCallback(_=>{const te=String(_.workspace||"").trim();if(!te)return;const he=(t.workspaces||[]).find(Re=>Ir(Re.path)===Ir(te));if(he){xe(he.id),ce("");return}xe("__custom__"),ce(te)},[t.workspaces]),De=o.useCallback(_=>{const te=String(_.workspace||"").trim();if(!te)return{workspaceId:null,workspacePath:"",useHome:!0};const he=(t.workspaces||[]).find(Re=>Ir(Re.path)===Ir(te));return he?{workspaceId:he.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:te,useHome:!1}},[t.workspaces]),rt=o.useCallback(async _=>{if(!l||!_||e!=="cli"){Q([]),pe(!1),we(!1),ve("");return}const te=ut.current+1;ut.current=te,pe(!0),ve("");try{const he=await l(r,"list_saved_sessions",{providerType:_,kind:"cli",limit:30});if(ut.current!==te)return;const Re=(he==null?void 0:he.result)??he;Q(Array.isArray(Re==null?void 0:Re.sessions)?Re.sessions:[])}catch(he){if(ut.current!==te)return;Q([]),ve(he instanceof Error?he.message:"Could not load saved sessions")}finally{ut.current===te&&(pe(!1),we(!0))}},[e,r,l]),Ct=o.useMemo(()=>{if(e!=="cli"||!M)return null;const _=E.get(M)||M;return{routeId:r,daemonId:r,providerSessionId:O||void 0,transport:"pty",mode:"chat",agentName:_,agentType:M,status:"idle",title:_,messages:[],ideType:M,workspaceName:Ue,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${M}`}},[e,r,E,Ue,O,M]),ft=o.useCallback(_=>{if(e==="ide"||!_){T([]);return}T(pl(r,_))},[e,r]);o.useEffect(()=>{ut.current+=1,D(""),ft(M),we(!1),Q([]),ve(""),pe(!1)},[e,ft,rt,M]);const Tt=o.useMemo(()=>W.find(_=>_.providerSessionId===O)||null,[W,O]);o.useEffect(()=>{if(!O)return;const _=W.find(te=>te.providerSessionId===O);_!=null&&_.canResume||D("")},[W,O]);const yt=o.useCallback((_,te)=>{Oe.current=te,Je.current=_.selectedWorkspaceKey||"__home__",dt(_.selectedWorkspaceKey||"__home__"),et(_)},[]),B=o.useCallback(()=>{Oe.current&&(ot(!0),Oe.current().finally(()=>{Oe.current=null,ot(!1),et(null)}))},[]),$=o.useCallback(_=>{if(!_)return;X(he=>he.includes(_)?he:[...he,_]);const te=$e.current[_];te&&clearTimeout(te),$e.current[_]=setTimeout(()=>{X(he=>he.includes(_)?he.filter(Re=>Re!==_):he),delete $e.current[_]},2e4)},[]);o.useEffect(()=>{for(const te of a)bt(te.status)!=="stopped"&&(ae.includes(te.type)&&!qe.current.has(te.type)&&(qe.current.add(te.type),b("info",`${E.get(te.type)||te.type} launched`,!0)),Ve(te.type));const _=new Set(a.filter(te=>bt(te.status)!=="stopped").map(te=>te.type));qe.current.forEach(te=>{!ae.includes(te)&&!_.has(te)&&qe.current.delete(te)})},[b,Ve,a,ae,E]),o.useEffect(()=>()=>{Object.values($e.current).forEach(clearTimeout),$e.current={}},[]);const[F,q]=o.useState({}),[le,ke]=o.useState(null);o.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const te=await l(r,"get_ide_extensions",{}),he=(te==null?void 0:te.result)||te;he!=null&&he.success&&(he!=null&&he.ideExtensions)&&q(he.ideExtensions)}catch{}})()},[k,r,l]);const Me=_=>k?st(_.type):e==="cli"?_.cliName:_.acpName,Ce=k?t.detectedIdes||[]:[],re=o.useCallback(async _=>{const te=(_==null?void 0:_.type)||M,he=(_==null?void 0:_.workspacePath)??Ue;if(k){await x(te,he?{workspace:he}:void 0)&&$(te);return}const Re=await c.runLaunchCliCore({cliType:te,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)??(R||void 0),model:(_==null?void 0:_.model)??(w&&L||void 0),resumeSessionId:(_==null?void 0:_.resumeSessionId)||!w&&e==="cli"&&te===M&&O||void 0});if(Re.success||Re.pending){const Se=(_==null?void 0:_.argsStr)??R;!k&&(Se!=null&&Se.trim())&&(hl(r,te,Se),ft(te)),$(te),Re.success&&Re.sessionId&&y(Re.sessionId)}},[c,x,w,k,R,L,ft,$,r,y,Ue,O,M]),je=jc(k?"ide":w?"acp":"cli",!k&&!w&&!!O),We=kc(k?"ide":w?"acp":"cli",!k&&!w&&!!O),Fe=()=>{var Se;const _=k?st(M):E.get(M)||M,te=!k&&!w&&!!O,{options:he,selectedKey:Re}=os({machine:t,currentWorkspaceId:se&&se!=="__custom__"?se:null,currentWorkspacePath:Ue});yt({title:te?Da(_):ss("start-fresh",_),description:te?Ea():rs("start-fresh"),confirmLabel:je,busyLabel:We,workspaceOptions:he,selectedWorkspaceKey:Re,details:[{label:"Mode",value:I.label},{label:"Provider",value:_},...!k&&e==="cli"&&O?[{label:"Resume",value:((Se=W.find(Ae=>Ae.providerSessionId===O))==null?void 0:Se.title)||O}]:[],...!k&&R.trim()?[{label:"Arguments",value:R.trim()}]:[],...w&&L.trim()?[{label:"Model",value:L.trim()}]:[]]},async()=>{const Ae=he.find(Te=>Te.key===Je.current);Ae!=null&&Ae.workspaceId?(xe(Ae.workspaceId),ce("")):Ae!=null&&Ae.workspacePath?(xe("__custom__"),ce(Ae.workspacePath)):(xe(""),ce("")),await re({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(_,te,he=!1)=>{if(_.mode===te){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:te}),he&&y(_.sessionId)}catch(Re){const Se=Fc(Re);Hc(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:se,onChange:_=>{const te=_.target.value;if(xe(te),te==="__custom__"&&l){ee();return}te!=="__custom__"&&ce("")},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…"})]})}),se==="__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:ee,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:ie,onChange:_=>ce(_.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:se==="__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:se===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 ${I.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",I.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?Ce.length>0?Ce.map(_=>{const te=a.find(Te=>(Te.type||"").toLowerCase()===(_.type||"").toLowerCase()&&bt(Te.status)!=="stopped"),he=_.running||!!te,Re=!!te&&te.cdpConnected,Se=ae.includes(_.type||_.id||""),Ae=M===(_.type||"");return s.jsxs("button",{onClick:()=>{if(Re&&te){const Te=te.sessionId;Te?u(Gt(Te),{state:{openRemoteForTabKey:Te}}):u("/dashboard",{state:{openRemoteForTabKey:te.id}});return}Se||C(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||st(_.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($d,{size:14})," Scan System"]})]}):g.length>0?g.map(_=>{const te=M===_.type,he=ae.includes(_.type),Se=!!a.find(Ae=>Ae.type===_.type&&bt(Ae.status)!=="stopped");return s.jsxs("button",{onClick:()=>C(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 ${te?"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":te?"text-accent-primary":"text-text-muted"}`,children:he?"Starting...":te?"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?st(M):E.get(M)||M})]}),Pe,!k&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&s.jsx(bl,{busy:!!j||!!h||ae.includes(M),savedSessionsLoading:be,savedSessionsError:ye,selectedSession:Tt,onRefresh:()=>void rt(M),onOpenHistory:()=>{M&&(H(!0),xl({hasLoadedInitialResults:ue,isLoading:be})&&rt(M))},onClearSelection:()=>D("")}),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:L,onChange:_=>Y(_.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:R,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"}),z.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:z.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:Fe,disabled:!!j||!!h||ae.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||h===M?"⏳ 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(te=>te.type===_&&bt(te.status)!=="stopped")).length,")"]}),a.length===0&&Ie.length===0?s.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",I.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ie.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?st(_):E.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 te=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:[Me(_),(te==null?void 0:te.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",te.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}`),A(he.runtimeKey||null),window.setTimeout(()=>{A(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:fb(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",st(_.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:st(_.type)}]},async()=>{const pt=Ae.find(Ot=>Ot.key===Je.current),ct=(pt==null?void 0:pt.workspacePath)??"";if(ct&&ct!==Se){await re({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?st(_.type):Me(_),{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:I.label},{label:"Provider",value:Ae}]},async()=>{const ct=Te.find(Ot=>Ot.key===Je.current);await re({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})})]})]}),te&&te.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:te.aiAgents.map(Se=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${zi(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))}),te&&(F[te.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:(F[te.type]||[]).map(Se=>s.jsxs("button",{disabled:le===`${te.type}.${Se.type}`,onClick:async()=>{const Ae=`${te.type}.${Se.type}`;ke(Ae);try{await l(r,"set_ide_extension",{ideType:te.type,extensionType:Se.type,enabled:!Se.enabled}),q(Te=>({...Te,[te.type]:(Te[te.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)})]}),J&&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:P,directories:U,busy:Ne,error:ge,confirmLabel:"Use this folder",onClose:()=>oe(!1),onNavigate:_=>{Qe(_)},onConfirm:_=>{ce(_),xe("__custom__"),oe(!1)}}),Ke&&s.jsx(Ga,{title:Ke.title,description:Ke.description,details:Ke.details,workspaceOptions:Ke.workspaceOptions,selectedWorkspaceKey:at,onWorkspaceChange:_=>{Je.current=_,dt(_)},confirmLabel:Ke.confirmLabel,busyLabel:Ke.busyLabel,busy:mt,onConfirm:B,onCancel:()=>{Oe.current=null,et(null)}}),V&&Ct&&s.jsx($a,{activeConv:Ct,ides:[],isCreatingChat:!1,isRefreshingHistory:be,savedSessions:W,isSavedSessionsLoading:be,isResumingSavedSessionId:ne,savedHistoryFilters:Z,onSavedHistoryFiltersChange:me,onClose:()=>H(!1),onNewChat:()=>{D(""),H(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{rt(M)},onResumeSavedSession:_=>{if(!_.canResume||ne)return;const te=De(_);D(_.providerSessionId),Le(_),fe(_.providerSessionId),H(!1),re({type:_.providerType,workspaceId:te.workspaceId,workspacePath:te.workspacePath,useHome:te.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{fe(he=>he===_.providerSessionId?null:he)})}})]})}const pi=[{id:"ide",label:"IDE",helper:"Open a graphical workspace and attach CDP"},{id:"cli",label:"CLI",helper:"Launch a terminal-first workspace on this machine"},{id:"acp",label:"ACP",helper:"Launch an ACP-backed workspace on this machine"}];function hb({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:pi.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=pi.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 xb({onNicknameSynced:e}={}){var fe,se,xe,ie,ce,ae,X,J,oe;const{id:t}=id(),r=As(),n=pa(),{sendCommand:a}=wt(),i=ar(),c=Bc(),l=pc(),d=l.ides||[],f=l.initialLoaded??!0,u=d.find(P=>P.id===t&&P.type==="adhdev-daemon"),x=d.some(P=>P.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__"),[A,y]=o.useState("__home__"),[I,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 P=u.machine;(typeof(P==null?void 0:P.cpus)!="number"||typeof(P==null?void 0:P.totalMem)!="number"||typeof(P==null?void 0:P.arch)!="string"||typeof(P==null?void 0:P.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[m,c,u,t]),gp(t&&m==="overview"?[t]:[],{enabled:m==="overview",intervalMs:Im});const g=()=>{if(x){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},E=$x({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:w});o.useEffect(()=>lt.onToast(G=>{l.setToasts(de=>{if(de.some(ge=>ge.message===G.message&&G.timestamp-ge.timestamp<3e3))return de;const _e={id:G.id,message:G.message,type:G.type,timestamp:G.timestamp,targetKey:G.targetKey,actions:G.actions};return[...de.slice(-4),_e]});const U=G.duration||5e3;setTimeout(()=>l.setToasts(de=>de.filter(Ne=>Ne.id!==G.id)),U)}),[l]);const M=(u==null?void 0:u.availableProviders)||[],C={};for(const P of M)C[P.type]=P.icon;const R=P=>C[P]||"",K=u?{id:u.id,hostname:Vi(u,{fallbackId:u.id}),platform:((fe=u.machine)==null?void 0:fe.platform)||"unknown",arch:((se=u.machine)==null?void 0:se.arch)||"",cpus:((xe=u.machine)==null?void 0:xe.cpus)||0,totalMem:((ie=u.machine)==null?void 0:ie.totalMem)||0,freeMem:(ce=u.machine)==null?void 0:ce.freeMem,availableMem:(ae=u.machine)==null?void 0:ae.availableMem,loadavg:(X=u.machine)==null?void 0:X.loadavg,uptime:(J=u.machine)==null?void 0:J.uptime,release:((oe=u.machine)==null?void 0:oe.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,z=d.filter(P=>P.daemonId===t&&P.type!=="adhdev-daemon").filter(P=>!Qs(P)&&!ys(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,version:P.version||"",instanceId:P.instanceId||"",status:P.status,workspace:P.workspace||null,terminals:P.terminals||0,aiAgents:Ru(P.aiAgents||(P.agents||[]).map(G=>({id:G.name,name:G.name,status:G.status,version:G.version}))),activeChat:P.activeChat||null,chats:P.chats||[],childSessions:P.childSessions||[],cdpConnected:P.cdpConnected||!1,daemonId:t})),T=d.filter(P=>P.daemonId===t&&Qs(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,cliName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,mode:P.mode,runtimeKey:P.runtimeKey,runtimeDisplayName:P.runtimeDisplayName,runtimeWorkspaceLabel:P.runtimeWorkspaceLabel,runtimeWriteOwner:P.runtimeWriteOwner||null,runtimeAttachedClients:P.runtimeAttachedClients||[],daemonId:t})),L=d.filter(P=>P.daemonId===t&&ys(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,acpName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,daemonId:t})),Y=u?At(u,{fallbackId:t}):"",O="workspace",D=n.state,W=D==null?void 0:D.initialMachineTab,Q=D==null?void 0:D.initialWorkspaceCategory,be=D==null?void 0:D.initialWorkspaceId,pe=D==null?void 0:D.initialWorkspacePath,ue=W==="ides"||W==="clis"||W==="acps"?"workspace":W||O,we=W==="ides"?"ide":W==="clis"?"cli":W==="acps"?"acp":Q,ye=[...z.map(P=>{var G,U,de,Ne,_e;return{id:`ide:${P.type}:${P.workspace||""}`,label:((G=P.activeChat)==null?void 0:G.title)||P.type,kind:"ide",providerType:P.type,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:((_e=(Ne=(de=(U=P.activeChat)==null?void 0:U.messages)==null?void 0:de.at)==null?void 0:Ne.call(de,-1))==null?void 0:_e.timestamp)||0}}),...T.map(P=>{var G,U,de,Ne,_e;return{id:`cli:${P.type}:${P.workspace||""}`,label:((G=P.activeChat)==null?void 0:G.title)||P.cliName,kind:"cli",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:((_e=(Ne=(de=(U=P.activeChat)==null?void 0:U.messages)==null?void 0:de.at)==null?void 0:Ne.call(de,-1))==null?void 0:_e.timestamp)||0}}),...L.map(P=>{var G,U,de,Ne,_e;return{id:`acp:${P.type}:${P.workspace||""}`,label:((G=P.activeChat)==null?void 0:G.title)||P.acpName,kind:"acp",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:ds(P.summaryMetadata)||P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:((_e=(Ne=(de=(U=P.activeChat)==null?void 0:U.messages)==null?void 0:de.at)==null?void 0:Ne.call(de,-1))==null?void 0:_e.timestamp)||0}})].sort((P,G)=>(G.lastLaunchedAt||0)-(P.lastLaunchedAt||0)),ve=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(P=>({id:P.id,label:P.title||P.providerName||P.providerType,kind:P.kind,providerType:P.providerType,providerSessionId:P.providerSessionId,subtitle:ds(P.summaryMetadata)||P.workspace||void 0,workspace:P.workspace,summaryMetadata:P.summaryMetadata,lastLaunchedAt:P.lastLaunchedAt})):ye,V=o.useMemo(()=>{var G;const P=((G=l.connectionStates)==null?void 0:G[t||""])||void 0;return d.filter(U=>U.daemonId===t&&U.type!=="adhdev-daemon").flatMap(U=>Ba(U,{connectionStates:t&&P?{[t]:P}:void 0,defaultConnectionState:P})).filter(U=>!(U.transport==="pty"&&U.mode==="terminal")).sort((U,de)=>ea(de)-ea(U))},[d,l.connectionStates,t]),H=o.useCallback(P=>{const G=Ia(P);G&&r(Gt(G))},[r]),Z=o.useCallback(()=>{h.current&&(k(!0),h.current().finally(()=>{h.current=null,k(!1),b(null)}))},[]),me=o.useCallback(P=>{if(!K)return;const{options:G,selectedKey:U}=os({machine:K,currentWorkspacePath:P.workspace}),de=async()=>{p(P.kind),v("workspace")};h.current=async()=>{const Ne=G.find(Be=>Be.key===N.current),_e=(Ne==null?void 0:Ne.workspacePath)??null,ge=(Ne==null?void 0:Ne.workspaceId)??null;if(P.kind==="ide"&&P.providerType){await E.handleLaunchIde(P.providerType,_e?{workspace:_e}:void 0);return}if((P.kind==="cli"||P.kind==="acp")&&P.providerType){await E.runLaunchCliCore({cliType:P.providerType,dir:ge?void 0:_e||"",workspaceId:ge||void 0,model:P.kind==="acp"&&qi(P.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:P.providerSessionId});return}await de()},N.current=U,y(U),b({title:P.kind==="ide"?ss("restart-ide",P.label):P.providerSessionId?Da(P.label):ss("start-fresh",P.label),description:P.kind==="ide"?rs("restart-ide"):P.providerSessionId?Ea():rs("start-fresh"),confirmLabel:P.kind==="ide"?Is("restart-ide"):P.providerSessionId?Ur(!0):Is("start-fresh"),busyLabel:P.kind==="ide"?Ms("restart-ide"):P.providerSessionId?Pa(!0):Ms("start-fresh"),workspaceOptions:G,details:[{label:"Mode",value:P.kind.toUpperCase()},...P.providerType?[{label:"Provider",value:P.providerType}]:[]]})},[E,K]);if(o.useEffect(()=>{v(ue)},[O,ue,t]),o.useEffect(()=>{we&&p(we)},[we,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 ne=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nt,{size:14})," Workspace"]}),count:z.length+T.length+L.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(Bd,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Dd,{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:[E.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:E.nicknameInput,onChange:P=>E.setNicknameInput(P.target.value),onKeyDown:P=>{P.key==="Enter"&&E.handleSaveNickname(),P.key==="Escape"&&E.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:E.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>E.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{E.setEditingNickname(!0),E.setNicknameInput(K.machineNickname||"")},title:"Click to set nickname",children:Y}),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"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.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:ne.map(P=>s.jsxs("button",{onClick:()=>v(P.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${m===P.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[P.label,P.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${m===P.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:P.count})]},P.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(mb,{machineEntry:u,providers:M,recentLaunches:ve,currentConversations:V,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:me,onOpenConversation:H}),s.jsx(hb,{machine:K,machineId:t,providers:M,ideSessions:z,cliSessions:T,acpSessions:L,actions:E,getIcon:R,initialCategory:S,initialWorkspaceId:be,initialWorkspacePath:pe,sendDaemonCommand:a})]}),m==="providers"&&s.jsx(zx,{machineId:t,providers:M,sendDaemonCommand:a}),m==="overview"&&s.jsx(Bx,{machineId:t,machine:K,ideSessions:z,cliSessions:T,acpSessions:L,actions:E,sendDaemonCommand:a}),m==="session-host"&&s.jsx(db,{machineId:t,cliSessions:T,sendDaemonCommand:a}),m==="logs"&&s.jsx(rb,{machineId:t,sendDaemonCommand:a})]})})}),E.launchPick&&K&&s.jsx(ub,{machine:K,launchPick:E.launchPick,actions:E}),j&&s.jsx(Ga,{title:j.title,description:j.description,details:j.details,workspaceOptions:j.workspaceOptions,selectedWorkspaceKey:A,onWorkspaceChange:P=>{N.current=P,y(P)},confirmLabel:j.confirmLabel,busyLabel:j.busyLabel,busy:I,onConfirm:Z,onCancel:()=>{h.current=null,b(null)}}),s.jsx(Sc,{toasts:l.toasts||[],onDismiss:P=>l.setToasts(G=>G.filter(U=>U.id!==P)),onClickToast:P=>{P.targetKey&&r(Gt(P.targetKey))}}),s.jsx("style",{children:`
72
+ @keyframes toast-in {
73
+ from { opacity: 0; transform: translateX(40px); }
74
+ to { opacity: 1; transform: translateX(0); }
75
+ }
76
+ `})]})}function Xa(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function bb(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(bb(e),{credentials:"same-origin",...t})}function jl(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class gb{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 gb;function yb(){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=yb(),hi=3e3,vb=3e4;let Rt=null,wb=0;const qr=new Map;let Jt=null,Gs=null;function xi(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 jb(e){return e==="connected"?"connected":e}async function Er(e,t,r){const n=Ic(e,r||{}),a=Rt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++wb}_${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 kb(e,t,r){const n=Rt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Ic(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 Sb{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 Nb(e){return(!Mt||Mt.daemonId!==e)&&(Mt=new Sb(e)),Mt}function Cb({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(hi),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(A){console.error("[Standalone WS] Failed to create WebSocket:",A),h();return}f.current=j,j.onopen=()=>{if(!m.current){j.close();return}d("connected"),x.current=hi,Ks("open",{url:Mr,reason:S.current}),qt.resubscribeAll({sendData:da}),console.log("[Standalone WS] Connected")},Rt=j,j.onmessage=A=>{var y,I;try{const k=JSON.parse(A.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:E,getIdes:M}=t.current,C=w.instanceId||"standalone",R=M().find(T=>T.id===C),K=Nb(C);Wt.register(C,K),Wt.setState(C,"connected"),d("connected",C),Wt.emitStatus(C,w);const z=Fr(w,{daemonId:C,existingDaemon:R,existingEntries:M()});xi("ws_status",{type:k.type,daemonId:C,sessions:(w.sessions||[]).map(T=>({id:T.id,parentId:T.parentId,providerType:T.providerType,kind:T.kind,transport:T.transport,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,title:T.title})),recentLaunches:(w.recentLaunches||[]).map(T=>({id:T.id,providerType:T.providerType,kind:T.kind,workspace:T.workspace,lastLaunchedAt:T.lastLaunchedAt}))}),xi("entries",{daemonId:C,entries:z.filter(T=>T.type!=="adhdev-daemon").map(T=>({id:T.id,type:T.type,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,sessionId:T.sessionId}))}),z.length>0&&g(z,{authoritativeDaemonIds:[C]}),E(),c.current!==C&&((I=i.current)==null||I.call(i),c.current=C,i.current=qt.subscribe({sendData:da},C,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${C}`,params:{includeSessions:!0}},T=>{if(T.topic!=="daemon.metadata")return;const L=t.current.getIdes(),Y=L.find(D=>D.id===C),O=Fr(T.status,{daemonId:C,existingDaemon:Y,existingEntries:L,timestamp:T.timestamp});O.length>0&&t.current.injectEntries(O,{authoritativeDaemonIds:[C]}),T.userName&&a.current&&a.current(T.userName)}))}}catch(k){console.error("[Standalone WS] Parse error:",k)}},j.onclose=A=>{m.current&&(Mt==null||Mt.stopScreenshots(),Mt&&Wt.setState(Mt.daemonId,"disconnected"),d("disconnected"),f.current=null,S.current=`close:${A.code}${A.wasClean?":clean":":unclean"}`,Ks("close",{code:A.code,reason:A.reason||"",wasClean:A.wasClean}),h())},j.onerror=A=>{v.current||!m.current||(S.current="error",Ks("error",{message:A instanceof Event?"event":String(A),readyState:j.readyState}),console.warn("[Standalone WS] Error, will reconnect:",A))}}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,vb),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 Ib({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=jb(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(Nd,{connectionOverrides:i,children:s.jsx(Cb,{children:e})})}const kl="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"}],Mb=new Set(ln.map(e=>e.id)),Ab=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"?Mb:Ab).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 Tb(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=Tb(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(kl,JSON.stringify(t))}catch{}return t}function Lb(){try{const e=localStorage.getItem(kl);if(e)return Bt(JSON.parse(e))}catch{}return is}function Rb(){return Zt(Lb())}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 Pb=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Ai,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(ls,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(Yr,{}),label:"Settings"}];function _b({children:e}){const t=As(),r=pa(),n=o.useMemo(()=>Pb.map(i=>({...i,active:r.pathname.startsWith(i.path),onSelect:()=>t(i.path)})),[r.pathname,t]),a=o.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Li,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Ri,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Uf,{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.26"]}),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 Db=[{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(Pi,{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(Li,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Eb=[{icon:s.jsx(Od,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Ai,{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(_d,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Ti,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Ed,{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 Bb(){return s.jsxs(Lc,{icon:s.jsx(Ri,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.26"]}),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:Db.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:Mc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Tc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Ac.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(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:Eb.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(Pc,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(Xd,{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 Kb({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 Ob(){const{ides:e}=cs(),t=e.find(V=>V.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,A]=o.useState("127.0.0.1"),[y,I]=o.useState(""),[k,w]=o.useState(""),[g,E]=o.useState(""),[M,C]=o.useState(""),[R,K]=o.useState(""),[z,T]=o.useState(!1),L=async()=>{const H=await(await Et("/auth/session")).json();d(H)},Y=async()=>{const H=await(await Et("/api/v1/standalone/preferences")).json();u(H),A(H.standaloneBindHost);const Z=Bt(H.standaloneFontPreferences);m(Z),Zt(Z),ua(Z)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([L(),Y()]).catch(V=>{C(V instanceof Error?V.message:String(V))})},[]),o.useEffect(()=>{Zt(x)},[x]);const O=V=>{const H=V.target.value.trim();t!=null&&t.id&&H!==a&&n(t.id,"set_user_name",{userName:H}).catch(console.error)},[D,W]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),Q=V=>{W(V);try{localStorage.setItem("adhdev_sound",V?"1":"0")}catch{}},be=async()=>{h(""),b(""),S(!0);try{const V=Bt(x),H=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:V})}),Z=await H.json();if(!H.ok)throw new Error((Z==null?void 0:Z.error)||"Failed to save standalone font preferences");const me=Bt(Z.standaloneFontPreferences);u(Z),m(me),Zt(me),ua(me),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(V){h(V instanceof Error?V.message:String(V))}finally{S(!1)}},pe=()=>{const V=Bt(f==null?void 0:f.standaloneFontPreferences);h(""),b(""),m(V),Zt(V)},ue=()=>{h(""),b(""),m(is),Zt(is)},we=async()=>{C(""),K(""),T(!0);try{const V=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),H=await V.json();if(!V.ok)throw new Error((H==null?void 0:H.error)||"Failed to save standalone network preference");u(H),A(H.standaloneBindHost),K(H.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(V){C(V instanceof Error?V.message:String(V))}finally{T(!1)}},ye=async()=>{if(C(""),K(""),k.trim().length<4){C("Password must be at least 4 characters.");return}if(k!==g){C("New password and confirmation do not match.");return}T(!0);try{const V=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:k})}),H=await V.json();if(!V.ok)throw new Error((H==null?void 0:H.error)||"Failed to save password");d(H),await Y(),I(""),w(""),E(""),K(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),jl()}catch(V){C(V instanceof Error?V.message:String(V))}finally{T(!1)}},ve=async()=>{C(""),K(""),T(!0);try{const V=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),H=await V.json();if(!V.ok)throw new Error((H==null?void 0:H.error)||"Failed to clear password");d(H),await Y(),I(""),w(""),E(""),K("Standalone password disabled.")}catch(V){C(V instanceof Error?V.message:String(V))}finally{T(!1)}};return s.jsxs(Lc,{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.26"]}),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:()=>A("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:()=>A("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:()=>{we()},disabled:z,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:z?"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."}),M&&s.jsx(gr,{variant:"error",children:M}),R&&s.jsx(gr,{variant:"success",children:R}),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:V=>I(V.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:V=>w(V.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:V=>E(V.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{ye()},disabled:z,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:z?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ve()},disabled:z,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(V=>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 ${V.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:V.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:V.type})]},V.type))})}),s.jsx(St,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Zf,{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(rp,{})]}),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(up,{})]}),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(Kb,{value:x,savedValue:Bt(f==null?void 0:f.standaloneFontPreferences),saving:v,error:p,notice:j,onChange:m,onSave:()=>{be()},onResetToSaved:pe,onResetToDefaults:ue})]}),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(pp,{})]})]})}),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(Xf,{}),s.jsx(Qt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Yd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:D,onChange:Q})]})}),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(Pd,{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:V=>c(V.target.value),onBlur:O,onKeyDown:V=>{V.key==="Enter"&&V.currentTarget.blur()}})]})})})]})}Hf();lp();Rb();const Wb=Ci({baseUrl:"",getToken:Xa});function Hb({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(""),jl()}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 bi(){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 Fb(){const e=o.useMemo(()=>({sendCommand:Er,sendData:da,sendPtyInput:kb}),[]);return s.jsx(cd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Md,{client:Wb,children:s.jsx(Hb,{children:s.jsx(Ib,{children:s.jsx(Td,{value:e,children:s.jsx(_b,{children:s.jsxs(ld,{children:[s.jsx(Yt,{path:"/dashboard",element:s.jsx(Ex,{})}),s.jsx(Yt,{path:"/machine",element:s.jsx(bi,{})}),s.jsx(Yt,{path:"/machines/:id",element:s.jsx(xb,{})}),s.jsx(Yt,{path:"/machines",element:s.jsx(bi,{})}),s.jsx(Yt,{path:"/about",element:s.jsx(Bb,{})}),s.jsx(Yt,{path:"/settings",element:s.jsx(Ob,{})}),s.jsx(Yt,{path:"*",element:s.jsx(Vn,{to:"/dashboard",replace:!0})})]})})})})})})})}of({connectionManager:Wt});dd(document.getElementById("root")).render(s.jsx(Fb,{}));