@adhdev/daemon-standalone 0.9.44 → 0.9.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +408 -310
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/{index-CntBcmAq.js → index-Cp_MxwQG.js} +28 -28
- package/public/index.html +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-DbJP_JGY.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
var Jl=Object.defineProperty;var Ql=(e,t,r)=>t in e?Jl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var ze=(e,t,r)=>Ql(e,typeof t!="symbol"?t+"":t,r);import{r as o,j as s,M as ba,a as Zl,b as ed,c as td,u as Is,R as jt,d as Js,t as sd,e as rd,D as nd,f as qn,g as Yn,h as ga,i as ad,k as od,B as id,l as cd,m as Gt,N as Xn,n as ld}from"./vendor-BRZ4K-AC.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();function dd(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(a),r.length>t&&r.splice(0,r.length-t),a},list(n={}){const a=Math.max(1,Math.floor(n.limit||100));return r.filter(i=>!n.interactionId||i.interactionId===n.interactionId).filter(i=>!n.topic||i.topic===n.topic).filter(i=>!n.kind||i.kind===n.kind).slice(-a).map(i=>({...i,payload:i.payload?{...i.payload}:{}}))},clear(){r.splice(0,r.length)}}}const js=dd();function lo(e){const t={};for(const r of e)r.transport&&(t[r.transport]=(t[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:t}}function ud(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function md(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function wi(e,t){var m;if(!e)return t??null;if(!t)return e??null;const r=md(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:void 0,a=e.status==="waiting_approval"||Array.isArray((m=e.activeModal)==null?void 0:m.buttons)&&e.activeModal.buttons.length>0,i=r&&a&&(n==null?void 0:n.length)===0&&Array.isArray(t.messages)&&t.messages.length>0,c=r?i?t.messages:n??[]:t.messages,l=e.activeModal||(e.status==="waiting_approval"?t.activeModal:null),u={...t,...e,activeModal:l,inputContent:e.inputContent??t.inputContent};return r?{...u,messages:c}:u}function Fs(e,t){const r=ud(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(t==null?void 0:t.parentSessionId)??null,providerSessionId:e.providerSessionId??(t==null?void 0:t.providerSessionId),providerName:r??(t==null?void 0:t.providerName)??(t==null?void 0:t.cliName)??(t==null?void 0:t.type)??e.providerName??e.providerType,title:e.title??(t==null?void 0:t.title)??r??(t==null?void 0:t.providerName)??e.providerName??e.providerType,workspace:e.workspace??(t==null?void 0:t.workspace)??null,mode:e.mode??(t==null?void 0:t.mode),capabilities:e.capabilities??(t==null?void 0:t.sessionCapabilities)??(t==null?void 0:t.capabilities)??[],cdpConnected:e.cdpConnected??(t==null?void 0:t.cdpConnected),activeChat:wi(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 ji(e,t,r){if(!(t!=null&&t.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const n=t.map(a=>{const i=e.find(c=>c.id===a.id);return i?Fs(a,i):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(t.map(i=>i.id));for(const i of e)a.has(i.id)||n.push(i)}return n}function uo(e){return!!e&&typeof e=="object"&&"text"in e}function ya(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:uo(i)?String(i.text||""):"").join(r):uo(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function ks(e){return ya(e,{normalizeWhitespace:!0})}const ki=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}),Si=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function mo(e){var r,n;let t=0;return e.activeChat!==void 0&&(t+=4),(r=e.childSessions)!=null&&r.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(n=e.agents)!=null&&n.length&&(t+=1),t}function Ni(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,i=t.serverVersion??e.serverVersion??r.serverVersion,c=t.versionMismatch===!0||e.versionMismatch===!0,l=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,u=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),i&&(n.serverVersion=i),u&&(n.versionUpdateReason=u),a&&i&&a===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||c&&a&&i&&a!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function fd(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function mn(e){if(!e||typeof e!="object")return"";const t=e,r=fd(ks(t.content).slice(0,512));return[String(t.id||""),String(t._localId||""),String(t._turnKey||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),r].join(":")}function pd(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=mn(n);for(let i=0;i<a.length;i+=1)r^=a.charCodeAt(i),r=Math.imul(r,16777619)>>>0}return{count:e.length,hash:r.toString(16).padStart(8,"0"),first:mn(e[0]),last:mn(e[e.length-1])}}function Jn(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(Jn(e)&&Jn(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 zs(e,t){return Array.isArray(e)?e.map(r=>zs(r,t)):!e||typeof e!="object"?e:Jn(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?pd(a,t):zs(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,zs(n,t)]))}function hd(e,t){try{const r=new WeakSet;return Qn(e,t,r),JSON.stringify(zs(e,r))===JSON.stringify(zs(t,r))}catch{return!1}}function Zn(e,t,r){return hd(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Ci(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function xd(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function fo(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,i=ji(e.childSessions,t.childSessions,{preserveMissing:n}),c=wi(t.activeChat,e.activeChat);return Ni(e,t,{...e,...t,chats:a,childSessions:i,activeChat:c,_lastUpdate:r})}function bd(e,t,r){var a,i;const n={};t.status&&t.status!==e.status&&(n.status=t.status),t.cdpConnected!==void 0&&(n.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(n.childSessions=ji(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((i=e.chats)!=null&&i.length)&&(n.chats=t.chats);for(const c of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion"])xd(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function gd(e,t,r,n){const a=bd(e,t,n),i=Object.keys(a).length>0?Ni(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return Zn(e,i,r)}function yd(e){const t=new Set(e.map(i=>i.id)),r=new Set,n=new Set,a=new Set;for(const i of e){const c=Ci(i);c&&r.add(c),c&&i.type!=="adhdev-daemon"&&n.add(c),c&&i.type==="adhdev-daemon"&&i._sessionListAuthoritative&&a.add(c)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function vd(e,t,r,n,a,i){return!a.has(t)||!i.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function wd(e,t,r,n){return!!(r.has(t)&&e.transport&&!n.has(t))}function jd(e,t,r){var d,h;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(f=>({...f,_lastUpdate:n}));const i=new Map;for(const f of t)i.set(f.id,f);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:u,daemonIdsWithAuthoritativeSessionList:m}=yd(e);for(const f of e){const j=i.get(f.id);if(!j){i.set(f.id,{...f,_lastUpdate:n});continue}const N=mo(f),p=mo(j),x=Ci(f),y=!a.has(x);if(N>p){const I=fo(j,f,n,y);i.set(f.id,Zn(j,I,n));continue}if(N<p){i.set(f.id,gd(j,f,n,y));continue}const g=f.timestamp||n,C=j._lastUpdate||j.timestamp||0;if(g>=C){const I=fo(j,f,n,y);i.set(f.id,Zn(j,I,n));continue}(d=f.chats)!=null&&d.length&&!((h=j.chats)!=null&&h.length)&&i.set(f.id,{...j,chats:f.chats})}for(const[f,j]of i){const N=j.daemonId||f.split(":")[0];if(!l.has(N))continue;if(a.has(N)&&m.has(N)&&!c.has(f)){i.delete(f);continue}const p=n-(j._lastUpdate||j.timestamp||0);vd(j,N,p,c,a,u)&&i.delete(f)}for(const[f,j]of i){const N=j.daemonId||f.split(":")[0];if(wd(j,N,l,u))continue;n-(j._lastUpdate||j.timestamp||0)>3e5&&j.status!=="online"&&i.delete(f)}return Array.from(i.values())}function kd(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Sd({children:e,connectionOverrides:t}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[u,m]=o.useState(void 0),d=o.useRef(r);o.useEffect(()=>{d.current=r},[r]);const h=o.useCallback((y,g)=>{n(C=>{let I=!1;const v=C.map(T=>T.id!==y||T.chats===g?T:(I=!0,{...T,chats:g}));return I?v:C})},[]),f=o.useCallback((y,g)=>{n(C=>{const I=C.length===0?y:jd(y,C,g),v=!kd(C,I);return v&&js.record({kind:"dashboard.entries_applied",payload:{incoming:lo(y),next:lo(I)}}),v?I:C})},[]),j=o.useCallback(()=>i(!0),[]),N=o.useMemo(()=>({injectEntries:f,markLoaded:j,getIdes:()=>d.current}),[f,j]),p=t,x=o.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(p==null?void 0:p.wsStatus)??"connected",isConnected:(p==null?void 0:p.isConnected)??!0,connectionStates:(p==null?void 0:p.connectionStates)??{},connectionTransports:(p==null?void 0:p.connectionTransports)??{},showReconnected:(p==null?void 0:p.showReconnected)??!1,retryConnection:p==null?void 0:p.retryConnection,retryServerConnection:p==null?void 0:p.retryServerConnection,connectionLoginUrl:p==null?void 0:p.connectionLoginUrl,isP2PActive:(p==null?void 0:p.isP2PActive)??!1,p2pStates:(p==null?void 0:p.p2pStates)??{},userRole:p==null?void 0:p.userRole,userName:u,setUserName:m}),[r,h,a,c,p==null?void 0:p.wsStatus,p==null?void 0:p.isConnected,p==null?void 0:p.connectionStates,p==null?void 0:p.connectionTransports,p==null?void 0:p.showReconnected,p==null?void 0:p.retryConnection,p==null?void 0:p.retryServerConnection,p==null?void 0:p.connectionLoginUrl,p==null?void 0:p.isP2PActive,p==null?void 0:p.p2pStates,p==null?void 0:p.userRole,u]);return s.jsx(Si.Provider,{value:N,children:s.jsx(ki.Provider,{value:x,children:e})})}function os(){return o.useContext(ki)}function Qs(){return o.useContext(Si)}function Mi(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function i(l){const u=r==null?void 0:r(),m=a(l),d=l.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return u&&d.searchParams.set("token",u),!l.startsWith("http")&&!t?`${d.pathname}${d.search}${d.hash}`:d.toString()}async function c(l,u={}){const m={"Content-Type":"application/json",...u.headers||{}},d=r==null?void 0:r();d&&(m.Authorization=`Bearer ${d}`);const h=a(l),f=new AbortController,j=setTimeout(()=>f.abort(),15e3);try{const N=await fetch(h,{...u,headers:m,signal:f.signal});if(N.status===401)throw n==null||n(),new Error("Unauthorized");if(!N.ok){const p=await N.json().catch(()=>({error:N.statusText}));throw new Error(p.error||`API Error: ${N.status}`)}return N.json()}finally{clearTimeout(j)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,u,m={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:m})}),execTerminal:(l,u,m)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:m})}),sendAgentMessage:(l,u,m)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:m})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,m)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:m?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,u,m={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:m})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Nd=Mi({baseUrl:"http://localhost:3847"}),Cd=o.createContext(Nd);function Md({client:e,children:t}){return s.jsx(Cd.Provider,{value:e,children:t})}const Td={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Ti=o.createContext(Td);function Id({value:e,children:t}){return s.jsx(Ti.Provider,{value:e,children:t})}function wt(){return o.useContext(Ti)}function Ad(e){let t=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)t^=n.charCodeAt(a),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function Ld(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Ii(e){return e?Ad([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Ld(e.content)]):""}const De={size:18};function Ai({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 va({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function is({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function Li({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Rd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function _d({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function Ri({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 Pd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Xr({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function _i({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Dd({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Wt({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function St({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function wa({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("polyline",{points:"14 2 14 8 20 8"}),s.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),s.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Ed({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Ss({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function nr({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function Zs({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function er({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function Pi({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"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 Di({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 Ei({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function $d({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 ja({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Bd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function ka({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function $i({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function vt({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Kd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),s.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),s.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),s.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Od({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Wd({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function Hd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function Jr({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Fd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"5"}),s.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),s.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),s.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),s.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),s.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),s.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),s.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),s.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function Ud({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function zd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Vd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Gd({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function qd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function Yd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function Xd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function Jd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Qd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function Zd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function eu({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const Bi=[Zl,{singleTilde:!1}],Ki=[Bi,ed,td],tu=[Bi],Sa=200,su=80,po=650,Ps=new Map;function Br(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function ru(e,t){if(!Array.isArray(e)||e.length===0)return"0:empty";const r=String(t||"").trim();if(r)return`${e.length}:${r}`;const n=e[e.length-1];return`${e.length}:${Ii(n)}`}function nu(e,t,r,n){return e||!t?!1:Br(r,n)}function au({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=su,bottomThresholdPx:a=Sa}){const i=Math.max(0,Number(e)||0),c=Math.max(0,Number(t)||0),l=Math.max(0,Number(r)||0);return Math.max(0,c-l)<=0?{showTop:!1,showBottom:!1}:{showTop:i>n,showBottom:Math.max(0,c-i-l)>a}}function ou(e){return au({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Us(e,t=Sa){return!!e&&e.fromBottom>=t}function iu(e,t){return Br(e,t)?!Us(e):!0}function cu({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function lu({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function fn(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function Oi(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function du(e,t,r){return Number(e.receivedAt||r[Kr(e,t)]||0)||0}function Wi(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function uu(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function ur(e,t){if(!e)return t;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||t}catch{return e.split(/[\\/]/).filter(Boolean).pop()||t}}function pn(e){if(typeof e.uri=="string"&&e.uri)return e.uri;if(typeof e.data=="string"&&e.data&&typeof e.mimeType=="string"&&e.mimeType)return`data:${e.mimeType};base64,${e.data}`}function ho(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Wi(e)?s.jsx(ba,{remarkPlugins:Ki,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=pn(r);return a?s.jsx("img",{src:a,alt:ur(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=pn(r);return a?s.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=pn(r);return a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:ur(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||ur(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=ur(r.resource.uri,"resource");if(r.resource.text)return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[s.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),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=ya(e.content,{joiner:`
|
|
3
|
-
`});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${t}`].filter(Boolean).join("|")}const
|
|
4
|
-
`});if(d==="thought"){const b=typeof((T=t.meta)==null?void 0:T.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(Wd,{size:13}),s.jsx("span",{children:b})]}),s.jsx("div",{className:"chat-msg-body",children:j})]})}if(d==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),f&&h?s.jsx("div",{className:"tool-text w-full",children:s.jsx(mr,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:j})]});if(d==="terminal"){const b=(S=t.meta)!=null&&S.isRunning?"⏳":"✅",B=typeof((k=t.meta)==null?void 0:k.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:b}),s.jsx("span",{children:B})]}),f&&h?s.jsx("div",{className:"chat-msg-body",children:s.jsx(mr,{parts:h,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:j})]})}if(d==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:f&&h?s.jsx(mr,{parts:h,renderAsPreformatted:!1}):j.slice(0,100)});const N=t.meta,x=(typeof(N==null?void 0:N.renderMode)=="string"?N.renderMode.trim():"")==="preformatted",y=j,g=!1,C=y,I=x,v=!I&&Wi(C);return s.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${m?"self-end":"self-start"}`,children:(y||f||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${y||f?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:m?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:Oi(r)})]}),(y||f)&&s.jsx("div",{className:"chat-markdown",children:f&&h?s.jsx(mr,{parts:h,renderAsPreformatted:I}):I?s.jsx("pre",{className:"chat-preformatted",children:C}):v?s.jsx(ba,{remarkPlugins:Ki,children:C}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:C})}),g]})})},(e,t)=>e.message===t.message&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),pu=o.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},lastMessageHash:m,emptyState:d,onLoadMore:h,isLoadingMore:f,hasMoreHistory:j,hiddenLiveCount:N=0,loadError:p,scrollToBottomRequestNonce:x,isVisible:y=!0},g){const C=o.useRef(null),I=o.useRef(null),v=o.useRef(null),T=o.useRef(0),S=o.useRef(""),k=o.useRef(""),b=o.useRef(!1),B=o.useRef(null),L=o.useRef(!1),_=o.useRef(null),H=o.useRef(!1),[F,O]=o.useState(new Set),[M,A]=o.useState({showTop:!1,showBottom:!1}),U=o.useRef(!1),$=o.useRef(!1),E=o.useRef(y),z=o.useRef(y),Y=o.useRef(null);z.current=y;const ve=()=>{const X=C.current;return X?X.scrollHeight-X.scrollTop-X.clientHeight<Sa:!0},re=o.useCallback(()=>{const X=C.current,J=X?ou(X):{showTop:!1,showBottom:!1};A(de=>de.showTop===J.showTop&&de.showBottom===J.showBottom?de:J)},[]),ye=o.useCallback((X="auto")=>{var de;const J=C.current;J&&(J.scrollTo({top:J.scrollHeight,behavior:X}),(de=J.ownerDocument.defaultView)==null||de.requestAnimationFrame(()=>re()))},[re]),le=o.useCallback((X="auto")=>{var de;const J=C.current;J&&(J.scrollTo({top:0,behavior:X}),(de=J.ownerDocument.defaultView)==null||de.requestAnimationFrame(()=>re()))},[re]),be=o.useCallback(()=>{var ie;const X=C.current,J=(ie=window.getSelection)==null?void 0:ie.call(window);if(!X||!J||J.rangeCount===0||J.isCollapsed){H.current=!1;return}const de=J.anchorNode,D=J.focusNode;H.current=!!(de&&D&&X.contains(de)&&X.contains(D))},[]),ge=ru(t,m),G=o.useCallback(()=>{const X=C.current;if(!X||!l||!z.current)return;const J={top:X.scrollTop,fromBottom:Math.max(0,X.scrollHeight-X.scrollTop-X.clientHeight),messageFingerprint:ge};Y.current={contextKey:l,snapshot:J},Ps.set(l,J)},[l,ge]),ne=o.useCallback((X="auto")=>{B.current!=null&&cancelAnimationFrame(B.current),B.current=requestAnimationFrame(()=>{B.current=null,ye(X)})},[ye]),q=o.useCallback(()=>{U.current=!1,L.current=!0,$.current=!0,_.current!=null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{L.current=!1,_.current=null},po)},[]);o.useEffect(()=>{const X=!b.current,J=k.current!==l;if(k.current=l,X||J){b.current=!0;const D=l?Ps.get(l):null,ie=!!D&&Br(D,ge);U.current=ie?Us(D):!1,L.current=iu(D,ge),H.current||(ie?requestAnimationFrame(()=>{const Q=C.current;Q&&(fn(Q,D),U.current=Us(D),re(),$.current=!0)}):ne("auto")),T.current=t.length,S.current=ge;return}t.length>T.current;const de=ge!==S.current;cu({hasSelection:H.current,userScrolledUp:U.current,hasChatContentChanged:de})&&ne("auto"),T.current=t.length,S.current=ge},[ge,l,t.length,ne,re]),o.useEffect(()=>{x&&(q(),H.current||ne("auto"))},[q,ne,x]),o.useEffect(()=>{const X=E.current;X&&!y&&G(),z.current=y,E.current=y;const J=l?Ps.get(l):null;if(nu(X,y,J,ge)){if(!J)return;U.current=Us(J),L.current=!1,H.current||requestAnimationFrame(()=>{const de=C.current;de&&(fn(de,J),re())});return}},[y,l,ge,q,G,ne,re]),o.useEffect(()=>()=>{const X=Y.current;X&&Ps.set(X.contextKey,X.snapshot),B.current!=null&&cancelAnimationFrame(B.current),_.current!=null&&window.clearTimeout(_.current)},[]),o.useEffect(()=>{const X=I.current,J=C.current;if(!X||!J)return;const de=()=>{_.current!=null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{L.current=!1,_.current=null},po)},D=new ResizeObserver(()=>{re();const ie=L.current;lu({hasSelection:H.current,userScrolledUp:U.current,contextAutoScrollActive:ie})&&(ne("auto"),ie&&de())});return D.observe(X),J!==X&&D.observe(J),()=>{D.disconnect(),_.current!=null&&(window.clearTimeout(_.current),_.current=null)}},[ne,l,re]),o.useImperativeHandle(g,()=>({scrollToBottom:(X="smooth")=>{ye(X)}}),[ye]),o.useEffect(()=>{const X=C.current;if(!X)return;let J;const de=()=>{G(),clearTimeout(J),J=setTimeout(()=>{U.current=!ve(),re()},50)};return X.addEventListener("scroll",de,{passive:!0}),()=>{X.removeEventListener("scroll",de),clearTimeout(J)}},[G,re]),o.useEffect(()=>(document.addEventListener("selectionchange",be),()=>document.removeEventListener("selectionchange",be)),[be]);const ue=o.useRef(0),ce=o.useRef(!1);o.useEffect(()=>{const X=C.current;if(!X||!ce.current||ue.current===0)return;const J=X.scrollHeight-ue.current;J>0&&(X.scrollTop=J),re(),G(),ue.current=0,ce.current=!1},[t.length,G,re]),o.useEffect(()=>{if($.current||!l)return;const X=Ps.get(l),J=C.current;if(!(!X||!J)){if(!Br(X,ge)){ye("auto"),$.current=!0;return}fn(J,X),U.current=Us(X),re(),$.current=!0}},[l,ge,t.length,ye,re]);const je=()=>{const X=C.current;X&&(ue.current=X.scrollHeight),ce.current=!0,h==null||h()},ae=()=>{U.current=!0,le("smooth"),G()},fe=()=>{q(),ye("smooth"),G()},oe=o.useMemo(()=>{const X=t.map((ie,Q)=>({type:"message",data:ie,index:Q,ts:du(ie,Q,u)}));if(!r||r.length===0)return X;const J=[...r].sort((ie,Q)=>ie.timestamp-Q.timestamp).map((ie,Q)=>({type:"action",data:ie,index:Q,ts:ie.timestamp})),de=[];let D=0;for(const ie of X){for(;D<J.length&&ie.ts>0&&J[D].ts<ie.ts;)de.push(J[D++]);de.push(ie)}for(;D<J.length;)de.push(J[D++]);return de},[t,r,u]),te=N>0||!!j,ee=N>0?`↑ Show ${Math.min(N,80)} earlier messages${N>80?` (${N} hidden)`:""}`:p?`↻ ${p}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:C,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:I,className:"chat-container-content",children:[f&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),te&&!f&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:je,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${p&&N===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:ee})}),oe.length===0&&!te&&(d||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),oe.map(X=>{if(X.type==="action"){const Ne=X.data;return s.jsx(mu,{log:Ne},`action-${X.index}`)}const J=X.data,de=X.index,D=Kr(J,de),ie=J.receivedAt||u[D],Q=`${l}-${D}`,we=F.has(Q);return s.jsx(fu,{message:J,receivedAt:ie,agentName:n,userName:a,isCliMode:i,isTextExpanded:we,onToggleTextExpanded:()=>O(Ne=>{const Ae=new Set(Ne);return we?Ae.delete(Q):Ae.add(Q),Ae})},`msg-${D}`)}),c&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),s.jsx("div",{className:"min-h-10",ref:v})]})}),(M.showTop||M.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[M.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:ae,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),M.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:fe,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),hu=o.memo(pu,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.lastMessageHash===t.lastMessageHash&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible),xu="modulepreload",bu=function(e){return"/"+e},xo={},gu=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=Promise.allSettled(r.map(u=>{if(u=bu(u),u in xo)return;xo[u]=!0;const m=u.endsWith(".css"),d=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const h=document.createElement("link");if(h.rel=m?"stylesheet":xu,m||(h.as="script"),h.crossOrigin="",h.href=u,l&&h.setAttribute("nonce",l),document.head.appendChild(h),m)return new Promise((f,j)=>{h.addEventListener("load",f),h.addEventListener("error",()=>j(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};let bo=!1;const Hi=o.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:i="measured"},c)=>{const l=o.useRef(null),[u,m]=o.useState(null),d=o.useRef([]),h=o.useRef(!1),f=o.useRef(!1),j=o.useRef(!1),N=o.useRef(!1),p=()=>{const x=l.current;if(x){h.current&&(x.clear(),h.current=!1);for(const y of d.current)x.write(y.data,y.onProcessed);d.current=[],f.current&&(x.fit(),f.current=!1),j.current&&(x.bumpResize(),j.current=!1),N.current&&(x.scrollToTop(),N.current=!1)}};return o.useImperativeHandle(c,()=>({write:(x,y)=>{l.current?l.current.write(x,y):d.current.push({data:x,onProcessed:y})},clear:()=>{l.current?l.current.clear():(d.current=[],h.current=!0)},reset:()=>{l.current&&typeof l.current.reset=="function"?l.current.reset():(d.current=[],h.current=!0)},resize:(x,y)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(x,y)},fit:()=>{l.current?l.current.fit():f.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():j.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():N.current=!0},getSelection:()=>{var x,y;return((y=(x=l.current)==null?void 0:x.getSelection)==null?void 0:y.call(x))||""},getVisibleText:()=>{var x,y;return((y=(x=l.current)==null?void 0:x.getVisibleText)==null?void 0:y.call(x))||""}}),[]),o.useEffect(()=>{u&&p()},[u]),o.useEffect(()=>{let x=!1;return gu(()=>import("./terminal-DbJP_JGY.js"),__vite__mapDeps([0,1,2])).then(y=>{bo||(bo=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),x||m(()=>y.GhosttyTerminalView)}).catch(y=>{console.error("[CliTerminal] failed to load terminal renderer",y)}),()=>{x=!0}},[]),u?s.jsx(u,{ref:l,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:i,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Hi.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 yu({cursorPos:e,viewportRef:t,imgRef:r}){var g;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(g=t.current)==null?void 0:g.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,u=c/l,m=a.width/a.height;let d,h,f,j;u>m?(d=a.width,h=a.width/u,f=0,j=(a.height-h)/2):(h=a.height,d=a.height*u,f=(a.width-d)/2,j=0);const N=a.left-i.left+f+d*e.nx,p=a.top-i.top+j+h*e.ny,x=Math.max(8,Math.min(i.width-8,N)),y=Math.max(8,Math.min(i.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:x-8,top:y-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function vu({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:m,zoom:d,isMobile:h,mobileFillZoom:f,onZoomOut:j,onZoomReset:N,onZoomIn:p,transportType:x,screenshotUsage:y,lastActionStatus:g}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:C=>C.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(C=>!C),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:C=>C.stopPropagation(),onChange:C=>l(C.target.value),onKeyDown:C=>{u(C)},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(C=>!C),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:m?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),d>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),x==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),x==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),y&&y.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:y.budgetExhausted?"TURN blocked":`TURN ${y.dailyUsedMinutes}/${y.dailyBudgetMinutes}m`}),g&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:g})]})]}),a&&s.jsxs("div",{onTouchStart:C=>C.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",d<=(h?f:1)+.01?h?"FILL":"FIT":`${Math.round(d*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:C=>{C.stopPropagation(),j()},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:C=>{C.stopPropagation(),N()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:h?"FILL":"FIT"}),s.jsx("button",{onClick:C=>{C.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 wu({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 ju(){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 ar(e,t){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!ju())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 ku({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:m,setPanY:d,setZoom:h,lastWheelTimeRef:f,onAction:j,setLastActionStatus:N,spawnRippleFromNormalized:p,clampPan:x,isMobile:y,mobileFillZoom:g}){const[C,I]=o.useState(null),v=o.useRef(null),T=o.useRef(null),S=o.useRef(null),k=o.useRef(!1),b=o.useRef(null),B=o.useRef(0),L=o.useRef(null),_=o.useRef(1),H=o.useRef({x:0,y:0}),F=o.useRef(!1),O=o.useRef(n),M=o.useRef(j),A=30,U=550,$=18,E=60,z=400,Y=12,ve=()=>{if(v.current)return;const le={nx:.5,ny:.5};v.current=le,I(le)};return o.useEffect(()=>{O.current=n,n==="mouse"&&ve()},[n]),o.useEffect(()=>{M.current=j},[j]),o.useEffect(()=>{const le=e.current;if(!le)return;const be=ce=>{if(!r.current)return null;const je=r.current.getBoundingClientRect();return!je.width||!je.height?null:{nx:Math.max(0,Math.min(1,(ce.clientX-je.left)/je.width)),ny:Math.max(0,Math.min(1,(ce.clientY-je.top)/je.height))}},ge=(ce,je)=>{if(!r.current)return{dnx:0,dny:0};const ae=r.current,fe=ae.getBoundingClientRect(),oe=ae.naturalWidth||fe.width,te=ae.naturalHeight||fe.height,ee=oe/te,X=fe.width/fe.height;let J,de;return ee>X?(J=fe.width,de=fe.width/ee):(de=fe.height,J=fe.height*ee),{dnx:ce/J,dny:je/de}},G=(ce,je,ae)=>{if(ae<=1.05)return;const fe=-(ce-.5)*100,oe=-(je-.5)*100,te=x(fe,oe,ae);(Math.abs(te.x-l.current)>.1||Math.abs(te.y-u.current)>.1)&&(m(te.x),d(te.y),l.current=te.x,u.current=te.y)},ne=ce=>{const je=t.current;if(je&&ce.target instanceof Node&&je.contains(ce.target))ce.preventDefault();else return;if(ce.touches.length===1){const ae=ce.touches[0];T.current={x:ae.clientX,y:ae.clientY,time:Date.now()},S.current={x:ae.clientX,y:ae.clientY},F.current||(k.current=!1),b.current=setTimeout(()=>{if(!k.current&&!F.current)if(k.current=!0,O.current==="mouse"){const fe=v.current||{nx:.5,ny:.5};N("Right Click"),p(fe.nx,fe.ny,"right"),M.current("input_click",{...fe,button:"right"}).catch(()=>{})}else{const fe=be(ae);fe&&(N("Right Click"),p(fe.nx,fe.ny,"right"),M.current("input_click",{...fe,button:"right"}).catch(()=>{}))}},500);return}if(ce.touches.length===2){b.current&&clearTimeout(b.current),k.current=!0,F.current=!0;const ae=ce.touches[1].clientX-ce.touches[0].clientX,fe=ce.touches[1].clientY-ce.touches[0].clientY;L.current=Math.sqrt(ae*ae+fe*fe),_.current=c.current,H.current={x:(ce.touches[0].clientX+ce.touches[1].clientX)/2,y:(ce.touches[0].clientY+ce.touches[1].clientY)/2}}},q=ce=>{const je=t.current;if(je&&ce.target instanceof Node&&je.contains(ce.target)&&ce.preventDefault(),ce.touches.length===1&&S.current){const ae=ce.touches[0],fe=ae.clientX-S.current.x,oe=ae.clientY-S.current.y;if(!k.current&&T.current){const te=ae.clientX-T.current.x,ee=ae.clientY-T.current.y;Math.sqrt(te*te+ee*ee)>8&&(k.current=!0,b.current&&clearTimeout(b.current))}if(k.current)if(O.current==="mouse"){const te=ge(fe,oe),ee=v.current||{nx:.5,ny:.5},X=Math.max(0,Math.min(1,ee.nx+te.dnx)),J=Math.max(0,Math.min(1,ee.ny+te.dny));v.current={nx:X,ny:J},I({nx:X,ny:J}),N(`Cursor: ${Math.round(X*100)}%, ${Math.round(J*100)}%`),G(X,J,c.current);const de=Date.now();de-f.current>=30&&(f.current=de,M.current("input_mouseMoved",{nx:X,ny:J}).catch(()=>{}))}else if(c.current>1){const te=t.current;if(te){const ee=te.clientWidth,X=te.clientHeight,J=l.current+fe/ee*100,de=u.current+oe/X*100,D=x(J,de,c.current);m(D.x),d(D.y),l.current=D.x,u.current=D.y}}else{const te=be(ae);if(te){const ee=Date.now();ee-f.current>=40&&(f.current=ee,N("Scroll"),M.current("input_wheel",{nx:te.nx,ny:te.ny,deltaX:Math.round(-fe*2.5),deltaY:Math.round(-oe*2.5)}).catch(()=>{}))}}S.current={x:ae.clientX,y:ae.clientY};return}if(ce.touches.length===2&&L.current!==null){const ae=ce.touches[1].clientX-ce.touches[0].clientX,fe=ce.touches[1].clientY-ce.touches[0].clientY,te=Math.sqrt(ae*ae+fe*fe)/L.current,ee=(ce.touches[0].clientX+ce.touches[1].clientX)/2,X=(ce.touches[0].clientY+ce.touches[1].clientY)/2,J=ee-H.current.x,de=X-H.current.y,D=Math.abs(te-1)>.03;if(O.current==="mouse"){if(D){const ie=Math.max(i,Math.min(5,_.current*te));h(ie),c.current=ie}else if(Math.abs(J)>2||Math.abs(de)>2){const ie=v.current||{nx:.5,ny:.5},Q=Date.now();Q-f.current>=30&&(f.current=Q,N("Scroll"),M.current("input_wheel",{nx:ie.nx,ny:ie.ny,deltaX:Math.round(-J*3),deltaY:Math.round(-de*3)}).catch(()=>{}))}}else{const ie=Math.max(i,Math.min(5,_.current*te));h(ie),c.current=ie;const Q=t.current;if(Q&&ie>1){const we=Q.clientWidth,Ne=Q.clientHeight,Ae=l.current+J/we*100,Te=u.current+de/Ne*100,Ue=x(Ae,Te,ie);m(Ue.x),d(Ue.y),l.current=Ue.x,u.current=Ue.y}}H.current={x:ee,y:X}}},ue=ce=>{var je;if(b.current&&clearTimeout(b.current),L.current=null,ce.touches.length===1&&F.current){const ae=ce.touches[0];T.current={x:ae.clientX,y:ae.clientY,time:Date.now()},S.current={x:ae.clientX,y:ae.clientY},k.current=!0;return}if(ce.touches.length===0){if(F.current){F.current=!1,k.current=!1;return}if(ce.changedTouches.length===1){const ae=ce.changedTouches[0],fe=Date.now(),oe=fe-(((je=T.current)==null?void 0:je.time)||0),te=T.current?ae.clientX-T.current.x:0,ee=T.current?ae.clientY-T.current.y:0,X=Math.sqrt(te*te+ee*ee);if(O.current==="mouse"){if(oe<A||oe>U||X>$){k.current=!1;return}const J=v.current||be(ae);J&&(N(`Click: ${Math.round(J.nx*100)}%, ${Math.round(J.ny*100)}%`),p(J.nx,J.ny,"left"),M.current("input_click",{...J}).catch(()=>{}))}else{if(k.current){k.current=!1;return}if(oe<E||oe>z||X>Y){k.current=!1;return}const J=be(ae);if(!J)return;fe-B.current<300?(N("Double tap"),p(J.nx,J.ny,"double"),M.current("input_click",{...J,clickCount:2}).catch(()=>{}),B.current=0):(N(`Tap: ${Math.round(J.nx*100)}%, ${Math.round(J.ny*100)}%`),p(J.nx,J.ny,"left"),M.current("input_click",{...J}).catch(()=>{}),B.current=fe)}}k.current=!1}};return le.addEventListener("touchstart",ne,{passive:!1}),le.addEventListener("touchmove",q,{passive:!1}),le.addEventListener("touchend",ue,{passive:!1}),()=>{le.removeEventListener("touchstart",ne),le.removeEventListener("touchmove",q),le.removeEventListener("touchend",ue),b.current&&clearTimeout(b.current)}},[e,t,r,i,c,l,u,m,d,h,f,N,p,x]),{cursorPos:C,cursorPosRef:v,handleToggleInputMode:()=>{a(le=>{const be=le==="touch"?"mouse":"touch";return be==="mouse"&&ve(),be})},handleZoomReset:()=>{const le=y?g:1;h(le),c.current=le,m(0),d(0),l.current=0,u.current=0}}}function Fi({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),u=o.useRef(null),[m,d]=o.useState(null),[h,f]=o.useState(""),[,j]=o.useState(!1),[N,p]=o.useState([]),x=o.useRef(0),[y,g]=o.useState(!1),[C,I]=o.useState(!1),v=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[T,S]=o.useState(v?"mouse":"touch"),[k,b]=o.useState(1),B=o.useRef(!1),[L,_]=o.useState(1),[H,F]=o.useState(0),[O,M]=o.useState(0);ar("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:T,zoom:L,panX:H,panY:O,isMenuOpen:y,isImeOpen:C});const A=o.useRef(0),U=o.useRef(L),$=o.useRef(H),E=o.useRef(O);o.useEffect(()=>{U.current=L},[L]),o.useEffect(()=>{$.current=H},[H]),o.useEffect(()=>{E.current=O},[O]),o.useEffect(()=>{var oe;(oe=c.current)==null||oe.focus()},[]);const z=r==="connected",Y=n,ve=z?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",re=z?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!v||B.current||!Y)return;const oe=u.current,te=l.current;if(!oe||!te)return;const ee=()=>{const X=te.clientWidth,J=te.clientHeight,de=oe.naturalWidth,D=oe.naturalHeight;if(!de||!D||!X||!J)return;const ie=Math.min(X/de,J/D),we=Math.max(X/de,J/D)/ie;we>1.01&&(b(we),_(we),U.current=we),B.current=!0};oe.complete&&oe.naturalWidth?ee():oe.addEventListener("load",ee,{once:!0})},[Y,v]);const ye=.5;o.useEffect(()=>{L<=ye&&(F(0),M(0))},[L,ye]);const le=(oe,te,ee)=>{if(ee<=ye)return{x:0,y:0};const X=(ee-1)/(2*ee)*100,J=(ee-1)/(2*ee)*100;return{x:Math.max(-X,Math.min(X,oe)),y:Math.max(-J,Math.min(J,te))}},be=(oe,te)=>{if(!u.current)return null;const ee=u.current.getBoundingClientRect();return!ee.width||!ee.height?null:{nx:Math.max(0,Math.min(1,(oe-ee.left)/ee.width)),ny:Math.max(0,Math.min(1,(te-ee.top)/ee.height))}},ge=(oe,te,ee)=>{const X=l.current;if(!X)return;const J=X.getBoundingClientRect(),de=++x.current;p(D=>[...D,{id:de,x:oe-J.left,y:te-J.top,type:ee}]),setTimeout(()=>p(D=>D.filter(ie=>ie.id!==de)),600)},G=(oe,te,ee)=>{const X=u.current,J=l.current;if(!X||!J)return;const de=X.getBoundingClientRect(),D=J.getBoundingClientRect(),ie=X.naturalWidth||de.width,Q=X.naturalHeight||de.height,we=ie/Q,Ne=de.width/de.height;let Ae,Te,Ue,We;we>Ne?(Ae=de.width,Te=de.width/we,Ue=0,We=(de.height-Te)/2):(Te=de.height,Ae=de.height*we,Ue=(de.width-Ae)/2,We=0);const Ke=de.left-D.left+Ue+Ae*oe,Ge=de.top-D.top+We+Te*te,Ze=++x.current;p(Je=>[...Je,{id:Ze,x:Ke,y:Ge,type:ee}]),setTimeout(()=>p(Je=>Je.filter(Ye=>Ye.id!==Ze)),600)},ne=async oe=>{var ee;const te=be(oe.clientX,oe.clientY);if(te){d(`Click: ${Math.round(te.nx*100)}%, ${Math.round(te.ny*100)}%`),ge(oe.clientX,oe.clientY,"left"),(ee=c.current)==null||ee.focus();try{const X=await e("input_click",{nx:te.nx,ny:te.ny});X!=null&&X.success||t(`❌ Click failed: ${X==null?void 0:X.error}`)}catch(X){t(`❌ Click error: ${X.message||X}`)}}},q=async(oe,te,ee,X=0)=>{try{await e("input_key",{type:ee?"char":"keyDown",key:oe,code:te,text:ee?oe:void 0,unmodifiedText:ee?oe:void 0,modifiers:X})}catch(J){t(`❌ Key error: ${J.message||J}`)}},ue=async oe=>{if(oe.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(oe.key)&&oe.preventDefault();let ee=0;oe.altKey&&(ee|=1),oe.ctrlKey&&(ee|=2),oe.metaKey&&(ee|=4),oe.shiftKey&&(ee|=8),d(`Key: ${oe.key}`),await q(oe.key,oe.code,oe.key.length===1,ee)},ce=async oe=>{if(oe.key==="Enter"){if(oe.nativeEvent.isComposing)return;if(h){const te=h;f(""),d(`IME Sent: ${te}`);try{const ee=await e("input_type",{text:te});ee!=null&&ee.success||t(`❌ IME error: ${ee==null?void 0:ee.error}`)}catch(ee){t(`❌ IME error: ${ee.message}`)}}else d("Key: Enter"),await q("Enter","Enter",!1)}};o.useEffect(()=>{const oe=c.current;if(!oe)return;const te=ee=>{var X;if((X=u.current)!=null&&X.contains(ee.target)){ee.preventDefault();const J=Date.now();if(J-A.current<40)return;A.current=J;const de=be(ee.clientX,ee.clientY);if(!de)return;d(`Scroll: ${Math.round(ee.deltaY)}`),e("input_wheel",{nx:de.nx,ny:de.ny,deltaX:Math.round(ee.deltaX),deltaY:Math.round(ee.deltaY)}).catch(()=>{})}};return oe.addEventListener("wheel",te,{passive:!1}),()=>oe.removeEventListener("wheel",te)},[e]);const{cursorPos:je,handleToggleInputMode:ae,handleZoomReset:fe}=ku({containerRef:c,viewportRef:l,imgRef:u,inputMode:T,setInputMode:S,minZoom:ye,zoomRef:U,panXRef:$,panYRef:E,setPanX:F,setPanY:M,setZoom:_,lastWheelTimeRef:A,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:G,clampPan:le,isMobile:v,mobileFillZoom:k});return s.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ue,onContextMenu:oe=>oe.preventDefault(),onFocus:()=>j(!0),onBlur:()=>j(!1),tabIndex:0,children:[s.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[Y?s.jsx("img",{ref:u,src:Y,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${L}) translate(${H}%, ${O}%)`,transformOrigin:"center center",cursor:T==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ne,onContextMenu:oe=>oe.preventDefault(),onDragStart:oe=>oe.preventDefault()}):s.jsx(wu,{waitingLabel:ve,waitingHint:re,transportType:i}),T==="mouse"&&Y&&s.jsx(yu,{cursorPos:je,viewportRef:l,imgRef:u}),N.map(oe=>{const ee={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[oe.type];return s.jsxs("div",{style:{position:"absolute",left:oe.x,top:oe.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ee}, 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(${ee}, 0.9)`,boxShadow:`0 0 12px rgba(${ee}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},oe.id)})]}),s.jsx(vu,{inputMode:T,onToggleInputMode:ae,isImeOpen:C,setIsImeOpen:I,isMenuOpen:y,setIsMenuOpen:g,imeText:h,setImeText:f,handleImeSubmit:ce,isConnActive:z,zoom:L,isMobile:v,mobileFillZoom:k,onZoomOut:()=>_(oe=>Math.max(.5,oe-.25)),onZoomReset:fe,onZoomIn:()=>_(oe=>Math.min(5,oe+.25)),transportType:i,screenshotUsage:a,lastActionStatus:m}),s.jsx("style",{children:`
|
|
2
|
+
var Xl=Object.defineProperty;var Jl=(e,t,r)=>t in e?Xl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var ze=(e,t,r)=>Jl(e,typeof t!="symbol"?t+"":t,r);import{r as o,j as s,M as ba,a as Ql,b as Zl,c as ed,u as Is,R as jt,d as Js,t as td,e as sd,D as rd,f as qn,g as Yn,h as ga,i as nd,k as ad,B as od,l as id,m as Gt,N as Xn,n as cd}from"./vendor-BRZ4K-AC.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();function ld(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(a),r.length>t&&r.splice(0,r.length-t),a},list(n={}){const a=Math.max(1,Math.floor(n.limit||100));return r.filter(i=>!n.interactionId||i.interactionId===n.interactionId).filter(i=>!n.topic||i.topic===n.topic).filter(i=>!n.kind||i.kind===n.kind).slice(-a).map(i=>({...i,payload:i.payload?{...i.payload}:{}}))},clear(){r.splice(0,r.length)}}}const js=ld();function lo(e){const t={};for(const r of e)r.transport&&(t[r.transport]=(t[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:t}}function dd(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function ud(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function vi(e,t){var m;if(!e)return t??null;if(!t)return e??null;const r=ud(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:void 0,a=e.status==="waiting_approval"||Array.isArray((m=e.activeModal)==null?void 0:m.buttons)&&e.activeModal.buttons.length>0,i=r&&a&&(n==null?void 0:n.length)===0&&Array.isArray(t.messages)&&t.messages.length>0,c=r?i?t.messages:n??[]:t.messages,l=e.activeModal||(e.status==="waiting_approval"?t.activeModal:null),u={...t,...e,activeModal:l,inputContent:e.inputContent??t.inputContent};return r?{...u,messages:c}:u}function Fs(e,t){const r=dd(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(t==null?void 0:t.parentSessionId)??null,providerSessionId:e.providerSessionId??(t==null?void 0:t.providerSessionId),providerName:r??(t==null?void 0:t.providerName)??(t==null?void 0:t.cliName)??(t==null?void 0:t.type)??e.providerName??e.providerType,title:e.title??(t==null?void 0:t.title)??r??(t==null?void 0:t.providerName)??e.providerName??e.providerType,workspace:e.workspace??(t==null?void 0:t.workspace)??null,mode:e.mode??(t==null?void 0:t.mode),capabilities:e.capabilities??(t==null?void 0:t.sessionCapabilities)??(t==null?void 0:t.capabilities)??[],cdpConnected:e.cdpConnected??(t==null?void 0:t.cdpConnected),activeChat:vi(e.activeChat,t==null?void 0:t.activeChat),controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel)}}function wi(e,t,r){if(!(t!=null&&t.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const n=t.map(a=>{const i=e.find(c=>c.id===a.id);return i?Fs(a,i):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(t.map(i=>i.id));for(const i of e)a.has(i.id)||n.push(i)}return n}function uo(e){return!!e&&typeof e=="object"&&"text"in e}function ya(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:uo(i)?String(i.text||""):"").join(r):uo(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function ks(e){return ya(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 mo(e){var r,n;let t=0;return e.activeChat!==void 0&&(t+=4),(r=e.childSessions)!=null&&r.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(n=e.agents)!=null&&n.length&&(t+=1),t}function Si(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,i=t.serverVersion??e.serverVersion??r.serverVersion,c=t.versionMismatch===!0||e.versionMismatch===!0,l=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,u=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),i&&(n.serverVersion=i),u&&(n.versionUpdateReason=u),a&&i&&a===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||c&&a&&i&&a!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function md(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function mn(e){if(!e||typeof e!="object")return"";const t=e,r=md(ks(t.content).slice(0,512));return[String(t.id||""),String(t._localId||""),String(t._turnKey||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),r].join(":")}function fd(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=mn(n);for(let i=0;i<a.length;i+=1)r^=a.charCodeAt(i),r=Math.imul(r,16777619)>>>0}return{count:e.length,hash:r.toString(16).padStart(8,"0"),first:mn(e[0]),last:mn(e[e.length-1])}}function Jn(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(Jn(e)&&Jn(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 zs(e,t){return Array.isArray(e)?e.map(r=>zs(r,t)):!e||typeof e!="object"?e:Jn(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?fd(a,t):zs(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,zs(n,t)]))}function pd(e,t){try{const r=new WeakSet;return Qn(e,t,r),JSON.stringify(zs(e,r))===JSON.stringify(zs(t,r))}catch{return!1}}function Zn(e,t,r){return pd(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Ni(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function hd(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function fo(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,i=wi(e.childSessions,t.childSessions,{preserveMissing:n}),c=vi(t.activeChat,e.activeChat);return Si(e,t,{...e,...t,chats:a,childSessions:i,activeChat:c,_lastUpdate:r})}function xd(e,t,r){var a,i;const n={};t.status&&t.status!==e.status&&(n.status=t.status),t.cdpConnected!==void 0&&(n.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(n.childSessions=wi(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((i=e.chats)!=null&&i.length)&&(n.chats=t.chats);for(const c of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion"])hd(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function bd(e,t,r,n){const a=xd(e,t,n),i=Object.keys(a).length>0?Si(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return Zn(e,i,r)}function gd(e){const t=new Set(e.map(i=>i.id)),r=new Set,n=new Set,a=new Set;for(const i of e){const c=Ni(i);c&&r.add(c),c&&i.type!=="adhdev-daemon"&&n.add(c),c&&i.type==="adhdev-daemon"&&i._sessionListAuthoritative&&a.add(c)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function yd(e,t,r,n,a,i){return!a.has(t)||!i.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function vd(e,t,r,n){return!!(r.has(t)&&e.transport&&!n.has(t))}function wd(e,t,r){var d,h;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(f=>({...f,_lastUpdate:n}));const i=new Map;for(const f of t)i.set(f.id,f);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:u,daemonIdsWithAuthoritativeSessionList:m}=gd(e);for(const f of e){const j=i.get(f.id);if(!j){i.set(f.id,{...f,_lastUpdate:n});continue}const N=mo(f),p=mo(j),x=Ni(f),y=!a.has(x);if(N>p){const I=fo(j,f,n,y);i.set(f.id,Zn(j,I,n));continue}if(N<p){i.set(f.id,bd(j,f,n,y));continue}const g=f.timestamp||n,C=j._lastUpdate||j.timestamp||0;if(g>=C){const I=fo(j,f,n,y);i.set(f.id,Zn(j,I,n));continue}(d=f.chats)!=null&&d.length&&!((h=j.chats)!=null&&h.length)&&i.set(f.id,{...j,chats:f.chats})}for(const[f,j]of i){const N=j.daemonId||f.split(":")[0];if(!l.has(N))continue;if(a.has(N)&&m.has(N)&&!c.has(f)){i.delete(f);continue}const p=n-(j._lastUpdate||j.timestamp||0);yd(j,N,p,c,a,u)&&i.delete(f)}for(const[f,j]of i){const N=j.daemonId||f.split(":")[0];if(vd(j,N,l,u))continue;n-(j._lastUpdate||j.timestamp||0)>3e5&&j.status!=="online"&&i.delete(f)}return Array.from(i.values())}function jd(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function kd({children:e,connectionOverrides:t}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[u,m]=o.useState(void 0),d=o.useRef(r);o.useEffect(()=>{d.current=r},[r]);const h=o.useCallback((y,g)=>{n(C=>{let I=!1;const v=C.map(M=>M.id!==y||M.chats===g?M:(I=!0,{...M,chats:g}));return I?v:C})},[]),f=o.useCallback((y,g)=>{n(C=>{const I=C.length===0?y:wd(y,C,g),v=!jd(C,I);return v&&js.record({kind:"dashboard.entries_applied",payload:{incoming:lo(y),next:lo(I)}}),v?I:C})},[]),j=o.useCallback(()=>i(!0),[]),N=o.useMemo(()=>({injectEntries:f,markLoaded:j,getIdes:()=>d.current}),[f,j]),p=t,x=o.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(p==null?void 0:p.wsStatus)??"connected",isConnected:(p==null?void 0:p.isConnected)??!0,connectionStates:(p==null?void 0:p.connectionStates)??{},connectionTransports:(p==null?void 0:p.connectionTransports)??{},showReconnected:(p==null?void 0:p.showReconnected)??!1,retryConnection:p==null?void 0:p.retryConnection,retryServerConnection:p==null?void 0:p.retryServerConnection,connectionLoginUrl:p==null?void 0:p.connectionLoginUrl,isP2PActive:(p==null?void 0:p.isP2PActive)??!1,p2pStates:(p==null?void 0:p.p2pStates)??{},userRole:p==null?void 0:p.userRole,userName:u,setUserName:m}),[r,h,a,c,p==null?void 0:p.wsStatus,p==null?void 0:p.isConnected,p==null?void 0:p.connectionStates,p==null?void 0:p.connectionTransports,p==null?void 0:p.showReconnected,p==null?void 0:p.retryConnection,p==null?void 0:p.retryServerConnection,p==null?void 0:p.connectionLoginUrl,p==null?void 0:p.isP2PActive,p==null?void 0:p.p2pStates,p==null?void 0:p.userRole,u]);return s.jsx(ki.Provider,{value:N,children:s.jsx(ji.Provider,{value:x,children:e})})}function os(){return o.useContext(ji)}function Qs(){return o.useContext(ki)}function Ci(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function i(l){const u=r==null?void 0:r(),m=a(l),d=l.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return u&&d.searchParams.set("token",u),!l.startsWith("http")&&!t?`${d.pathname}${d.search}${d.hash}`:d.toString()}async function c(l,u={}){const m={"Content-Type":"application/json",...u.headers||{}},d=r==null?void 0:r();d&&(m.Authorization=`Bearer ${d}`);const h=a(l),f=new AbortController,j=setTimeout(()=>f.abort(),15e3);try{const N=await fetch(h,{...u,headers:m,signal:f.signal});if(N.status===401)throw n==null||n(),new Error("Unauthorized");if(!N.ok){const p=await N.json().catch(()=>({error:N.statusText}));throw new Error(p.error||`API Error: ${N.status}`)}return N.json()}finally{clearTimeout(j)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,u,m={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:m})}),execTerminal:(l,u,m)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:m})}),sendAgentMessage:(l,u,m)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:m})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,m)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:m?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,u,m={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:m})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Sd=Ci({baseUrl:"http://localhost:3847"}),Nd=o.createContext(Sd);function Cd({client:e,children:t}){return s.jsx(Nd.Provider,{value:e,children:t})}const Td={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Ti=o.createContext(Td);function Md({value:e,children:t}){return s.jsx(Ti.Provider,{value:e,children:t})}function wt(){return o.useContext(Ti)}function Id(e){let t=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)t^=n.charCodeAt(a),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function Ad(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Mi(e){return e?Id([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Ad(e.content)]):""}const De={size:18};function Ii({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function va({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function is({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function Ai({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Ld({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Rd({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function Li({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function _d({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Xr({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Ri({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Pd({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Wt({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function St({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function wa({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("polyline",{points:"14 2 14 8 20 8"}),s.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),s.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Dd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Ss({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function nr({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function Zs({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function er({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function _i({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Pi({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),s.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Di({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function Ed({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function ja({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function $d({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function ka({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Ei({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function vt({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Bd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),s.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),s.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),s.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Kd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Od({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function Wd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function Jr({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Hd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"5"}),s.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),s.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),s.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),s.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),s.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),s.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),s.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),s.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function Fd({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Ud({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function zd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Vd({size:e=De.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Gd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function qd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function Yd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function Xd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Jd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function Qd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function Zd({size:e=De.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const $i=[Ql,{singleTilde:!1}],Bi=[$i,Zl,ed],eu=[$i],Sa=200,tu=80,po=650,Ps=new Map;function Br(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function su(e,t){if(!Array.isArray(e)||e.length===0)return"0:empty";const r=String(t||"").trim();if(r)return`${e.length}:${r}`;const n=e[e.length-1];return`${e.length}:${Mi(n)}`}function ru(e,t,r,n){return e||!t?!1:Br(r,n)}function nu({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=tu,bottomThresholdPx:a=Sa}){const i=Math.max(0,Number(e)||0),c=Math.max(0,Number(t)||0),l=Math.max(0,Number(r)||0);return Math.max(0,c-l)<=0?{showTop:!1,showBottom:!1}:{showTop:i>n,showBottom:Math.max(0,c-i-l)>a}}function au(e){return nu({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Us(e,t=Sa){return!!e&&e.fromBottom>=t}function ou(e,t){return Br(e,t)?!Us(e):!0}function iu({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function cu({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function fn(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function Ki(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function lu(e,t,r){return Number(e.receivedAt||r[Kr(e,t)]||0)||0}function Oi(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function du(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function ur(e,t){if(!e)return t;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||t}catch{return e.split(/[\\/]/).filter(Boolean).pop()||t}}function pn(e){if(typeof e.uri=="string"&&e.uri)return e.uri;if(typeof e.data=="string"&&e.data&&typeof e.mimeType=="string"&&e.mimeType)return`data:${e.mimeType};base64,${e.data}`}function ho(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Oi(e)?s.jsx(ba,{remarkPlugins:Bi,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function mr({parts:e,renderAsPreformatted:t}){return s.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return s.jsx("div",{children:ho(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=pn(r);return a?s.jsx("img",{src:a,alt:ur(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=pn(r);return a?s.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=pn(r);return a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:ur(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||ur(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=ur(r.resource.uri,"resource");if(r.resource.text)return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[s.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),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=ya(e.content,{joiner:`
|
|
3
|
+
`});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${t}`].filter(Boolean).join("|")}const uu=o.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(ba,{remarkPlugins:eu,children:t.text}),s.jsx("span",{className:"action-time",children:Ki(t.timestamp)})]})},(e,t)=>e.log===t.log),mu=o.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var M,S,k;const u=(t.role||"").toLowerCase(),m=u==="user"||u==="human",d=t.kind||(u==="tool"?"tool":"standard"),h=du(t.content)?t.content:null,f=!!(h!=null&&h.some(b=>b.type!=="text")),j=ya(t.content,{joiner:`
|
|
4
|
+
`});if(d==="thought"){const b=typeof((M=t.meta)==null?void 0:M.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(Od,{size:13}),s.jsx("span",{children:b})]}),s.jsx("div",{className:"chat-msg-body",children:j})]})}if(d==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),f&&h?s.jsx("div",{className:"tool-text w-full",children:s.jsx(mr,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:j})]});if(d==="terminal"){const b=(S=t.meta)!=null&&S.isRunning?"⏳":"✅",B=typeof((k=t.meta)==null?void 0:k.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:b}),s.jsx("span",{children:B})]}),f&&h?s.jsx("div",{className:"chat-msg-body",children:s.jsx(mr,{parts:h,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:j})]})}if(d==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:f&&h?s.jsx(mr,{parts:h,renderAsPreformatted:!1}):j.slice(0,100)});const N=t.meta,x=(typeof(N==null?void 0:N.renderMode)=="string"?N.renderMode.trim():"")==="preformatted",y=j,g=!1,C=y,I=x,v=!I&&Oi(C);return s.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${m?"self-end":"self-start"}`,children:(y||f||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${y||f?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:m?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:Ki(r)})]}),(y||f)&&s.jsx("div",{className:"chat-markdown",children:f&&h?s.jsx(mr,{parts:h,renderAsPreformatted:I}):I?s.jsx("pre",{className:"chat-preformatted",children:C}):v?s.jsx(ba,{remarkPlugins:Bi,children:C}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:C})}),g]})})},(e,t)=>e.message===t.message&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),fu=o.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},lastMessageHash:m,emptyState:d,onLoadMore:h,isLoadingMore:f,hasMoreHistory:j,hiddenLiveCount:N=0,loadError:p,scrollToBottomRequestNonce:x,isVisible:y=!0},g){const C=o.useRef(null),I=o.useRef(null),v=o.useRef(null),M=o.useRef(0),S=o.useRef(""),k=o.useRef(""),b=o.useRef(!1),B=o.useRef(null),L=o.useRef(!1),_=o.useRef(null),H=o.useRef(!1),[F,O]=o.useState(new Set),[T,A]=o.useState({showTop:!1,showBottom:!1}),U=o.useRef(!1),$=o.useRef(!1),E=o.useRef(y),z=o.useRef(y),Y=o.useRef(null);z.current=y;const ve=()=>{const X=C.current;return X?X.scrollHeight-X.scrollTop-X.clientHeight<Sa:!0},re=o.useCallback(()=>{const X=C.current,J=X?au(X):{showTop:!1,showBottom:!1};A(de=>de.showTop===J.showTop&&de.showBottom===J.showBottom?de:J)},[]),ye=o.useCallback((X="auto")=>{var de;const J=C.current;J&&(J.scrollTo({top:J.scrollHeight,behavior:X}),(de=J.ownerDocument.defaultView)==null||de.requestAnimationFrame(()=>re()))},[re]),le=o.useCallback((X="auto")=>{var de;const J=C.current;J&&(J.scrollTo({top:0,behavior:X}),(de=J.ownerDocument.defaultView)==null||de.requestAnimationFrame(()=>re()))},[re]),be=o.useCallback(()=>{var ie;const X=C.current,J=(ie=window.getSelection)==null?void 0:ie.call(window);if(!X||!J||J.rangeCount===0||J.isCollapsed){H.current=!1;return}const de=J.anchorNode,D=J.focusNode;H.current=!!(de&&D&&X.contains(de)&&X.contains(D))},[]),ge=su(t,m),G=o.useCallback(()=>{const X=C.current;if(!X||!l||!z.current)return;const J={top:X.scrollTop,fromBottom:Math.max(0,X.scrollHeight-X.scrollTop-X.clientHeight),messageFingerprint:ge};Y.current={contextKey:l,snapshot:J},Ps.set(l,J)},[l,ge]),ne=o.useCallback((X="auto")=>{B.current!=null&&cancelAnimationFrame(B.current),B.current=requestAnimationFrame(()=>{B.current=null,ye(X)})},[ye]),q=o.useCallback(()=>{U.current=!1,L.current=!0,$.current=!0,_.current!=null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{L.current=!1,_.current=null},po)},[]);o.useEffect(()=>{const X=!b.current,J=k.current!==l;if(k.current=l,X||J){b.current=!0;const D=l?Ps.get(l):null,ie=!!D&&Br(D,ge);U.current=ie?Us(D):!1,L.current=ou(D,ge),H.current||(ie?requestAnimationFrame(()=>{const Q=C.current;Q&&(fn(Q,D),U.current=Us(D),re(),$.current=!0)}):ne("auto")),M.current=t.length,S.current=ge;return}t.length>M.current;const de=ge!==S.current;iu({hasSelection:H.current,userScrolledUp:U.current,hasChatContentChanged:de})&&ne("auto"),M.current=t.length,S.current=ge},[ge,l,t.length,ne,re]),o.useEffect(()=>{x&&(q(),H.current||ne("auto"))},[q,ne,x]),o.useEffect(()=>{const X=E.current;X&&!y&&G(),z.current=y,E.current=y;const J=l?Ps.get(l):null;if(ru(X,y,J,ge)){if(!J)return;U.current=Us(J),L.current=!1,H.current||requestAnimationFrame(()=>{const de=C.current;de&&(fn(de,J),re())});return}},[y,l,ge,q,G,ne,re]),o.useEffect(()=>()=>{const X=Y.current;X&&Ps.set(X.contextKey,X.snapshot),B.current!=null&&cancelAnimationFrame(B.current),_.current!=null&&window.clearTimeout(_.current)},[]),o.useEffect(()=>{const X=I.current,J=C.current;if(!X||!J)return;const de=()=>{_.current!=null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{L.current=!1,_.current=null},po)},D=new ResizeObserver(()=>{re();const ie=L.current;cu({hasSelection:H.current,userScrolledUp:U.current,contextAutoScrollActive:ie})&&(ne("auto"),ie&&de())});return D.observe(X),J!==X&&D.observe(J),()=>{D.disconnect(),_.current!=null&&(window.clearTimeout(_.current),_.current=null)}},[ne,l,re]),o.useImperativeHandle(g,()=>({scrollToBottom:(X="smooth")=>{ye(X)}}),[ye]),o.useEffect(()=>{const X=C.current;if(!X)return;let J;const de=()=>{G(),clearTimeout(J),J=setTimeout(()=>{U.current=!ve(),re()},50)};return X.addEventListener("scroll",de,{passive:!0}),()=>{X.removeEventListener("scroll",de),clearTimeout(J)}},[G,re]),o.useEffect(()=>(document.addEventListener("selectionchange",be),()=>document.removeEventListener("selectionchange",be)),[be]);const ue=o.useRef(0),ce=o.useRef(!1);o.useEffect(()=>{const X=C.current;if(!X||!ce.current||ue.current===0)return;const J=X.scrollHeight-ue.current;J>0&&(X.scrollTop=J),re(),G(),ue.current=0,ce.current=!1},[t.length,G,re]),o.useEffect(()=>{if($.current||!l)return;const X=Ps.get(l),J=C.current;if(!(!X||!J)){if(!Br(X,ge)){ye("auto"),$.current=!0;return}fn(J,X),U.current=Us(X),re(),$.current=!0}},[l,ge,t.length,ye,re]);const je=()=>{const X=C.current;X&&(ue.current=X.scrollHeight),ce.current=!0,h==null||h()},ae=()=>{U.current=!0,le("smooth"),G()},fe=()=>{q(),ye("smooth"),G()},oe=o.useMemo(()=>{const X=t.map((ie,Q)=>({type:"message",data:ie,index:Q,ts:lu(ie,Q,u)}));if(!r||r.length===0)return X;const J=[...r].sort((ie,Q)=>ie.timestamp-Q.timestamp).map((ie,Q)=>({type:"action",data:ie,index:Q,ts:ie.timestamp})),de=[];let D=0;for(const ie of X){for(;D<J.length&&ie.ts>0&&J[D].ts<ie.ts;)de.push(J[D++]);de.push(ie)}for(;D<J.length;)de.push(J[D++]);return de},[t,r,u]),te=N>0||!!j,ee=N>0?`↑ Show ${Math.min(N,80)} earlier messages${N>80?` (${N} hidden)`:""}`:p?`↻ ${p}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:C,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:I,className:"chat-container-content",children:[f&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),te&&!f&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:je,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${p&&N===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:ee})}),oe.length===0&&!te&&(d||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),oe.map(X=>{if(X.type==="action"){const Ne=X.data;return s.jsx(uu,{log:Ne},`action-${X.index}`)}const J=X.data,de=X.index,D=Kr(J,de),ie=J.receivedAt||u[D],Q=`${l}-${D}`,we=F.has(Q);return s.jsx(mu,{message:J,receivedAt:ie,agentName:n,userName:a,isCliMode:i,isTextExpanded:we,onToggleTextExpanded:()=>O(Ne=>{const Ae=new Set(Ne);return we?Ae.delete(Q):Ae.add(Q),Ae})},`msg-${D}`)}),c&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),s.jsx("div",{className:"min-h-10",ref:v})]})}),(T.showTop||T.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[T.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:ae,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),T.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:fe,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),pu=o.memo(fu,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.lastMessageHash===t.lastMessageHash&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible),hu="modulepreload",xu=function(e){return"/"+e},xo={},bu=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=Promise.allSettled(r.map(u=>{if(u=xu(u),u in xo)return;xo[u]=!0;const m=u.endsWith(".css"),d=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const h=document.createElement("link");if(h.rel=m?"stylesheet":hu,m||(h.as="script"),h.crossOrigin="",h.href=u,l&&h.setAttribute("nonce",l),document.head.appendChild(h),m)return new Promise((f,j)=>{h.addEventListener("load",f),h.addEventListener("error",()=>j(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};let bo=!1;const Wi=o.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:i="measured"},c)=>{const l=o.useRef(null),[u,m]=o.useState(null),d=o.useRef([]),h=o.useRef(!1),f=o.useRef(!1),j=o.useRef(!1),N=o.useRef(!1),p=()=>{const x=l.current;if(x){h.current&&(x.clear(),h.current=!1);for(const y of d.current)x.write(y.data,y.onProcessed);d.current=[],f.current&&(x.fit(),f.current=!1),j.current&&(x.bumpResize(),j.current=!1),N.current&&(x.scrollToTop(),N.current=!1)}};return o.useImperativeHandle(c,()=>({write:(x,y)=>{l.current?l.current.write(x,y):d.current.push({data:x,onProcessed:y})},clear:()=>{l.current?l.current.clear():(d.current=[],h.current=!0)},reset:()=>{l.current&&typeof l.current.reset=="function"?l.current.reset():(d.current=[],h.current=!0)},resize:(x,y)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(x,y)},fit:()=>{l.current?l.current.fit():f.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():j.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():N.current=!0},getSelection:()=>{var x,y;return((y=(x=l.current)==null?void 0:x.getSelection)==null?void 0:y.call(x))||""},getVisibleText:()=>{var x,y;return((y=(x=l.current)==null?void 0:x.getVisibleText)==null?void 0:y.call(x))||""}}),[]),o.useEffect(()=>{u&&p()},[u]),o.useEffect(()=>{let x=!1;return bu(()=>import("./terminal-DbJP_JGY.js"),__vite__mapDeps([0,1,2])).then(y=>{bo||(bo=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),x||m(()=>y.GhosttyTerminalView)}).catch(y=>{console.error("[CliTerminal] failed to load terminal renderer",y)}),()=>{x=!0}},[]),u?s.jsx(u,{ref:l,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:i,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Wi.displayName="CliTerminal";function fr({label:e,value:t,sub:r,icon:n}){return s.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:n}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),r&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function 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 gu({cursorPos:e,viewportRef:t,imgRef:r}){var g;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(g=t.current)==null?void 0:g.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,u=c/l,m=a.width/a.height;let d,h,f,j;u>m?(d=a.width,h=a.width/u,f=0,j=(a.height-h)/2):(h=a.height,d=a.height*u,f=(a.width-d)/2,j=0);const N=a.left-i.left+f+d*e.nx,p=a.top-i.top+j+h*e.ny,x=Math.max(8,Math.min(i.width-8,N)),y=Math.max(8,Math.min(i.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:x-8,top:y-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function yu({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:m,zoom:d,isMobile:h,mobileFillZoom:f,onZoomOut:j,onZoomReset:N,onZoomIn:p,transportType:x,screenshotUsage:y,lastActionStatus:g}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:C=>C.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(C=>!C),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:C=>C.stopPropagation(),onChange:C=>l(C.target.value),onKeyDown:C=>{u(C)},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(C=>!C),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:m?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),d>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),x==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),x==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),y&&y.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:y.budgetExhausted?"TURN blocked":`TURN ${y.dailyUsedMinutes}/${y.dailyBudgetMinutes}m`}),g&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:g})]})]}),a&&s.jsxs("div",{onTouchStart:C=>C.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",d<=(h?f:1)+.01?h?"FILL":"FIT":`${Math.round(d*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:C=>{C.stopPropagation(),j()},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:C=>{C.stopPropagation(),N()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:h?"FILL":"FIT"}),s.jsx("button",{onClick:C=>{C.stopPropagation(),p()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function vu({waitingLabel:e,waitingHint:t,transportType:r}){return s.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[s.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),s.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),s.jsx("div",{className:"text-[11px] text-white/40",children:t}),r==="relay"&&s.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function wu(){if(typeof window>"u")return!1;try{return window.__ADHDEV_DEBUG_RENDERS__===!0||window.localStorage.getItem("adhdev_debug_renders")==="1"}catch{return window.__ADHDEV_DEBUG_RENDERS__===!0}}function 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 ar(e,t){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!wu())return;n.current+=1;const a=r.current;if(!a){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([c,l])=>[c,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 ju({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:m,setPanY:d,setZoom:h,lastWheelTimeRef:f,onAction:j,setLastActionStatus:N,spawnRippleFromNormalized:p,clampPan:x,isMobile:y,mobileFillZoom:g}){const[C,I]=o.useState(null),v=o.useRef(null),M=o.useRef(null),S=o.useRef(null),k=o.useRef(!1),b=o.useRef(null),B=o.useRef(0),L=o.useRef(null),_=o.useRef(1),H=o.useRef({x:0,y:0}),F=o.useRef(!1),O=o.useRef(n),T=o.useRef(j),A=30,U=550,$=18,E=60,z=400,Y=12,ve=()=>{if(v.current)return;const le={nx:.5,ny:.5};v.current=le,I(le)};return o.useEffect(()=>{O.current=n,n==="mouse"&&ve()},[n]),o.useEffect(()=>{T.current=j},[j]),o.useEffect(()=>{const le=e.current;if(!le)return;const be=ce=>{if(!r.current)return null;const je=r.current.getBoundingClientRect();return!je.width||!je.height?null:{nx:Math.max(0,Math.min(1,(ce.clientX-je.left)/je.width)),ny:Math.max(0,Math.min(1,(ce.clientY-je.top)/je.height))}},ge=(ce,je)=>{if(!r.current)return{dnx:0,dny:0};const ae=r.current,fe=ae.getBoundingClientRect(),oe=ae.naturalWidth||fe.width,te=ae.naturalHeight||fe.height,ee=oe/te,X=fe.width/fe.height;let J,de;return ee>X?(J=fe.width,de=fe.width/ee):(de=fe.height,J=fe.height*ee),{dnx:ce/J,dny:je/de}},G=(ce,je,ae)=>{if(ae<=1.05)return;const fe=-(ce-.5)*100,oe=-(je-.5)*100,te=x(fe,oe,ae);(Math.abs(te.x-l.current)>.1||Math.abs(te.y-u.current)>.1)&&(m(te.x),d(te.y),l.current=te.x,u.current=te.y)},ne=ce=>{const je=t.current;if(je&&ce.target instanceof Node&&je.contains(ce.target))ce.preventDefault();else return;if(ce.touches.length===1){const ae=ce.touches[0];M.current={x:ae.clientX,y:ae.clientY,time:Date.now()},S.current={x:ae.clientX,y:ae.clientY},F.current||(k.current=!1),b.current=setTimeout(()=>{if(!k.current&&!F.current)if(k.current=!0,O.current==="mouse"){const fe=v.current||{nx:.5,ny:.5};N("Right Click"),p(fe.nx,fe.ny,"right"),T.current("input_click",{...fe,button:"right"}).catch(()=>{})}else{const fe=be(ae);fe&&(N("Right Click"),p(fe.nx,fe.ny,"right"),T.current("input_click",{...fe,button:"right"}).catch(()=>{}))}},500);return}if(ce.touches.length===2){b.current&&clearTimeout(b.current),k.current=!0,F.current=!0;const ae=ce.touches[1].clientX-ce.touches[0].clientX,fe=ce.touches[1].clientY-ce.touches[0].clientY;L.current=Math.sqrt(ae*ae+fe*fe),_.current=c.current,H.current={x:(ce.touches[0].clientX+ce.touches[1].clientX)/2,y:(ce.touches[0].clientY+ce.touches[1].clientY)/2}}},q=ce=>{const je=t.current;if(je&&ce.target instanceof Node&&je.contains(ce.target)&&ce.preventDefault(),ce.touches.length===1&&S.current){const ae=ce.touches[0],fe=ae.clientX-S.current.x,oe=ae.clientY-S.current.y;if(!k.current&&M.current){const te=ae.clientX-M.current.x,ee=ae.clientY-M.current.y;Math.sqrt(te*te+ee*ee)>8&&(k.current=!0,b.current&&clearTimeout(b.current))}if(k.current)if(O.current==="mouse"){const te=ge(fe,oe),ee=v.current||{nx:.5,ny:.5},X=Math.max(0,Math.min(1,ee.nx+te.dnx)),J=Math.max(0,Math.min(1,ee.ny+te.dny));v.current={nx:X,ny:J},I({nx:X,ny:J}),N(`Cursor: ${Math.round(X*100)}%, ${Math.round(J*100)}%`),G(X,J,c.current);const de=Date.now();de-f.current>=30&&(f.current=de,T.current("input_mouseMoved",{nx:X,ny:J}).catch(()=>{}))}else if(c.current>1){const te=t.current;if(te){const ee=te.clientWidth,X=te.clientHeight,J=l.current+fe/ee*100,de=u.current+oe/X*100,D=x(J,de,c.current);m(D.x),d(D.y),l.current=D.x,u.current=D.y}}else{const te=be(ae);if(te){const ee=Date.now();ee-f.current>=40&&(f.current=ee,N("Scroll"),T.current("input_wheel",{nx:te.nx,ny:te.ny,deltaX:Math.round(-fe*2.5),deltaY:Math.round(-oe*2.5)}).catch(()=>{}))}}S.current={x:ae.clientX,y:ae.clientY};return}if(ce.touches.length===2&&L.current!==null){const ae=ce.touches[1].clientX-ce.touches[0].clientX,fe=ce.touches[1].clientY-ce.touches[0].clientY,te=Math.sqrt(ae*ae+fe*fe)/L.current,ee=(ce.touches[0].clientX+ce.touches[1].clientX)/2,X=(ce.touches[0].clientY+ce.touches[1].clientY)/2,J=ee-H.current.x,de=X-H.current.y,D=Math.abs(te-1)>.03;if(O.current==="mouse"){if(D){const ie=Math.max(i,Math.min(5,_.current*te));h(ie),c.current=ie}else if(Math.abs(J)>2||Math.abs(de)>2){const ie=v.current||{nx:.5,ny:.5},Q=Date.now();Q-f.current>=30&&(f.current=Q,N("Scroll"),T.current("input_wheel",{nx:ie.nx,ny:ie.ny,deltaX:Math.round(-J*3),deltaY:Math.round(-de*3)}).catch(()=>{}))}}else{const ie=Math.max(i,Math.min(5,_.current*te));h(ie),c.current=ie;const Q=t.current;if(Q&&ie>1){const we=Q.clientWidth,Ne=Q.clientHeight,Ae=l.current+J/we*100,Me=u.current+de/Ne*100,Ue=x(Ae,Me,ie);m(Ue.x),d(Ue.y),l.current=Ue.x,u.current=Ue.y}}H.current={x:ee,y:X}}},ue=ce=>{var je;if(b.current&&clearTimeout(b.current),L.current=null,ce.touches.length===1&&F.current){const ae=ce.touches[0];M.current={x:ae.clientX,y:ae.clientY,time:Date.now()},S.current={x:ae.clientX,y:ae.clientY},k.current=!0;return}if(ce.touches.length===0){if(F.current){F.current=!1,k.current=!1;return}if(ce.changedTouches.length===1){const ae=ce.changedTouches[0],fe=Date.now(),oe=fe-(((je=M.current)==null?void 0:je.time)||0),te=M.current?ae.clientX-M.current.x:0,ee=M.current?ae.clientY-M.current.y:0,X=Math.sqrt(te*te+ee*ee);if(O.current==="mouse"){if(oe<A||oe>U||X>$){k.current=!1;return}const J=v.current||be(ae);J&&(N(`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(k.current){k.current=!1;return}if(oe<E||oe>z||X>Y){k.current=!1;return}const J=be(ae);if(!J)return;fe-B.current<300?(N("Double tap"),p(J.nx,J.ny,"double"),T.current("input_click",{...J,clickCount:2}).catch(()=>{}),B.current=0):(N(`Tap: ${Math.round(J.nx*100)}%, ${Math.round(J.ny*100)}%`),p(J.nx,J.ny,"left"),T.current("input_click",{...J}).catch(()=>{}),B.current=fe)}}k.current=!1}};return le.addEventListener("touchstart",ne,{passive:!1}),le.addEventListener("touchmove",q,{passive:!1}),le.addEventListener("touchend",ue,{passive:!1}),()=>{le.removeEventListener("touchstart",ne),le.removeEventListener("touchmove",q),le.removeEventListener("touchend",ue),b.current&&clearTimeout(b.current)}},[e,t,r,i,c,l,u,m,d,h,f,N,p,x]),{cursorPos:C,cursorPosRef:v,handleToggleInputMode:()=>{a(le=>{const be=le==="touch"?"mouse":"touch";return be==="mouse"&&ve(),be})},handleZoomReset:()=>{const le=y?g:1;h(le),c.current=le,m(0),d(0),l.current=0,u.current=0}}}function Hi({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),u=o.useRef(null),[m,d]=o.useState(null),[h,f]=o.useState(""),[,j]=o.useState(!1),[N,p]=o.useState([]),x=o.useRef(0),[y,g]=o.useState(!1),[C,I]=o.useState(!1),v=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[M,S]=o.useState(v?"mouse":"touch"),[k,b]=o.useState(1),B=o.useRef(!1),[L,_]=o.useState(1),[H,F]=o.useState(0),[O,T]=o.useState(0);ar("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:M,zoom:L,panX:H,panY:O,isMenuOpen:y,isImeOpen:C});const A=o.useRef(0),U=o.useRef(L),$=o.useRef(H),E=o.useRef(O);o.useEffect(()=>{U.current=L},[L]),o.useEffect(()=>{$.current=H},[H]),o.useEffect(()=>{E.current=O},[O]),o.useEffect(()=>{var oe;(oe=c.current)==null||oe.focus()},[]);const z=r==="connected",Y=n,ve=z?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",re=z?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!v||B.current||!Y)return;const oe=u.current,te=l.current;if(!oe||!te)return;const ee=()=>{const X=te.clientWidth,J=te.clientHeight,de=oe.naturalWidth,D=oe.naturalHeight;if(!de||!D||!X||!J)return;const ie=Math.min(X/de,J/D),we=Math.max(X/de,J/D)/ie;we>1.01&&(b(we),_(we),U.current=we),B.current=!0};oe.complete&&oe.naturalWidth?ee():oe.addEventListener("load",ee,{once:!0})},[Y,v]);const ye=.5;o.useEffect(()=>{L<=ye&&(F(0),T(0))},[L,ye]);const le=(oe,te,ee)=>{if(ee<=ye)return{x:0,y:0};const X=(ee-1)/(2*ee)*100,J=(ee-1)/(2*ee)*100;return{x:Math.max(-X,Math.min(X,oe)),y:Math.max(-J,Math.min(J,te))}},be=(oe,te)=>{if(!u.current)return null;const ee=u.current.getBoundingClientRect();return!ee.width||!ee.height?null:{nx:Math.max(0,Math.min(1,(oe-ee.left)/ee.width)),ny:Math.max(0,Math.min(1,(te-ee.top)/ee.height))}},ge=(oe,te,ee)=>{const X=l.current;if(!X)return;const J=X.getBoundingClientRect(),de=++x.current;p(D=>[...D,{id:de,x:oe-J.left,y:te-J.top,type:ee}]),setTimeout(()=>p(D=>D.filter(ie=>ie.id!==de)),600)},G=(oe,te,ee)=>{const X=u.current,J=l.current;if(!X||!J)return;const de=X.getBoundingClientRect(),D=J.getBoundingClientRect(),ie=X.naturalWidth||de.width,Q=X.naturalHeight||de.height,we=ie/Q,Ne=de.width/de.height;let Ae,Me,Ue,We;we>Ne?(Ae=de.width,Me=de.width/we,Ue=0,We=(de.height-Me)/2):(Me=de.height,Ae=de.height*we,Ue=(de.width-Ae)/2,We=0);const Ke=de.left-D.left+Ue+Ae*oe,Ge=de.top-D.top+We+Me*te,Ze=++x.current;p(Je=>[...Je,{id:Ze,x:Ke,y:Ge,type:ee}]),setTimeout(()=>p(Je=>Je.filter(Ye=>Ye.id!==Ze)),600)},ne=async oe=>{var ee;const te=be(oe.clientX,oe.clientY);if(te){d(`Click: ${Math.round(te.nx*100)}%, ${Math.round(te.ny*100)}%`),ge(oe.clientX,oe.clientY,"left"),(ee=c.current)==null||ee.focus();try{const X=await e("input_click",{nx:te.nx,ny:te.ny});X!=null&&X.success||t(`❌ Click failed: ${X==null?void 0:X.error}`)}catch(X){t(`❌ Click error: ${X.message||X}`)}}},q=async(oe,te,ee,X=0)=>{try{await e("input_key",{type:ee?"char":"keyDown",key:oe,code:te,text:ee?oe:void 0,unmodifiedText:ee?oe:void 0,modifiers:X})}catch(J){t(`❌ Key error: ${J.message||J}`)}},ue=async oe=>{if(oe.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(oe.key)&&oe.preventDefault();let ee=0;oe.altKey&&(ee|=1),oe.ctrlKey&&(ee|=2),oe.metaKey&&(ee|=4),oe.shiftKey&&(ee|=8),d(`Key: ${oe.key}`),await q(oe.key,oe.code,oe.key.length===1,ee)},ce=async oe=>{if(oe.key==="Enter"){if(oe.nativeEvent.isComposing)return;if(h){const te=h;f(""),d(`IME Sent: ${te}`);try{const ee=await e("input_type",{text:te});ee!=null&&ee.success||t(`❌ IME error: ${ee==null?void 0:ee.error}`)}catch(ee){t(`❌ IME error: ${ee.message}`)}}else d("Key: Enter"),await q("Enter","Enter",!1)}};o.useEffect(()=>{const oe=c.current;if(!oe)return;const te=ee=>{var X;if((X=u.current)!=null&&X.contains(ee.target)){ee.preventDefault();const J=Date.now();if(J-A.current<40)return;A.current=J;const de=be(ee.clientX,ee.clientY);if(!de)return;d(`Scroll: ${Math.round(ee.deltaY)}`),e("input_wheel",{nx:de.nx,ny:de.ny,deltaX:Math.round(ee.deltaX),deltaY:Math.round(ee.deltaY)}).catch(()=>{})}};return oe.addEventListener("wheel",te,{passive:!1}),()=>oe.removeEventListener("wheel",te)},[e]);const{cursorPos:je,handleToggleInputMode:ae,handleZoomReset:fe}=ju({containerRef:c,viewportRef:l,imgRef:u,inputMode:M,setInputMode:S,minZoom:ye,zoomRef:U,panXRef:$,panYRef:E,setPanX:F,setPanY:T,setZoom:_,lastWheelTimeRef:A,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:G,clampPan:le,isMobile:v,mobileFillZoom:k});return s.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ue,onContextMenu:oe=>oe.preventDefault(),onFocus:()=>j(!0),onBlur:()=>j(!1),tabIndex:0,children:[s.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[Y?s.jsx("img",{ref:u,src:Y,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${L}) translate(${H}%, ${O}%)`,transformOrigin:"center center",cursor:M==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ne,onContextMenu:oe=>oe.preventDefault(),onDragStart:oe=>oe.preventDefault()}):s.jsx(vu,{waitingLabel:ve,waitingHint:re,transportType:i}),M==="mouse"&&Y&&s.jsx(gu,{cursorPos:je,viewportRef:l,imgRef:u}),N.map(oe=>{const ee={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[oe.type];return s.jsxs("div",{style:{position:"absolute",left:oe.x,top:oe.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ee}, 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(${ee}, 0.9)`,boxShadow:`0 0 12px rgba(${ee}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},oe.id)})]}),s.jsx(yu,{inputMode:M,onToggleInputMode:ae,isImeOpen:C,setIsImeOpen:I,isMenuOpen:y,setIsMenuOpen:g,imeText:h,setImeText:f,handleImeSubmit:ce,isConnActive:z,zoom:L,isMobile:v,mobileFillZoom:k,onZoomOut:()=>_(oe=>Math.max(.5,oe-.25)),onZoomReset:fe,onZoomIn:()=>_(oe=>Math.min(5,oe+.25)),transportType:i,screenshotUsage:a,lastActionStatus:m}),s.jsx("style",{children:`
|
|
5
5
|
@keyframes slideUp {
|
|
6
6
|
from { opacity: 0; transform: translateY(6px); }
|
|
7
7
|
to { opacity: 1; transform: translateY(0); }
|
|
@@ -24,60 +24,60 @@ var Jl=Object.defineProperty;var Ql=(e,t,r)=>t in e?Jl(e,t,{enumerable:!0,config
|
|
|
24
24
|
50% { transform: translateY(-7px); }
|
|
25
25
|
100% { transform: translateY(0px); }
|
|
26
26
|
}
|
|
27
|
-
`})]})}function Qr(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,i=Date.now()-e,c=Math.floor(i/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const u=Math.floor(l/60);if(u<24)return`${u}h${r}`;const m=Math.floor(u/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const Ui=e=>Qr(e);function Su(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function As(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function Nu(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...Su(a)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const a of n.childSessions||[])r(a.id,a)}return t}function Or(e,t){if(e.sessionId){const r=t.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function Zr(e,t,r){const n=Or(e,t),a=As(e),i=a.isReconnecting,c=a.isConnecting,l=a.isGenerating,u=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||u,d=n.inboxBucket==="working"||l,f=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:f,requiresAction:m,isWorking:d,isReconnecting:i,isConnecting:c,isGenerating:l,isWaiting:u,inboxBucket:m?"needs_attention":d?"working":f?"task_complete":"idle"}}function Cu(e,t,r){return Zr(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function zi({activeConv:e,onModalButton:t}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!As(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),t(l))},c=l=>l.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&s.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(Zs,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,u)=>{const m=c(l).toLowerCase(),d=/^(run|approve|accept|yes|allow|always)/.test(m),h=/^(reject|deny|delete|remove|abort)/.test(m),f=r===l,j=r!==null;return s.jsx("button",{onClick:()=>i(l),disabled:j,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${d?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${j&&!f?"opacity-40":"opacity-100"} ${j?"cursor-not-allowed":"cursor-pointer"}`,style:d?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:h?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:f?"⏳ ...":c(l)},u)})})]})]})}const Na="adhdev_controls_bar_visible",ea="adhdev:controlsbarvisibilitychange";function hn(e){if(!e)return!1;try{return e.getItem(Na)==="1"}catch{return!1}}function vo(e,t){if(t)try{t.setItem(Na,e?"1":"0")}catch{}}function wo(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ea,{detail:{visible:e}}))}function Vi(){const[e,t]=o.useState(()=>typeof window>"u"?!1:hn(window.localStorage));o.useEffect(()=>{const a=c=>{const l=c.detail;if(typeof(l==null?void 0:l.visible)=="boolean"){t(l.visible);return}t(hn(window.localStorage))},i=c=>{c.key===Na&&t(hn(window.localStorage))};return window.addEventListener(ea,a),window.addEventListener("storage",i),()=>{window.removeEventListener(ea,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 Mu=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Tu(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function bt(e,t){if(Tu(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Mu.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 Gi(e){return bt(e)==="generating"}function rt(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Iu(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const r=Math.floor(t/60),n=t%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),i=r%24;return`${a}d ${i}h`}function xn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function en(e,t){const r=typeof t=="string"?t.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),i=a.split(/[\\/]/).filter(Boolean);return i[i.length-1]||a}function Au(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 Lu(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Ru(e){return Au(e.trim().replace(/\.local$/i,""))}function _u(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function qi(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&&!Lu(c));if(r&&r!=="Unknown")return Ru(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Mt(e,t={}){return _u(e)||qi(e,t)}function Yi(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 Xi(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function cs(e,t){return Yi(e).join(" · ")}function tr(e){return e.transport==="pty"}function gs(e){return e.transport==="acp"}function Pu(e,t){var r,n;return(r=t==null?void 0:t.providerLabels)!=null&&r[e]?t.providerLabels[e]:(n=t==null?void 0:t.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:rt(e)}function jo(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=rt(r||"").trim().toLowerCase();return n===a||n===i||n===c}function Du(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Eu(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=t.get(a),c=bt(n.status);if(!i){t.set(a,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),u=r.indexOf(c||"idle");u>=0&&(l<0||u<l)&&t.set(a,{...n,status:c})}return Array.from(t.values())}function $u(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 Bu(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&&$u(t.receivedAt)||0}function Ku(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ta(e){return Math.max(Ku(e),Bu(e.activeChat))}function Ou(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 Ca(e,t){return Ou(ta(e),ta(t),Mt(e,{fallbackId:e.id}),Mt(t,{fallbackId:t.id}),e.id,t.id)}const Ji="adhdev_notification_prefs",ko={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Wu(){try{const e=localStorage.getItem(Ji);if(e){const t=JSON.parse(e);return{...ko,...t}}}catch{}return{...ko}}function Hu(e){try{localStorage.setItem(Ji,JSON.stringify(e))}catch{}}let Kt=Wu(),Mr=[];function Fu(){Mr.forEach(e=>e())}function Uu(e){Kt={...Kt,...e},Hu(Kt),Fu()}function zu(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Mr.push(r),()=>{Mr=Mr.filter(n=>n!==r)}},[]);const t=o.useCallback(r=>{Uu(r)},[]);return[{...Kt},t]}function Vs(e){if(!Kt.globalEnabled)return!1;switch(e){case"disconnect":return Kt.disconnectAlert;case"completion":return Kt.completionAlert;case"approval":return Kt.approvalAlert;case"browser":return Kt.browserNotifications;default:return!0}}const Vu={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Qi(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Zi(){return"Notification"in window&&Notification.permission==="granted"}let qt=null;function Gu(e){return e!==!1}async function qu(){if(qt!==null)return qt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return qt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(qt=!!await e.pushManager.getSubscription(),qt):(qt=!1,!1)}catch{return qt=!1,!1}}function sa(e,t,r){if(Zi())try{const n=new Notification(e,{body:t,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function Yu(e,t={}){const r={...Vu,...t},n=o.useRef(new Map),a=o.useRef(0),[i,c]=o.useState(null);o.useEffect(()=>{let u=!1;return qu().then(m=>{u||c(m)}),()=>{u=!0}},[]);const l=o.useCallback((u,m,d)=>{const h=Date.now();h-a.current<r.throttleMs||(a.current=h,sa(u,m,d))},[r.throttleMs]);o.useEffect(()=>{var u;if(!(!r.enabled||!Zi())&&Vs("browser")&&!Gu(i)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,bt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const d=n.current.get(m.id),h=bt(m.status,{activeModal:m.activeModal}),f=m.name||m.id;if(r.onApproval&&Vs("approval")&&h==="waiting_approval"&&d!=="waiting_approval"){const j=((u=m.activeModal)==null?void 0:u.message)||"Action requires your approval";l(`🔔 ${f} — Approval needed`,j.slice(0,120),`approval-${m.id}`)}r.onComplete&&Vs("completion")&&Gi(d)&&h==="idle"&&l(`✅ ${f} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&h==="error"&&d!=="error"&&l(`⚠️ ${f} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,h)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,i,l])}const Xu=/^(run|approve|accept|yes|allow|always)/,Ju=/^(run|approve|accept|yes|allow|always|proceed|save)/,Qu=/^(reject|deny|delete|remove|abort|cancel|no)/;function Ma(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Zu(e){const t=Ma(e).toLowerCase();return Xu.test(t)?"primary":Qu.test(t)?"danger":"default"}function em(e){return Ju.test(Ma(e).toLowerCase())?"approve":"reject"}function tm(e){return e.map((t,r)=>({label:Ma(t),variant:Zu(t),action:em(t),button:t,buttonIndex:r}))}function sm(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function rm(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 nm{constructor(){ze(this,"dedupMap",new Map);ze(this,"DEDUP_WINDOW_MS",5e3);ze(this,"DEDUP_MAX_SIZE",50);ze(this,"DEDUP_CLEANUP_AGE_MS",1e4);ze(this,"toastCallbacks",[]);ze(this,"resolveActionFn",null);ze(this,"viewRequestRespondFn",null);ze(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(i=>i.id===t.daemonId&&i.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const i=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var N;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),i=n||t.daemonId||"",c=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),l=`${i}:${t.event}:${c}`;if(this.isDuplicate(l))return;const u=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(u==null?void 0:u.type)||"";let d=rt(m);const h=this.resolveOwningDaemon(t);if(h){const p=Mt(h,{fallbackId:h.id});p&&(d=!m||m==="adhdev-daemon"?p:`${p}/${d}`)}let f="",j="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";f=`✅ ${d} agent task completed${p}`,j="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(f=`⚡ ${d} approval needed`,j="warning",(N=t.modalButtons)!=null&&N.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const x=this.resolveActionFn,y=tm(t.modalButtons).map(I=>({label:I.label,variant:I.variant,onClick:()=>{x(p,"resolve_action",{action:I.action,button:I.button,buttonIndex:I.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),g=sm(d,t.modalMessage,f),C=Date.now();this.emitToast({id:C,message:g,type:j,timestamp:C,targetKey:n||p,actions:y,duration:15e3}),f=""}}else if(t.event==="monitor:long_generating"){const p=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";f=`⚠️ ${d} agent is taking a long time${p}`,j="warning",Vs("browser")&&!document.hasFocus()&&sa(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const p=t.requesterName||"A team member",x=t.requestId,y=t.orgId;if(f=`👁️ ${p} wants to view your session`,j="warning",x&&y&&this.viewRequestRespondFn){const g=Date.now(),C=rm(y,x,this.viewRequestRespondFn,(I,v)=>console.error(`[EventManager] ${I} view request failed:`,v));this.emitToast({id:g,message:f,type:j,timestamp:g,actions:C,duration:3e4}),f=""}Vs("browser")&&!document.hasFocus()&&sa("👁️ View Request",`${p} wants to view your session`,`view-request-${x}`)}else t.event==="team:view_request_approved"?(f="✅ View request approved",j="success"):t.event==="team:view_request_rejected"&&(f=`❌ ${t.targetName||"Team member"} declined your view request`,j="warning");if(f){const p=Date.now();this.emitToast({id:p,message:f,type:j,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const it=new nm,So=new Map;function Wr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ys(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function tn(e){return Wr(e)?Wr(e.result)?e.result:e:null}function am(e){const t=tn(e);return!t||!Wr(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function pr(e){const t=tn(e);return!t||!Wr(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Ds(e){const t=tn(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function hr(e){const t=tn(e);return!!t&&t.success===!1}function om(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";it.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";it.showToast(n.notification.body,a)}}}function im(e,t){return e&&ys(e.currentValue)?e.currentValue:t}function cm(e,t){return ys(t)?ys(e)?typeof e=="string"&&e.trim()==="":!0:!1}function lm(e,t){var i,c;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(ys(l))return l}const n=(i=t.controlValues)==null?void 0:i[e];if(ys(n))return n;const a=(c=t.defaultValues)==null?void 0:c[e];return ys(a)?a:void 0}function Tr(e,t){return e.options||t[e.id]||[]}const dm={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 um(e,t,r){var n;return((n=dm[t])==null?void 0:n.has(r.id))===!0}function Ta(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!um(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function bn(e,t){return{value:t}}function mm(e,t,r){var a;return r?((a=Tr(e,t).find(i=>i.value===r))==null?void 0:a.label)||r:""}const fm={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function pm({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=wt(),u=`${e}:${t||n}`,m=fm[n]||"#94a3b8",[d,h]=o.useState({}),f=o.useRef({}),j=o.useRef(c);f.current=d,j.current=c;const N=o.useRef(0),p={};for(const A of i||[])A.defaultValue!==void 0&&(p[A.id]=A.defaultValue);const x={...p,...c||{},...Date.now()<N.current?d:{}};o.useEffect(()=>{c&&Date.now()>N.current&&h({})},[c]);const[y,g]=o.useState(So.get(u)||{}),[C,I]=o.useState(null),[v,T]=o.useState(null),S=o.useCallback(async(A,U={})=>{const $={...U,...t&&{targetSessionId:t}};return await l(e,A,$)},[e,t,l]),k=o.useCallback(async(A,U={})=>{const $=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await S("invoke_provider_script",{...$,scriptName:A,...U})},[S,n,r,t]),b=o.useCallback((A,U,$)=>{const E=im($,U);h(z=>({...z,[A.id]:E})),om($==null?void 0:$.effects)},[]),B=o.useCallback((A,U)=>{h($=>{const E={...$};return U===void 0?delete E[A.id]:E[A.id]=U,E}),N.current=0},[]);if(!i||i.length===0)return null;const L=Ta(i,{hostIdeType:r,providerType:n});if(L.length===0)return null;const _=async A=>{if(C===A.id){I(null);return}if(Tr(A,y).length>0){I(A.id);return}if(A.dynamic&&A.listScript){T(A.id);try{const $=await k(A.listScript,{}),E=am($);if(!E){const ve=Ds($);ve&&it.showToast(ve,"warning");return}const z=E.options;g(ve=>{const re={...ve,[A.id]:z};return So.set(u,re),re});const Y=lm(A.id,{localOverrideUntil:N.current,localValues:f.current,controlValues:j.current,defaultValues:p});if(cm(Y,E.currentValue)){const ve=E.currentValue;h(re=>({...re,[A.id]:ve}))}I(A.id)}catch($){const E=$ instanceof Error?$.message:`Could not load ${A.label}`;it.showToast(E,"warning")}finally{T(null)}}},H=async(A,U)=>{I(null);const $=(c==null?void 0:c[A.id])??p[A.id];h(E=>({...E,[A.id]:U})),N.current=Date.now()+5e3;try{if(!A.setScript)return;const E=await k(A.setScript,bn(A,U)),z=pr(E);if(z&&!z.ok||hr(E))throw new Error((z==null?void 0:z.error)||Ds(E)||`Could not update ${A.label}`);b(A,U,z)}catch(E){B(A,$);const z=E instanceof Error?E.message:`Could not update ${A.label}`;it.showToast(z,"warning")}},F=async A=>{const U=Tr(A,y).map(re=>re.value);if(U.length===0)return;const $=String(x[A.id]||""),z=(U.indexOf($)+1)%U.length,Y=U[z];if(typeof Y!="string")return;const ve=(c==null?void 0:c[A.id])??p[A.id];h(re=>({...re,[A.id]:Y})),N.current=Date.now()+5e3;try{if(!A.setScript)return;const re=await k(A.setScript,bn(A,Y)),ye=pr(re);if(ye&&!ye.ok||hr(re))throw new Error((ye==null?void 0:ye.error)||Ds(re)||`Could not update ${A.label}`);b(A,Y,ye)}catch(re){B(A,ve);const ye=re instanceof Error?re.message:`Could not update ${A.label}`;it.showToast(ye,"warning")}},O=async A=>{const $=!x[A.id],E=(c==null?void 0:c[A.id])??p[A.id];h(z=>({...z,[A.id]:$})),N.current=Date.now()+5e3;try{if(!A.setScript)return;const z=await k(A.setScript,bn(A,$)),Y=pr(z);if(Y&&!Y.ok||hr(z))throw new Error((Y==null?void 0:Y.error)||Ds(z)||`Could not update ${A.label}`);b(A,$,Y)}catch(z){B(A,E);const Y=z instanceof Error?z.message:`Could not update ${A.label}`;it.showToast(Y,"warning")}},M=async A=>{if(!A.invokeScript)return;if(A.confirmMessage){const $=[A.confirmTitle,A.confirmMessage,A.confirmLabel].filter(z=>typeof z=="string"&&z.trim().length>0);if(!window.confirm($.join(`
|
|
27
|
+
`})]})}function Qr(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,i=Date.now()-e,c=Math.floor(i/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const u=Math.floor(l/60);if(u<24)return`${u}h${r}`;const m=Math.floor(u/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const Fi=e=>Qr(e);function ku(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function As(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function Su(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...ku(a)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const a of n.childSessions||[])r(a.id,a)}return t}function Or(e,t){if(e.sessionId){const r=t.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function Zr(e,t,r){const n=Or(e,t),a=As(e),i=a.isReconnecting,c=a.isConnecting,l=a.isGenerating,u=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||u,d=n.inboxBucket==="working"||l,f=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:f,requiresAction:m,isWorking:d,isReconnecting:i,isConnecting:c,isGenerating:l,isWaiting:u,inboxBucket:m?"needs_attention":d?"working":f?"task_complete":"idle"}}function Nu(e,t,r){return Zr(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Ui({activeConv:e,onModalButton:t}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!As(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),t(l))},c=l=>l.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&s.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(Zs,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,u)=>{const m=c(l).toLowerCase(),d=/^(run|approve|accept|yes|allow|always)/.test(m),h=/^(reject|deny|delete|remove|abort)/.test(m),f=r===l,j=r!==null;return s.jsx("button",{onClick:()=>i(l),disabled:j,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${d?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${j&&!f?"opacity-40":"opacity-100"} ${j?"cursor-not-allowed":"cursor-pointer"}`,style:d?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:h?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:f?"⏳ ...":c(l)},u)})})]})]})}const Na="adhdev_controls_bar_visible",ea="adhdev:controlsbarvisibilitychange";function hn(e){if(!e)return!1;try{return e.getItem(Na)==="1"}catch{return!1}}function vo(e,t){if(t)try{t.setItem(Na,e?"1":"0")}catch{}}function wo(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ea,{detail:{visible:e}}))}function zi(){const[e,t]=o.useState(()=>typeof window>"u"?!1:hn(window.localStorage));o.useEffect(()=>{const a=c=>{const l=c.detail;if(typeof(l==null?void 0:l.visible)=="boolean"){t(l.visible);return}t(hn(window.localStorage))},i=c=>{c.key===Na&&t(hn(window.localStorage))};return window.addEventListener(ea,a),window.addEventListener("storage",i),()=>{window.removeEventListener(ea,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 Cu=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Tu(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function bt(e,t){if(Tu(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Cu.has(r)?"generating":r==="error"?"error":r==="stopped"?"stopped":r==="starting"?"starting":r==="panel_hidden"?"panel_hidden":r==="not_monitored"?"not_monitored":r==="disconnected"?"disconnected":"idle"}function Vi(e){return bt(e)==="generating"}function rt(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Mu(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const r=Math.floor(t/60),n=t%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),i=r%24;return`${a}d ${i}h`}function xn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function en(e,t){const r=typeof t=="string"?t.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),i=a.split(/[\\/]/).filter(Boolean);return i[i.length-1]||a}function Iu(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),r=t[t.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function Au(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Lu(e){return Iu(e.trim().replace(/\.local$/i,""))}function Ru(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function Gi(e,t={}){var a,i;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(i=e.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!Au(c));if(r&&r!=="Unknown")return Lu(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Tt(e,t={}){return Ru(e)||Gi(e,t)}function qi(e){return!e||!Array.isArray(e.items)?[]:e.items.map(t=>String((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim()).filter(Boolean)}function Yi(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function cs(e,t){return qi(e).join(" · ")}function tr(e){return e.transport==="pty"}function gs(e){return e.transport==="acp"}function _u(e,t){var r,n;return(r=t==null?void 0:t.providerLabels)!=null&&r[e]?t.providerLabels[e]:(n=t==null?void 0:t.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:rt(e)}function jo(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=rt(r||"").trim().toLowerCase();return n===a||n===i||n===c}function Pu(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Du(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=t.get(a),c=bt(n.status);if(!i){t.set(a,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),u=r.indexOf(c||"idle");u>=0&&(l<0||u<l)&&t.set(a,{...n,status:c})}return Array.from(t.values())}function Eu(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function $u(e){var r,n;const t=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return t&&Eu(t.receivedAt)||0}function Bu(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ta(e){return Math.max(Bu(e),$u(e.activeChat))}function Ku(e,t,r,n,a,i){const c=t-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(i)}function Ca(e,t){return Ku(ta(e),ta(t),Tt(e,{fallbackId:e.id}),Tt(t,{fallbackId:t.id}),e.id,t.id)}const Xi="adhdev_notification_prefs",ko={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Ou(){try{const e=localStorage.getItem(Xi);if(e){const t=JSON.parse(e);return{...ko,...t}}}catch{}return{...ko}}function Wu(e){try{localStorage.setItem(Xi,JSON.stringify(e))}catch{}}let Kt=Ou(),Tr=[];function Hu(){Tr.forEach(e=>e())}function Fu(e){Kt={...Kt,...e},Wu(Kt),Hu()}function Uu(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Tr.push(r),()=>{Tr=Tr.filter(n=>n!==r)}},[]);const t=o.useCallback(r=>{Fu(r)},[]);return[{...Kt},t]}function Vs(e){if(!Kt.globalEnabled)return!1;switch(e){case"disconnect":return Kt.disconnectAlert;case"completion":return Kt.completionAlert;case"approval":return Kt.approvalAlert;case"browser":return Kt.browserNotifications;default:return!0}}const zu={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Ji(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Qi(){return"Notification"in window&&Notification.permission==="granted"}let qt=null;function Vu(e){return e!==!1}async function Gu(){if(qt!==null)return qt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return qt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(qt=!!await e.pushManager.getSubscription(),qt):(qt=!1,!1)}catch{return qt=!1,!1}}function sa(e,t,r){if(Qi())try{const n=new Notification(e,{body:t,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function qu(e,t={}){const r={...zu,...t},n=o.useRef(new Map),a=o.useRef(0),[i,c]=o.useState(null);o.useEffect(()=>{let u=!1;return Gu().then(m=>{u||c(m)}),()=>{u=!0}},[]);const l=o.useCallback((u,m,d)=>{const h=Date.now();h-a.current<r.throttleMs||(a.current=h,sa(u,m,d))},[r.throttleMs]);o.useEffect(()=>{var u;if(!(!r.enabled||!Qi())&&Vs("browser")&&!Vu(i)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,bt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const d=n.current.get(m.id),h=bt(m.status,{activeModal:m.activeModal}),f=m.name||m.id;if(r.onApproval&&Vs("approval")&&h==="waiting_approval"&&d!=="waiting_approval"){const j=((u=m.activeModal)==null?void 0:u.message)||"Action requires your approval";l(`🔔 ${f} — Approval needed`,j.slice(0,120),`approval-${m.id}`)}r.onComplete&&Vs("completion")&&Vi(d)&&h==="idle"&&l(`✅ ${f} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&h==="error"&&d!=="error"&&l(`⚠️ ${f} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,h)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,i,l])}const Yu=/^(run|approve|accept|yes|allow|always)/,Xu=/^(run|approve|accept|yes|allow|always|proceed|save)/,Ju=/^(reject|deny|delete|remove|abort|cancel|no)/;function Ta(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=Ta(e).toLowerCase();return Yu.test(t)?"primary":Ju.test(t)?"danger":"default"}function Zu(e){return Xu.test(Ta(e).toLowerCase())?"approve":"reject"}function em(e){return e.map((t,r)=>({label:Ta(t),variant:Qu(t),action:Zu(t),button:t,buttonIndex:r}))}function tm(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function sm(e,t,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,t,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,t,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class rm{constructor(){ze(this,"dedupMap",new Map);ze(this,"DEDUP_WINDOW_MS",5e3);ze(this,"DEDUP_MAX_SIZE",50);ze(this,"DEDUP_CLEANUP_AGE_MS",1e4);ze(this,"toastCallbacks",[]);ze(this,"resolveActionFn",null);ze(this,"viewRequestRespondFn",null);ze(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(i=>i.id===t.daemonId&&i.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const i=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var N;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),i=n||t.daemonId||"",c=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),l=`${i}:${t.event}:${c}`;if(this.isDuplicate(l))return;const u=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(u==null?void 0:u.type)||"";let d=rt(m);const h=this.resolveOwningDaemon(t);if(h){const p=Tt(h,{fallbackId:h.id});p&&(d=!m||m==="adhdev-daemon"?p:`${p}/${d}`)}let f="",j="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";f=`✅ ${d} agent task completed${p}`,j="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(f=`⚡ ${d} approval needed`,j="warning",(N=t.modalButtons)!=null&&N.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const x=this.resolveActionFn,y=em(t.modalButtons).map(I=>({label:I.label,variant:I.variant,onClick:()=>{x(p,"resolve_action",{action:I.action,button:I.button,buttonIndex:I.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),g=tm(d,t.modalMessage,f),C=Date.now();this.emitToast({id:C,message:g,type:j,timestamp:C,targetKey:n||p,actions:y,duration:15e3}),f=""}}else if(t.event==="monitor:long_generating"){const p=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";f=`⚠️ ${d} agent is taking a long time${p}`,j="warning",Vs("browser")&&!document.hasFocus()&&sa(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const p=t.requesterName||"A team member",x=t.requestId,y=t.orgId;if(f=`👁️ ${p} wants to view your session`,j="warning",x&&y&&this.viewRequestRespondFn){const g=Date.now(),C=sm(y,x,this.viewRequestRespondFn,(I,v)=>console.error(`[EventManager] ${I} view request failed:`,v));this.emitToast({id:g,message:f,type:j,timestamp:g,actions:C,duration:3e4}),f=""}Vs("browser")&&!document.hasFocus()&&sa("👁️ View Request",`${p} wants to view your session`,`view-request-${x}`)}else t.event==="team:view_request_approved"?(f="✅ View request approved",j="success"):t.event==="team:view_request_rejected"&&(f=`❌ ${t.targetName||"Team member"} declined your view request`,j="warning");if(f){const p=Date.now();this.emitToast({id:p,message:f,type:j,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const it=new rm,So=new Map;function Wr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ys(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function tn(e){return Wr(e)?Wr(e.result)?e.result:e:null}function nm(e){const t=tn(e);return!t||!Wr(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function pr(e){const t=tn(e);return!t||!Wr(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Ds(e){const t=tn(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function hr(e){const t=tn(e);return!!t&&t.success===!1}function am(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";it.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";it.showToast(n.notification.body,a)}}}function om(e,t){return e&&ys(e.currentValue)?e.currentValue:t}function im(e,t){return ys(t)?ys(e)?typeof e=="string"&&e.trim()==="":!0:!1}function cm(e,t){var i,c;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(ys(l))return l}const n=(i=t.controlValues)==null?void 0:i[e];if(ys(n))return n;const a=(c=t.defaultValues)==null?void 0:c[e];return ys(a)?a:void 0}function Mr(e,t){return e.options||t[e.id]||[]}const lm={antigravity:new Set(["new_session"]),"claude-cli":new Set(["compact","new_session"]),"claude-code-vscode":new Set(["new_session"]),codex:new Set(["new_session"])};function dm(e,t,r){var n;return((n=lm[t])==null?void 0:n.has(r.id))===!0}function Ma(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!dm(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function bn(e,t){return{value:t}}function um(e,t,r){var a;return r?((a=Mr(e,t).find(i=>i.value===r))==null?void 0:a.label)||r:""}const mm={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function fm({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=wt(),u=`${e}:${t||n}`,m=mm[n]||"#94a3b8",[d,h]=o.useState({}),f=o.useRef({}),j=o.useRef(c);f.current=d,j.current=c;const N=o.useRef(0),p={};for(const A of i||[])A.defaultValue!==void 0&&(p[A.id]=A.defaultValue);const x={...p,...c||{},...Date.now()<N.current?d:{}};o.useEffect(()=>{c&&Date.now()>N.current&&h({})},[c]);const[y,g]=o.useState(So.get(u)||{}),[C,I]=o.useState(null),[v,M]=o.useState(null),S=o.useCallback(async(A,U={})=>{const $={...U,...t&&{targetSessionId:t}};return await l(e,A,$)},[e,t,l]),k=o.useCallback(async(A,U={})=>{const $=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await S("invoke_provider_script",{...$,scriptName:A,...U})},[S,n,r,t]),b=o.useCallback((A,U,$)=>{const E=om($,U);h(z=>({...z,[A.id]:E})),am($==null?void 0:$.effects)},[]),B=o.useCallback((A,U)=>{h($=>{const E={...$};return U===void 0?delete E[A.id]:E[A.id]=U,E}),N.current=0},[]);if(!i||i.length===0)return null;const L=Ma(i,{hostIdeType:r,providerType:n});if(L.length===0)return null;const _=async A=>{if(C===A.id){I(null);return}if(Mr(A,y).length>0){I(A.id);return}if(A.dynamic&&A.listScript){M(A.id);try{const $=await k(A.listScript,{}),E=nm($);if(!E){const ve=Ds($);ve&&it.showToast(ve,"warning");return}const z=E.options;g(ve=>{const re={...ve,[A.id]:z};return So.set(u,re),re});const Y=cm(A.id,{localOverrideUntil:N.current,localValues:f.current,controlValues:j.current,defaultValues:p});if(im(Y,E.currentValue)){const ve=E.currentValue;h(re=>({...re,[A.id]:ve}))}I(A.id)}catch($){const E=$ instanceof Error?$.message:`Could not load ${A.label}`;it.showToast(E,"warning")}finally{M(null)}}},H=async(A,U)=>{I(null);const $=(c==null?void 0:c[A.id])??p[A.id];h(E=>({...E,[A.id]:U})),N.current=Date.now()+5e3;try{if(!A.setScript)return;const E=await k(A.setScript,bn(A,U)),z=pr(E);if(z&&!z.ok||hr(E))throw new Error((z==null?void 0:z.error)||Ds(E)||`Could not update ${A.label}`);b(A,U,z)}catch(E){B(A,$);const z=E instanceof Error?E.message:`Could not update ${A.label}`;it.showToast(z,"warning")}},F=async A=>{const U=Mr(A,y).map(re=>re.value);if(U.length===0)return;const $=String(x[A.id]||""),z=(U.indexOf($)+1)%U.length,Y=U[z];if(typeof Y!="string")return;const ve=(c==null?void 0:c[A.id])??p[A.id];h(re=>({...re,[A.id]:Y})),N.current=Date.now()+5e3;try{if(!A.setScript)return;const re=await k(A.setScript,bn(A,Y)),ye=pr(re);if(ye&&!ye.ok||hr(re))throw new Error((ye==null?void 0:ye.error)||Ds(re)||`Could not update ${A.label}`);b(A,Y,ye)}catch(re){B(A,ve);const ye=re instanceof Error?re.message:`Could not update ${A.label}`;it.showToast(ye,"warning")}},O=async A=>{const $=!x[A.id],E=(c==null?void 0:c[A.id])??p[A.id];h(z=>({...z,[A.id]:$})),N.current=Date.now()+5e3;try{if(!A.setScript)return;const z=await k(A.setScript,bn(A,$)),Y=pr(z);if(Y&&!Y.ok||hr(z))throw new Error((Y==null?void 0:Y.error)||Ds(z)||`Could not update ${A.label}`);b(A,$,Y)}catch(z){B(A,E);const Y=z instanceof Error?z.message:`Could not update ${A.label}`;it.showToast(Y,"warning")}},T=async A=>{if(!A.invokeScript)return;if(A.confirmMessage){const $=[A.confirmTitle,A.confirmMessage,A.confirmLabel].filter(z=>typeof z=="string"&&z.trim().length>0);if(!window.confirm($.join(`
|
|
28
28
|
|
|
29
|
-
`)))return}const U=(c==null?void 0:c[A.id])??p[A.id];try{const $=await k(A.invokeScript),E=pr($);if(E&&!E.ok||hr($))throw new Error((E==null?void 0:E.error)||Ds($)||`Could not run ${A.label}`);E&&b(A,U??!0,E)}catch($){B(A,U);const E=$ instanceof Error?$.message:`Could not run ${A.label}`;it.showToast(E,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${m}33`,background:`${m}12`,color:m},children:a}),L.map(A=>{const U=String(x[A.id]||""),$=mm(A,y,U),E=C===A.id,z=v===A.id,Y=Tr(A,y),ve="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(A.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${ve} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${m}55`:"var(--border-default)",background:E?`${m}10`:"var(--surface-tertiary)",color:U?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void _(A),title:A.label,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:z?"Loading…":$||A.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),E&&Y.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>I(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:A.label}),Y.map(re=>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:re.value===U?`${m}14`:"transparent",color:re.value===U?"var(--text-primary)":"var(--text-secondary)",borderLeft:re.value===U?`2px solid ${m}`:"2px solid transparent"},title:re.description||re.label,onMouseEnter:ye=>{ye.currentTarget.style.background=`${m}10`},onMouseLeave:ye=>{ye.currentTarget.style.background=re.value===U?`${m}14`:"transparent"},onClick:()=>void H(A,re.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:re.label}),re.value===U&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},re.value))]})]})]},A.id);case"cycle":return s.jsxs("button",{type:"button",className:`${ve} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:U?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void F(A),title:`Click to cycle: ${Y.map(re=>re.label).join(" → ")}`,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$||A.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},A.id);case"toggle":return s.jsxs("button",{type:"button",className:`${ve} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:U?`${m}44`:"var(--border-default)",background:U?`${m}14`:"var(--surface-tertiary)",color:U?m:"var(--text-muted)"},onClick:()=>void O(A),"aria-pressed":!!U,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),A.label]},A.id);case"action":return s.jsxs("button",{type:"button",className:`${ve} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void M(A),children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:A.resultDisplay==="inline"&&U?`${A.label}: ${U}`:A.label})]},A.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:U?"var(--text-primary)":"var(--text-muted)"},children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:U?`${A.label}: ${U}`:A.label})]},A.id);default:return null}})]})})}function hm({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:m}=Vi(),d=Ta(l,{hostIdeType:a,providerType:i});return!e||t||d.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(pm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:d,controlValues:u})})}function xm({hasDraft:e,isBusy:t=!1}){return!e||t}const ec=o.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1,animateVisibility:m=!0}){const d=o.useRef(null),[h,f]=o.useState(""),{isVisible:j,toggleVisibility:N}=Vi();o.useEffect(()=>{f("")},[t]),o.useEffect(()=>{var x;l&&((x=d.current)==null||x.focus({preventScroll:!0}))},[t,l]);const p=async()=>{const x=h.trim();if(!x||a)return;await c(x)!==!1&&f("")};return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":""].filter(Boolean).join(" "),style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[s.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[u&&s.jsx("button",{type:"button",onClick:N,"aria-label":j?"Hide controls":"Show controls","aria-pressed":j,title:j?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("input",{ref:d,type:"text",placeholder:i||`Send message to ${r}...`,value:h,onChange:x=>f(x.target.value),onPaste:x=>{const y=x.clipboardData.getData("text");y&&f(g=>g+y),x.preventDefault()},onKeyDown:x=>{if(x.key==="Enter"){if(x.nativeEvent.isComposing){x.preventDefault();return}x.preventDefault(),p()}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),s.jsx("button",{onClick:()=>{p()},disabled:xm({hasDraft:!!h.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${h.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:h.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:h.trim()?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),Qe=e=>e.transport==="pty",Ls=(e,t)=>Qe(e)?e.mode||"terminal":"chat",tc=(e,t)=>Qe(e)&&Ls(e)==="terminal",Ve=e=>e.transport==="acp";function Ut(e){return e.streamSource!=="agent-stream"}function ms(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function sc(e){return e.machineName||""}function Rs(e){return ms(e)}function $t(e){return e.agentType||""}function Hr(e){return e.hostIdeType||""}function Ia(e){return e.displayPrimary||e.agentName||"Agent"}function rc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function bm(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function 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 gm(e){return No(e==null?void 0:e.receivedAt)||No(e==null?void 0:e.timestamp)||0}function nc(e){const t=bm(e),r=ks(t==null?void 0:t.content),n=gm(t),a=ks(e.lastMessagePreview),i=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0;return a&&!r?a:r&&!a?r:a&&r&&i>0&&n>0&&i>n?a:r||a||""}function ym(e){return nc(e)||e.displaySecondary||""}function ac(e){return[e.displaySecondary,sc(e)].filter(Boolean)}function Ns(e){return e.agentName||rt($t(e))}function vm(e){var t,r;if(!Ut(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return rt(Hr(e)||$t(e))}function oc(e){return Ut(e)?e.sessionId:e.nativeSessionId}function Co(e){return Ut(e)?"native":e.tabKey}function wm(e){return e.sessionId}function jm(e,t){if(t)return Ut(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function km(e,t){const r=$t(e),n=Ut(e),a=Qe(e)||Ve(e),i=n?a?Ns(e)||(t==null?void 0:t.cliName)||rt(Hr(e)||r):t!=null&&t.type?rt(t.type):rt(Hr(e)||r):Ns(e);return{isNativeConversation:n,isCli:Qe(e),isAcp:Ve(e),isCliTerminal:tc(e),providerType:r,displayLabel:i,targetEntry:jm(e,t)}}function gt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ot(e,t){const r=gt(t);return r?`${e}:${r}`:void 0}function Ft(e,t,r){const n=Ot(t,r),a=gt(r);n&&e.push(n),a&&e.push(a)}function bs(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function ic(e){return gt(e.providerSessionId)||gt(e.sessionId)||gt(e.tabKey)||gt(e.routeId)}function Aa(e){return bs([gt(e.providerSessionId),gt(e.sessionId)])}function vs(e){const t=[];return Ft(t,"provider",e.providerSessionId),Ft(t,"session",e.sessionId),Ft(t,"tab",e.tabKey),Ft(t,"route",e.routeId),bs(t)}function Sm(e){const t=[];return gt(e.providerSessionId)?(Ft(t,"provider",e.providerSessionId),bs(t)):gt(e.sessionId)?(Ft(t,"session",e.sessionId),bs(t)):gt(e.tabKey)?(Ft(t,"tab",e.tabKey),bs(t)):gt(e.routeId)?(Ft(t,"route",e.routeId),bs(t)):[]}function La(e){return Ot("provider",e.providerSessionId)||Ot("session",e.sessionId)||Ot("tab",e.tabKey)||Ot("route",e.routeId)||"unknown:"}function or(e){return Aa(e)[0]}function Nm(e){const t=gt(e.providerSessionId),r=gt(e.sessionId),n=gt(e.tabKey),a=gt(e.routeId),i=[Ot("provider",t),Ot("session",r),Ot("tab",n),Ot("route",a)].filter(u=>typeof u=="string"),c=vs({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=La({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:ic({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:or({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function ra(e,t){const r=Nm(e);return Sm(t).some(n=>r.lookupKeys.includes(n))}function Mo(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Qt(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],r=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,n=Mo(t==null?void 0:t.receivedAt)||Mo(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function na(e,t=0){return Qt(e)||e.lastUpdated||t||0}function cc(e){return Qt(e)||e.lastUpdated||0}function lc(e,t,r=cc){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 aa(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 Cm(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!aa(e)&&!e.title.trim()}function Mm(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(aa(r))-Number(aa(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:lc(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=Mm(a);return n?i&&Cm(n)?i:n:i||r[0]||null}function zt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ra(e){return or(e)||e.tabKey||e.routeId||null}function dc(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?Ra(a):null}function uc({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Is(),c=ms(e),l=sc(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",m=e.streamSource==="agent-stream"&&!!e.agentName,d=!m&&(e.transport==="pty"||e.transport==="acp"),h=Ns(e),f=vm(e),j=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),N=o.useCallback(()=>{if(r){r();return}const p=Ra(e);p&&i(zt(p))},[e,i,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:N,title:f,children:[s.jsx(St,{size:12}),s.jsx("span",{children:f})]}):s.jsxs("span",{className:"conversation-meta-chip",title:f,children:[s.jsx(St,{size:12}),s.jsx("span",{children:f})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(er,{size:12}),s.jsx("span",{children:h})]}),d&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(er,{size:12}),s.jsx("span",{children:h})]}),l&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:j,title:l,children:[s.jsx(is,{size:12}),s.jsx("span",{children:l})]}):s.jsxs("span",{className:"conversation-meta-chip",title:l,children:[s.jsx(is,{size:12}),s.jsx("span",{children:l})]}))]})}function gn(e,t){return`${e}:${t}`}function Tm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Es(e,t){Tm()&&console.debug(`[subscription-manager] ${e}`,t)}class Im{constructor(){ze(this,"active",new Map);ze(this,"retryTimers",new Map)}subscribe(t,r,n,a,i){var d;const c=gn(n.topic,n.key),l=this.active.get(c);let u=!0;if(l)l.handlers.add(a),l.lastUpdate&&a(l.lastUpdate);else{const h={daemonId:r,request:n,handlers:new Set([a])};this.active.set(c,h),Es("subscribe",{daemonId:r,topic:n.topic,key:n.key}),u=((d=t.sendData)==null?void 0:d.call(t,r,n))??!1,!u&&(i!=null&&i.retryIntervalMs)&&this.scheduleRetry(c,t,i.retryIntervalMs)}const m=()=>{var j;this.clearRetry(c);const h=this.active.get(c);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(c);const f={type:"unsubscribe",topic:n.topic,key:n.key};Es("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(j=t.sendData)==null||j.call(t,r,f)};return m.initialSendAccepted=u,m}publish(t){const r=gn(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,js.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),n.handlers.forEach(a=>{a(t),js.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,r,n){const a=gn(t,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(t){var r;Es("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=t.sendData)==null||r.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,r){var a;const n=Array.from(this.active.values()).filter(i=>i.daemonId===t);Es("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}scheduleRetry(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var l;this.retryTimers.delete(t);const i=this.active.get(t);if(!i)return;const c=((l=r.sendData)==null?void 0:l.call(r,i.daemonId,i.request))??!1;Es("subscribe_retry",{id:t,accepted:c,topic:i.request.topic,key:i.request.key}),c||this.scheduleRetry(t,r,n)},n);this.retryTimers.set(t,a)}clearRetry(t){const r=this.retryTimers.get(t);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(t))}}const Vt=new Im;function Am(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 Lm(e){const t=[],r=new Map;for(const n of e)if(n.parentId){const a=r.get(n.parentId)||[];a.push(n),r.set(n.parentId,a)}else t.push(n);return{topLevel:t,childrenByParent:r}}function Fr(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=t,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:m,childrenByParent:d}=Lm(u),h=Am(i,n),f=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,j=m.filter(x=>x.kind==="workspace"&&x.transport==="cdp-page"),N=m.filter(x=>x.kind==="agent"&&x.transport==="pty"),p=m.filter(x=>x.kind==="agent"&&x.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...f&&{machine:f,platform:f.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:j.some(x=>!!x.cdpConnected)});for(const x of j){const y=h.get(x.id),g=Fs(x,y),C=(d.get(x.id)||[]).map(I=>Fs(I,h.get(I.id)));r.push({id:`${n}:ide:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:g.parentId,sessionKind:g.kind,transport:g.transport,sessionCapabilities:g.capabilities,type:g.providerType,status:g.cdpConnected?"online":"detected",daemonId:n,instanceId:x.id,workspace:g.workspace,terminals:0,childSessions:C,agents:C.map(I=>({id:I.id,name:I.providerName||I.providerType,type:I.providerType,status:I.status})),activeChat:g.activeChat,chats:[],cdpConnected:g.cdpConnected,...g.lastMessagePreview!==void 0&&{lastMessagePreview:g.lastMessagePreview},...g.lastMessageRole!==void 0&&{lastMessageRole:g.lastMessageRole},...g.lastMessageAt!==void 0&&{lastMessageAt:g.lastMessageAt},...g.lastMessageHash!==void 0&&{lastMessageHash:g.lastMessageHash},lastUpdated:g.lastUpdated,unread:g.unread,lastSeenAt:g.lastSeenAt,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,seenCompletionMarker:g.seenCompletionMarker,surfaceHidden:g.surfaceHidden,...g.controlValues!==void 0&&{controlValues:g.controlValues},...g.providerControls!==void 0&&{providerControls:g.providerControls},...g.summaryMetadata!==void 0&&{summaryMetadata:g.summaryMetadata},timestamp:l})}for(const x of N){const y=h.get(x.id),g=Fs(x,y);r.push({id:`${n}:cli:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:g.parentId,sessionKind:g.kind,transport:g.transport,sessionCapabilities:g.capabilities,type:g.providerType,agentType:g.providerType,status:g.status||"running",daemonId:n,instanceId:x.id,cliName:g.providerName||g.providerType,mode:g.mode||(y==null?void 0:y.mode)||"terminal",workspace:g.workspace||"",activeChat:g.activeChat,...g.resume!==void 0&&{resume:g.resume},...g.runtimeKey!==void 0&&{runtimeKey:g.runtimeKey},...g.runtimeDisplayName!==void 0&&{runtimeDisplayName:g.runtimeDisplayName},...g.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:g.runtimeWorkspaceLabel},...g.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:g.runtimeWriteOwner},...g.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:g.runtimeAttachedClients},...g.lastMessagePreview!==void 0&&{lastMessagePreview:g.lastMessagePreview},...g.lastMessageRole!==void 0&&{lastMessageRole:g.lastMessageRole},...g.lastMessageAt!==void 0&&{lastMessageAt:g.lastMessageAt},...g.lastMessageHash!==void 0&&{lastMessageHash:g.lastMessageHash},lastUpdated:g.lastUpdated,unread:g.unread,lastSeenAt:g.lastSeenAt,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,seenCompletionMarker:g.seenCompletionMarker,surfaceHidden:g.surfaceHidden,...g.controlValues!==void 0&&{controlValues:g.controlValues},...g.providerControls!==void 0&&{providerControls:g.providerControls},...g.summaryMetadata!==void 0&&{summaryMetadata:g.summaryMetadata},timestamp:l,_isCli:!0})}for(const x of p){const y=h.get(x.id),g=Fs(x,y);r.push({id:`${n}:acp:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:g.parentId,sessionKind:g.kind,transport:g.transport,sessionCapabilities:g.capabilities,type:g.providerType,agentType:g.providerType,status:g.status||"running",daemonId:n,instanceId:x.id,cliName:g.providerName||g.providerType,mode:"chat",workspace:g.workspace||"",activeChat:g.activeChat,...g.runtimeKey!==void 0&&{runtimeKey:g.runtimeKey},...g.runtimeDisplayName!==void 0&&{runtimeDisplayName:g.runtimeDisplayName},...g.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:g.runtimeWorkspaceLabel},...g.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:g.runtimeWriteOwner},...g.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:g.runtimeAttachedClients},...g.lastMessagePreview!==void 0&&{lastMessagePreview:g.lastMessagePreview},...g.lastMessageRole!==void 0&&{lastMessageRole:g.lastMessageRole},...g.lastMessageAt!==void 0&&{lastMessageAt:g.lastMessageAt},...g.lastMessageHash!==void 0&&{lastMessageHash:g.lastMessageHash},lastUpdated:g.lastUpdated,unread:g.unread,lastSeenAt:g.lastSeenAt,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,seenCompletionMarker:g.seenCompletionMarker,surfaceHidden:g.surfaceHidden,...g.controlValues!==void 0&&{controlValues:g.controlValues},...g.providerControls!==void 0&&{providerControls:g.providerControls},...g.summaryMetadata!==void 0&&{summaryMetadata:g.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const Rm=15e3,_m=15e3,Pm=6e4,Dm=1200,To=12,Em=8e3,$m=4e3,yn=new Map,vn=new Map,xr=new Set,Gs=new Map;function Bm(e){if(!e||typeof e!="object")return null;const t=e,r=t.status;if(r&&typeof r=="object")return r;const n=t.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return t}function Io(e,t){const r=Gs.get(e);!r||r.size===0||(Gs.delete(e),r.forEach(n=>n(t)))}function Km(e,t){return new Promise(r=>{const n=Gs.get(e)||new Set;Gs.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&Gs.delete(e),r(c)},i=setTimeout(()=>a(!1),t);n.add(a)})}function ir(){const{sendCommand:e,sendData:t}=wt(),{injectEntries:r,getIdes:n}=Qs();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??Pm,l=vn.get(a)||0;if(!(i!=null&&i.force)&&xr.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=yn.get(a);if(u)return u;const m=(async()=>{if(t&&!xr.has(a)){const p=Vt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},x=>{const y=n(),g=y.find(I=>I.id===a),C=Fr(x.status,{daemonId:a,existingDaemon:g,existingEntries:y,timestamp:x.timestamp});C.length>0&&r(C),vn.set(a,Date.now()),Io(a,!0)});if(p.initialSendAccepted?xr.add(a):xr.delete(a),!(i!=null&&i.force)&&p.initialSendAccepted&&await Km(a,Dm))return}const d=await e(a,"get_status_metadata"),h=Bm(d);if(!h)return;const f=n(),j=f.find(p=>p.id===a),N=Fr(h,{daemonId:a,existingDaemon:j,existingEntries:f,timestamp:h.timestamp||Date.now()});N.length>0&&r(N,{authoritativeDaemonIds:[a]}),vn.set(a,Date.now()),Io(a,!0)})().finally(()=>{yn.delete(a)});return yn.set(a,m),m},[n,r,e,t])}function sn(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}function ws(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:Qe(e)||Ve(e)?{agentType:$t(e)}:e.streamSource==="agent-stream"?{agentType:$t(e)}:t}function sr(e){return e?Rs(e):""}function $s(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function _a(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Om(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 Wm=60,Hm=1e3;function mc(e={}){return e.isCliLike?Hm:Wm}function Fm(e={}){return mc(e)}const cr=60,Um=1e3,Pa=12e4,zm=new Set(["generating","waiting_approval","starting","streaming","working"]),Ao=new Map;function Da(e,t){return`${e}::${t}`}function oa(e=cr){return{liveMessages:[],cursor:fc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function ia(e){return Ii(e)}function fc(e,t=cr){return{knownMessageCount:e.length,lastMessageSignature:ia(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 Lo(e){for(let t=e.length-1;t>=0;t-=1){const r=sn(e[t]);if(r>0)return r}return 0}function Vm(e,t){if(t.length===0)return!1;if(e.length===0)return!0;const r=Lo(e),n=Lo(t);return!(r>0&&n<=0||r>0&&n>0&&n<r||r>0&&n===r&&t.length<e.length)}function Gm(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 qm{constructor(t){ze(this,"manager");ze(this,"sendData");ze(this,"daemonId");ze(this,"sessionId");ze(this,"historySessionId");ze(this,"subscriptionKey");ze(this,"snapshot");ze(this,"transportSubscription",null);ze(this,"listeners",new Set);ze(this,"retainCount",0);ze(this,"loadHistoryPromise",null);ze(this,"pendingDisconnectTimer",null);this.manager=t.manager||Vt,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=oa(Math.max(0,t.tailLimit??cr))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);if(r!==this.snapshot.cursor.tailLimit){const n=r>this.snapshot.cursor.tailLimit,a=n?0:Math.min(this.snapshot.cursor.knownMessageCount,this.snapshot.liveMessages.length),i=n?"":this.snapshot.cursor.lastMessageSignature;this.snapshot={...this.snapshot,cursor:{knownMessageCount:a,lastMessageSignature:i,tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect())}}}getSnapshot(){return this.snapshot}hydrateLiveMessages(t){const r=Array.isArray(t)?t:[];if(!Vm(this.snapshot.liveMessages,r))return;const n=r,a=fc(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:Um}))}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=ia(this.snapshot.liveMessages[this.snapshot.liveMessages.length-1]);if(t.syncMode!=="full"&&r&&n===r){const u={knownMessageCount:Math.max(this.snapshot.cursor.knownMessageCount,Number(t.totalMessages||0)),lastMessageSignature:r,tailLimit:this.snapshot.cursor.tailLimit};this.snapshot.cursor.knownMessageCount===u.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===u.lastMessageSignature||(this.snapshot={...this.snapshot,cursor:u},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:u.knownMessageCount,lastMessageSignature:u.lastMessageSignature}));return}const a=Gm(this.snapshot.liveMessages,t),i={knownMessageCount:a.length,lastMessageSignature:typeof t.lastMessageSignature=="string"?t.lastMessageSignature:ia(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 pc(e){const t=Da(e.daemonId,e.sessionId),r=Ao.get(t);if(r)return r.updateOptions(e),r;const n=new qm(e);return Ao.set(t,n),n}function Ym(e,t){return{...e,loadHistoryPage:t}}function Xm(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Jm(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(zm.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??Pa)),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 Qm(e=Pa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Zm(e,t={}){const r=new Set,n=[];for(const a of e){if(!Jm(a,t))continue;const i=Rs(a),c=a.sessionId||"";if(!i||!c)continue;const l=Da(i,c);if(r.has(l))continue;r.add(l);const u=or(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Xm),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function ef(e,t){const{sendData:r,sendCommand:n}=wt(),a=(t==null?void 0:t.enabled)!==!1,i=Rs(e),c=e.sessionId||"",l=or(e)||c,u=`daemon:${i}:session:${c}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??cr),d=o.useMemo(()=>!a||!i||!c?null:pc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:m}),[i,a,l,r,c,u,m]),[h,f]=o.useState(()=>(d==null?void 0:d.getSnapshot())||oa(m));o.useEffect(()=>{if(!d){f(oa(m));return}d.retain(),f(d.getSnapshot());const N=d.subscribe(p=>{f(p)});return()=>{N(),d.release()}},[d,m]),o.useEffect(()=>{d&&(d.hydrateLiveMessages(e.messages),f(d.getSnapshot()))},[e.messages,d]);const j=o.useCallback(async()=>{!d||!i||!c||await d.loadHistoryPage(async()=>{const N=e.agentType,p=await n(i,"chat_history",{agentType:N,offset:d.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),x=p&&typeof p=="object"&&"result"in p?p.result||{}:p||{};return{messages:Array.isArray(x.messages)?x.messages:[],hasMore:x.hasMore===!0}})},[e.agentType,d,i,l,n,c]);return o.useMemo(()=>Ym(h,j),[j,h])}function tf(e,t){const{sendData:r}=wt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??cr),i=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Pa)),c=Qm(i),[l,u]=o.useState(0),[m,d]=o.useState(()=>new Map);o.useEffect(()=>{if(!n||e.length===0)return;const f=setInterval(()=>{u(j=>j+1)},c);return()=>{clearInterval(f)}},[e.length,n,c]);const h=o.useMemo(()=>Zm(e,{recentActivityMs:i}),[e,i,l]);return o.useEffect(()=>{if(!n||!r||h.descriptors.length===0){d(x=>x.size===0?x:new Map);return}const f=h.descriptors.map(x=>({key:Da(x.daemonId,x.sessionId),controller:pc({...x,sendData:r,tailLimit:a})})),j=new Set(f.map(({key:x})=>x)),N=(x,y)=>{d(g=>{const C=new Map(g);for(const I of C.keys())j.has(I)||C.delete(I);return C.set(x,y),C})},p=f.map(({key:x,controller:y})=>(y.retain(),N(x,y.getSnapshot()),y.subscribe(g=>N(x,g))));return()=>{p.forEach(x=>x()),f.forEach(({controller:x})=>x.release())}},[h.signature,n,r,a]),m}function Ro(e,t){const r=e[e.length-1];if(!r)return`empty:${t||""}`;let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return[t||"",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function Ur(e){for(let t=e.length-1;t>=0;t-=1){const r=sn(e[t]);if(r>0)return r}return 0}function sf(e){const t=Rs(e),r=e.sessionId||"";return t&&r?`${t}::${r}`:""}function rf(e,t){if(t.length===0)return!1;const r=Array.isArray(e.messages)?e.messages:[];if(r.length===0)return!0;const n=Ur(r),a=Ur(t);if(n<=0||a<=n)return!1;const i=Ro(r,e.status),c=Ro(t,e.status);return i!==c}function nf(e,t){const r=t[t.length-1],n=sn(r),a=ks(r==null?void 0:r.content);return{...e,messages:t,...a?{lastMessagePreview:a}:{},...n>0?{lastMessageAt:n}:{}}}function af(e,t){const r=Array.isArray(e.messages)?e.messages:[],n=(t==null?void 0:t.liveMessages)||[];if(n.length===0)return r;if(r.length===0)return n;const a=Ur(r),i=Ur(n);return a>0&&(i<=0||a>=i)?r:n}function of(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 _o(e,t){if(t.size===0||e.length===0)return e;let r=!1;const n=e.map(a=>{var l;const i=sf(a);if(!i)return a;const c=((l=t.get(i))==null?void 0:l.liveMessages)||[];return rf(a,c)?(r=!0,nf(a,c)):a});return r?n:e}function cf(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function lf(e){return cf(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const df=60;function ca({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:m=!1,scrollToBottomRequestNonce:d,isInputActive:h=!0,isVisible:f=!0}){var le,be,ge,G,ne;const j=o.useRef(new Map),N=ir();ar("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const p=jt.useMemo(()=>As(e),[e.status,e.connectionState]),x=o.useMemo(()=>km(e,t),[e,t]),y=o.useMemo(()=>{var q;return Ta((q=x.targetEntry)==null?void 0:q.providerControls,{hostIdeType:e.hostIdeType,providerType:x.providerType})},[e.hostIdeType,x.providerType,(le=x.targetEntry)==null?void 0:le.providerControls]),g=mc({isCliLike:x.isCli||x.isAcp}),C=Fm({isCliLike:x.isCli||x.isAcp}),I=ef(e,{enabled:f&&!!e.sessionId,tailLimit:C}),[v,T]=o.useState(g),S=e.tabKey,k=I.historyMessages,b=I.hasMoreHistory,B=I.historyError,L=af(e,I);o.useEffect(()=>{T(g)},[g,S]);const _=Math.max(0,L.length-v),H=Ia(e),F=Rs(e),O=lf(e),M=_a(e),A=a||M,U=!!M,[$,E]=o.useState(!1);o.useEffect(()=>{const q=x.targetEntry;F&&(!q||q.providerControls===void 0||q.controlValues===void 0)&&N(F,{minFreshMs:3e4}).catch(()=>{})},[F,x.isAcp,(be=x.targetEntry)==null?void 0:be.providerControls,(ge=x.targetEntry)==null?void 0:ge.controlValues,N]);const z=o.useCallback(async()=>{if(!$){if(L.length>v){T(q=>Math.min(L.length,q+df));return}E(!0);try{await I.loadHistoryPage()}finally{E(!1)}}},[I,$,L.length,v]),{allMessages:Y,receivedAtMap:ve}=o.useMemo(()=>{const q=of({historyMessages:k,liveMessages:L,visibleLiveCount:v}),ue={};return q.forEach((ce,je)=>{const ae=`${e.tabKey}:${Kr(ce,je)}`;let fe=sn(ce)||j.current.get(ae)||0;fe||(fe=Date.now(),j.current.set(ae,fe)),ue[Kr(ce,je)]=fe}),{allMessages:q,receivedAtMap:ue}},[e.tabKey,_,k,L,v]),re=o.useMemo(()=>l.filter(q=>q.routeId===e.tabKey).sort((q,ue)=>q.timestamp-ue.timestamp),[l,e.tabKey]),ye=o.useMemo(()=>{if(L.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((p.isGenerating||e.status==="streaming")&&E(!1),e.status==="not_monitored"&&O)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(er,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ss,{size:14})," Open ",H," 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"&&O)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(Ss,{size:14})," Open ",H," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!$)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,O,i,c,$,L.length,H,p.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&s.jsx(uc,{conversation:e,className:"chat-pane-meta-row"}),s.jsx(hu,{messages:Y,actionLogs:re,agentName:Ns(e)||H||"Agent",userName:u,isCliMode:x.isCli||x.isAcp,isWorking:p.isGenerating,contextKey:e.tabKey,receivedAtMap:ve,lastMessageHash:e.lastMessageHash,onLoadMore:z,isLoadingMore:$,hasMoreHistory:b,hiddenLiveCount:_,loadError:B??void 0,emptyState:ye,scrollToBottomRequestNonce:d,isVisible:f}),s.jsx(hm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:x.providerType,displayLabel:x.displayLabel,controls:(G=x.targetEntry)==null?void 0:G.providerControls,controlValues:(ne=x.targetEntry)==null?void 0:ne.controlValues,isActive:h,isCliTerminal:x.isCliTerminal}),!x.isCliTerminal&&s.jsx(ec,{contextKey:e.tabKey,panelLabel:H,isSending:n,isBusy:U,statusMessage:A,onSend:r,isActive:h,showControlsToggle:y.length>0})]})}let hc=os;function xc(){return hc()}class uf{constructor(){ze(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{var n;(n=this.listeners.get(t))==null||n.delete(r)}}emit(t,...r){var n;(n=this.listeners.get(t))==null||n.forEach(a=>a(...r))}}let bc=new uf;class mf{sendPtyInput(t,r,n){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,r){return!1}get(t){}onScreenshot(t,r){return()=>{}}onRuntimeEvent(t,r,n){return()=>{}}requestRuntimeSnapshot(t,r,n){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let lt=new mf;function ff(e){e.dashboardWS&&(bc=e.dashboardWS),e.connectionManager&&(lt=e.connectionManager),e.useDaemonsHook&&(hc=e.useDaemonsHook)}const pf=.5,hf=1.25;function at(e){return Ia(e)}function ls(e){return ac(e).join(" · ")}function gc(e){const t=nc(e);return t||(e.title?e.title:ls(e)||"No messages yet")}function yc(e,t){const{isReconnecting:r,isConnecting:n}=As(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function xf(e,t){const r=["Chat",...ac(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function Zt(e){return yc(e)||ls(e)}function bf(e){return`${at(e)} · ${gc(e)}`}function gf(e){const t=Hr(e),r=t?rt(t):Ns(e);return`${at(e)} — ${r||"Agent"}`}function yf(e){return Ns(e)||"CLI"}function vc(e){return rc(e)}function wc(e){return e?`Remote · ${at(e)||e.workspaceName||"Session"}`:"Remote"}function vf({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var W;os();const{sendPtyInput:u}=wt(),[m,d]=o.useState(!1),h=o.useRef(!1);h.current=m;const[f,j]=o.useState("Runtime terminal unavailable"),[N,p]=o.useState(!1),[x,y]=o.useState(null),[g,C]=o.useState(!1),[I,v]=o.useState(!1),[T,S]=o.useState(1),[k,b]=o.useState({width:0,height:0}),[B,L]=o.useState({width:0,height:0}),[_,H]=o.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[F,O]=o.useState(null),M=o.useRef(null),A=o.useRef(null),U=o.useRef(!1),$=o.useRef(!1),E=o.useRef(c),z=o.useRef(0),Y=o.useRef(!1),ve=o.useRef(""),re=o.useRef(null),ye=o.useRef(!1),le=o.useRef(!1),be=o.useRef(null),ge=o.useRef(null),G=o.useRef(null),ne=32*1024,q=()=>{var w,R,P,V;return((R=(w=M.current)==null?void 0:w.ownerDocument)==null?void 0:R.defaultView)||((V=(P=A.current)==null?void 0:P.ownerDocument)==null?void 0:V.defaultView)||window},ue=w=>{const R=q();return{ownerWindow:R,frameId:R.requestAnimationFrame(w)}},ce=()=>{const w=be.current;if(w){try{w.ownerWindow.cancelAnimationFrame(w.frameId)}catch{}be.current=null}},je=()=>{const w=ge.current;if(w){try{w.ownerWindow.clearTimeout(w.timeoutId)}catch{}ge.current=null}},ae=()=>{const w=G.current;if(w){try{w.ownerWindow.clearTimeout(w.timeoutId)}catch{}G.current=null}},fe=()=>{c&&be.current===null&&(be.current=ue(()=>{Ze()}))},oe=e.tabKey,te=e.sessionId||"",ee=e.daemonId||((W=e.routeId)==null?void 0:W.split(":")[0])||e.routeId||"",X=_a(e),J=m?i||X:f,de=pf,D=hf,ie=.05,Q=()=>{const w=B.width,R=B.height;if(!Number.isFinite(k.width)||k.width<=0||!Number.isFinite(k.height)||k.height<=0||!Number.isFinite(w)||w<=0||!Number.isFinite(R)||R<=0)return 1;const P=k.width/w,V=k.height/R;return Number(Math.min(D,Math.max(de,Math.min(P,V))).toFixed(2))},we=Q(),Ne=U.current&&T>we,Ae=Number.isFinite(B.width)&&B.width>0?Math.max(k.width,Math.round(B.width*T)):k.width,Te=Number.isFinite(B.height)&&B.height>0?Math.max(k.height,Math.round(B.height*T)):k.height,Ue=()=>{ue(()=>{const w=A.current;w&&(w.scrollLeft=0,w.scrollTop=w.scrollHeight-w.clientHeight)})},We=()=>{var w,R;z.current=0,Y.current=!1,ve.current="",re.current=null,ye.current=!1,le.current=!1,U.current||($.current=!1,S(1)),be.current!==null&&ce(),d(!1),j("Runtime terminal unavailable"),ae(),je(),y(null),O(null),p(!1),C(!1),v(!1),(R=(w=r.current)==null?void 0:w.reset)==null||R.call(w)},Ke=()=>{var w,R;z.current=0,Y.current=!1,ve.current="",re.current=null,ye.current=!1,le.current=!1,be.current!==null&&ce(),d(!0),j(""),ae(),je(),y(null),O(null),p(!1),C(!1),v(!1),(R=(w=r.current)==null?void 0:w.reset)==null||R.call(w)},Ge=()=>{le.current&&(le.current=!1,ue(()=>{var w,R;(R=(w=r.current)==null?void 0:w.scrollToTop)==null||R.call(w)}))},Ze=()=>{if(be.current=null,!c)return;const w=ve.current;if(!w)return;const R=w.slice(0,ne);ve.current=w.slice(R.length);const P=r.current;if(!P){ve.current=R+ve.current,fe();return}P.write(R,()=>{if(ve.current.length>0){fe();return}Ge()})},Je=w=>{w&&(ve.current+=w,fe())},Ye=(w,R=0,P,V,Z={})=>{var he,Se,Re,ke;const me=!!Z.force;!me&&R>0&&z.current>=R||!me&&R===0&&Y.current||(z.current=R,R>0&&C(!0),d(!0),j(""),typeof P=="number"&&typeof V=="number"&&P>0&&V>0&&((Se=(he=r.current)==null?void 0:he.resize)==null||Se.call(he,P,V)),ve.current="",(ke=(Re=r.current)==null?void 0:Re.reset)==null||ke.call(Re),w?Je(w):Ge())};o.useEffect(()=>{We()},[te]),o.useEffect(()=>{var R;if(!te)return;const w=((R=lt.onRuntimeEvent)==null?void 0:R.call(lt,te,P=>{if(!(!P||P.sessionId!==te)){if(P.type==="runtime_snapshot"){if(!c){re.current={text:P.text||"",seq:P.seq||0,cols:P.cols,rows:P.rows,force:!!P.force};return}Ye(P.text||"",P.seq||0,P.cols,P.rows,{force:!!P.force});return}if(P.type==="session_output"){Y.current=!0,typeof P.seq=="number"&&(z.current=Math.max(z.current,P.seq),P.seq>0&&C(!0)),h.current||d(!0),h.current||j(""),typeof P.data=="string"&&Je(P.data);return}if(P.type==="session_cleared"){if(!c){ye.current=!0,ve.current="",re.current=null;return}Ke();return}if(P.type==="session_io_error"){const V=typeof P.error=="string"&&P.error?P.error:typeof P.reason=="string"&&P.reason?P.reason:"unknown error";d(!1),j(`Runtime input failed: ${V}`);return}}},ee))||(()=>{});return()=>{w()}},[ee,te,r,c]);const mt=async(w={})=>{var R;if(!ee||!te)return{success:!1,error:"daemonId and sessionId are required"};w.preserveStatus||j(w.loadingMessage||"Loading runtime terminal...");try{const P=await((R=lt.requestRuntimeSnapshot)==null?void 0:R.call(lt,ee,te,{sinceSeq:w.sinceSeq,force:w.force}));return P&&P.success===!1?(w.preserveStatus||(d(!1),j(`Runtime terminal unavailable: ${P.error}`)),P):P||{success:!0}}catch(P){const V=(P==null?void 0:P.message)||String(P);return w.preserveStatus||(d(!1),j(`Runtime terminal unavailable: ${V}`)),{success:!1,error:V}}},pt=async w=>{var me,he;const R=((me=M.current)==null?void 0:me.ownerDocument)||document,P=R.defaultView||window,V=(he=P.navigator)==null?void 0:he.clipboard;if(V!=null&&V.writeText&&P.isSecureContext)try{return await V.writeText(w),!0}catch{}let Z=null;try{return Z=R.createElement("textarea"),Z.value=w,Z.setAttribute("readonly","true"),Z.style.position="fixed",Z.style.left="-9999px",Z.style.top="0",R.body.appendChild(Z),Z.focus(),Z.select(),R.execCommand("copy")}catch{return!1}finally{Z==null||Z.remove()}},dt=w=>{je(),O(w);const R=q();ge.current={ownerWindow:R,timeoutId:R.setTimeout(()=>{ge.current=null,O(P=>P===w?null:P)},2200)}},Ce=w=>{ae(),y(w);const R=q();G.current={ownerWindow:R,timeoutId:R.setTimeout(()=>{G.current=null,y(P=>P===w?null:P)},2200)}},He=async()=>{var Z,me,he,Se;const w=((me=(Z=r.current)==null?void 0:Z.getSelection)==null?void 0:me.call(Z))||"",R=((Se=(he=r.current)==null?void 0:he.getVisibleText)==null?void 0:Se.call(he))||"",P=w.trimEnd()||R.trimEnd();if(!P){dt("Nothing to copy");return}if(!await pt(P)){dt("Copy failed");return}dt(w.trimEnd()?"Copied selection":"Copied visible terminal")},Xe=async()=>{if(N)return;p(!0),y("Loading older terminal output..."),le.current=!0;const w=await mt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),(w==null?void 0:w.success)===!1){le.current=!1,y(`Older terminal output unavailable: ${w.error}`);return}v(!0),Ce("Older terminal output loaded"),ue(()=>{var R;(R=r.current)==null||R.bumpResize()})};o.useEffect(()=>{var R,P;if(!te)return;ee&&((R=lt.getState)==null?void 0:R.call(lt,ee))==="connected"&&mt();const w=(P=lt.onStateChange)==null?void 0:P.call(lt,(V,Z)=>{V!==ee||Z!=="connected"||mt()});return()=>{w==null||w()}},[ee,te,r]),o.useEffect(()=>{t&&We()},[t,oe,r]),o.useEffect(()=>{var V,Z;const w=M.current,R=(Z=(V=w==null?void 0:w.ownerDocument)==null?void 0:V.defaultView)==null?void 0:Z.ResizeObserver;if(!w||!R)return;const P=new R(me=>{const he=me[0];if(!he)return;const{width:Se,height:Re}=he.contentRect;b(ke=>{const Ee=Math.round(Se),$e=Math.round(Re);return ke.width===Ee&&ke.height===$e?ke:{width:Ee,height:$e}})});return P.observe(w),()=>P.disconnect()},[]),o.useEffect(()=>{if(U.current)return;const w=Q();!Number.isFinite(w)||w<=0||S(R=>$.current?w<R-ie?w:R:($.current=!0,w))},[B.height,B.width,k.height,k.width]),o.useEffect(()=>{Ne&&Ue()},[Ne,Te,Ae]),o.useEffect(()=>{var P;const w=E.current;if(E.current=c,!c)return;w||v(!1),ye.current&&(ye.current=!1,Ke());const R=re.current;R&&(re.current=null,Ye(R.text,R.seq,R.cols,R.rows,{force:!!R.force})),ee&&te&&((P=lt.getState)==null?void 0:P.call(lt,ee))==="connected"&&mt(),ve.current&&be.current===null&&fe(),ue(()=>{var V;(V=r.current)==null||V.bumpResize()})},[ee,c,te]),o.useEffect(()=>()=>{be.current!==null&&ce(),je(),ae()},[]),o.useEffect(()=>{const w=V=>{var me;const Z=V.detail;Z!=null&&Z.sessionId&&Z.sessionId!==te||m&&((me=r.current)==null||me.bumpResize())},R=q(),P=R===window?[window]:[window,R];for(const V of P)V.addEventListener("adhdev:fit-cli-terminal",w);return()=>{for(const V of P)V.removeEventListener("adhdev:fit-cli-terminal",w)}},[m,te,r]);const ft=m&&g&&!I&&(_.atTop||!_.canScroll)||N||!!x;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:M,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[ft&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Xe()},disabled:!te||N,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:N?"Loading older...":"Load older terminal output"}),x&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:x})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[F&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:F}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{He()},disabled:!m,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{U.current=!0,S(w=>{const R=Math.max(we,Number((w-.1).toFixed(2)));return R>we&&Ue(),R})},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:()=>{U.current=!0,S(w=>{const R=Math.min(D,Number((w+.1).toFixed(2)));return R>we&&Ue(),R})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:A,className:Ne?"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:Ae>0?`${Ae}px`:"100%",height:Te>0?`${Te}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:T},children:s.jsx(Hi,{ref:r,readOnly:!m||!c,sizingMode:"measured",onViewportMetrics:L,onScrollMetrics:H,onInput:w=>{!m||(u==null||u(ee,te,w))}})})})}),!m&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:f})]}),s.jsx(ec,{contextKey:e.tabKey,panelLabel:at(e),isSending:a,isBusy:!!X,statusMessage:J,onSend:async w=>X?!1:n(w),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const wf=5e3;function jf(e){return e==="disconnected"||e==="reconnecting"}function kf({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=wf}){const i=jf(e),[c,l]=o.useState(()=>!i||a<=0),u=o.useRef(!1);o.useEffect(()=>{if(!i){l(!1);return}if(u.current=!1,a<=0){u.current=!0,l(!0);return}l(!1);const y=setTimeout(()=>{u.current=!0,l(!0)},a);return()=>clearTimeout(y)},[a,i]);const m=i?c:e==="offline"||e==="auth_failed",d=o.useMemo(()=>!t||e!=="connected"?!1:a<=0||u.current,[a,t,e]),h=e==="auth_failed"?"red":e==="offline"?"orange":"accent",f={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},j={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)"},N={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},p="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",x={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[m&&s.jsx("div",{className:p,style:x,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-4 py-3 text-[13px] font-semibold flex items-center gap-2.5 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:f[h],border:j[h],color:N[h]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),n&&e!=="auth_failed"&&s.jsx("button",{type:"button",className:"ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:n,disabled:e==="offline",children:"Reconnect now"})]})}),d&&s.jsx("div",{className:p,style:x,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function Sf({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=o.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=o.useState(!1);if(o.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!t||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",u=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!0)};return s.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[l," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:u,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Ea({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(ja,{size:n}):s.jsx(Wt,{size:n})})}const Dt="New session",jc="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 Nf({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 Po({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=Qr(e.updatedAt),l=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),i()},children:"Delete"})]})]})}function Cf({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:u,onHideConversation:m,hiddenConversations:d=[],onShowConversation:h,onShowAllHidden:f,onResetPanelsToMain:j,inboxOpen:N,onInboxOpenChange:p,hiddenOpen:x,onHiddenOpenChange:y,onOpenNewSession:g,onOpenDashboardGuide:C,guideNudgeVisible:I=!1,actionShortcuts:v,notifications:T,notificationUnreadCount:S,onOpenNotification:k,onMarkNotificationRead:b,onMarkNotificationUnread:B,onDeleteNotification:L}){const{ides:_,p2pStates:H={}}=os(),F=!!e&&Qe(e)&&!Ve(e),O=!!e&&Ve(e),M=l||(e?tc(e)?"terminal":"chat":null),[A,U]=o.useState(!1),$=o.useRef(null),E=o.useRef(null),z=_.filter(q=>q.type==="adhdev-daemon"),Y=Nf({wsStatus:t,isConnected:r,daemonCount:z.length,p2pStates:H}),ve=Y.subtitle,re=Y.tone==="connected"?"#22c55e":Y.tone==="limited"?"#eab308":"#ef4444",ye=Y.tone==="connected"?"0 0 4px #22c55e80":Y.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",le=o.useMemo(()=>T.filter(q=>!q.readAt),[T]),be=o.useMemo(()=>T.filter(q=>!!q.readAt),[T]),ge=o.useMemo(()=>le.slice(0,9),[le]),G=S;o.useEffect(()=>{if(!N)return;const q=ue=>{var ce;(ce=$.current)!=null&&ce.contains(ue.target)||p(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[N,p]),o.useEffect(()=>{if(!x)return;const q=ue=>{var ce;(ce=E.current)!=null&&ce.contains(ue.target)||y(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[x,y]),o.useEffect(()=>{if(!x&&!N)return;const q=ue=>{if(!ue.altKey)return;const ce=ue.code.match(/^Digit([1-9])$/);if(!ce)return;const je=Number(ce[1])-1,ae=x?d[je]:void 0,fe=N?ge[je]:void 0;if(!(!ae&&!fe)){if(ue.preventDefault(),ue.stopPropagation(),ae){h==null||h(ae),y(!1);return}fe&&(k(fe),p(!1))}};return window.addEventListener("keydown",q,!0),()=>window.removeEventListener("keydown",q,!0)},[d,x,N,ge,y,p,k,h]);const ne=q=>{if(!q)return;const ue=n.find(ce=>ce.tabKey===q);ue&&(m==null||m(ue))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Wt,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?at(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:re,boxShadow:ye}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[s.jsx("span",{title:Y.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:re,boxShadow:ye}}),ve&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ve]}),g&&s.jsx("button",{type:"button",onClick:g,className:"btn btn-secondary btn-sm ml-2",title:Dt,"aria-label":Dt,children:s.jsx($i,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[C&&s.jsxs("button",{type:"button",onClick:C,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),I&&s.jsx("span",{children:"Guide"})]}),e&&(F||O||!Ve(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:ls(e)||at(e),children:at(e)}),(F||O)&&c&&s.jsxs(s.Fragment,{children:[F&&u&&M&&s.jsx(Ea,{mode:M,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:O?"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})})]}),!Ve(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(wa,{size:14})}),!F&&!Ve(e)&&s.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(St,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:$,children:[s.jsxs("div",{className:`dashboard-header-hidden${A?" is-drop-target":""}`,ref:E,onDragEnter:q=>{q.dataTransfer.types.includes("text/tab-key")&&(q.preventDefault(),U(!0))},onDragOver:q=>{q.dataTransfer.types.includes("text/tab-key")&&(q.preventDefault(),q.dataTransfer.dropEffect="move",U(!0))},onDragLeave:q=>{q.currentTarget.contains(q.relatedTarget)||U(!1)},onDrop:q=>{const ue=q.dataTransfer.getData("text/tab-key");q.preventDefault(),U(!1),ne(ue)},children:[s.jsxs("button",{type:"button",onClick:()=>y(!x),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Di,{size:16}),d.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),x&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(Po,{value:v==null?void 0:v.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[j&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:j,children:"Reset panels"}),d.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),y(!1)},children:"Restore all"})]})]}),e&&m&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(Po,{value:v==null?void 0:v.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:at(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(q=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(q),y(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:at(q)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(q)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(q)+1]}):null,ls(q)]})]},q.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!N),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Jr,{size:16}),G>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:G})]}),N&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[le.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),le.map(q=>s.jsx(Do,{notification:q,shortcutIndex:ge.indexOf(q)>=0?ge.indexOf(q)+1:void 0,onOpen:()=>k(q),onMarkRead:()=>b(q.id),onMarkUnread:()=>B(q.id),onDelete:()=>L(q.id)},q.id))]}),be.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),be.map(q=>s.jsx(Do,{notification:q,onOpen:()=>k(q),onMarkRead:()=>b(q.id),onMarkUnread:()=>B(q.id),onDelete:()=>L(q.id)},q.id))]}),T.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function ht(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Mf(e,t){return String(e||"")!==String(t||"")}function Tf(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),i=!!t.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(u=>String(u||"").toLowerCase()).join(`
|
|
30
|
-
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!
|
|
31
|
-
`).includes(a)))}function If(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 kc(e,t={}){return If(Tf(e,t),t.sortMode||"recent")}function zr(e){return e?"Resume saved history":"Start fresh"}function $a(e){return e?"Resuming saved history…":"Starting fresh…"}function Af(){return"Start fresh"}function Sc(e,t=!1){return e==="cli"?zr(t):e==="ide"?"Start IDE":"Start ACP session"}function Nc(e,t=!1){return e==="cli"?$a(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Lf(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Rf(){return"Open saved history"}function _f(){return"Saved History"}function Ba(){return"Use saved history when you want continuity in the same provider conversation."}function Pf(){return"No saved history found yet."}function Df(){return"Refresh saved history"}function Ef(){return"Refreshing saved history…"}function es(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function ts(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Cs(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ms(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Ka(e){return`Resume saved history with ${e}?`}function Oa(){return"Review or change the target workspace before resuming saved history."}function $f(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 Wa({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:m,onNewChat:d,onSwitchSession:h,onRefreshHistory:f,onResumeSavedSession:j}){var k;const N=t.find(b=>b.id===e.routeId),p=(N==null?void 0:N.chats)||[],x=(k=N==null?void 0:N.activeChat)==null?void 0:k.id,y=Qe(e)&&!Ve(e),[g,C]=o.useState(()=>ht()),I=l||g,v=b=>{if(u){u(b);return}C(b)},T=o.useMemo(()=>kc(a,{textQuery:I.textQuery,workspaceQuery:I.workspaceQuery,modelQuery:I.modelQuery,resumableOnly:I.resumableOnly,sortMode:I.sortMode}),[I.modelQuery,I.resumableOnly,I.sortMode,I.textQuery,I.workspaceQuery,a]),S=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:m,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:y?_f():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:gf(e)}),y&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ba()})]}),s.jsx("button",{onClick:m,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!y&&s.jsx("button",{onClick:d,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),y?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:I.textQuery,onChange:b=>v({...I,textQuery:b.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:I.workspaceQuery,onChange:b=>v({...I,workspaceQuery:b.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:I.modelQuery,onChange:b=>v({...I,modelQuery:b.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:I.sortMode,onChange:b=>v({...I,sortMode:b.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:I.resumableOnly,onChange:b=>v({...I,resumableOnly:b.target.checked})}),"Resume-ready only"]})]}),T.map(b=>{const B=e.providerSessionId===b.providerSessionId,L=B||!b.canResume||!!c;return s.jsxs("button",{type:"button",onClick:()=>{L||!j||j(b)},disabled:L,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${B?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${L?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${B?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:b.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:b.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:$f(b.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:b.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[b.workspace||"Workspace unknown",cs(b.summaryMetadata)?` · ${cs(b.summaryMetadata)}`:"",b.messageCount>0?` · ${b.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:B?"ACTIVE":b.canResume?c===b.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},b.id)})]}):p.map(b=>s.jsxs("div",{onClick:()=>{h(e.routeId,b.id),m()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===b.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${x===b.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:b.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[b.id.substring(0,12),"..."]}),x===b.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},b.id)),(y&&!i&&T.length===0||!y&&p.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Hd,{size:32})}),s.jsx("div",{className:"text-[13px]",children:y?a.length>0?"No saved history matches these filters.":Pf():"No recent chat sessions found."})]}),y&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Ef()})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:f,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(nr,{size:13})," ",y?Df():"Refresh History"]})})})]})]});return typeof document>"u"?S:Js.createPortal(S,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 Cc({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 Bf=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Kf(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Of(e){return e.sessionId||e.instanceId||e.agentType}function wn(e,t){return e||t}function Mc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Mt(r,{fallbackId:r.id}));return t}function Tc(e,t={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=t.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Ha(e,t={}){return Wf(e,Tc(e,t))}function Wf(e,t={}){var d,h,f,j,N,p;const r=[],n=t.machineName,a=t.connectionState,i=Kf(e),c=Pu(e.type,{agentName:e.cliName}),l=Qe(e)||Ve(e)?c:rt(e.type),u=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var y,g;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||rt(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((y=x.activeChat)==null?void 0:y.messages)||[],activeModal:((g=x.activeChat)==null?void 0:g.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,surfaceHidden:x.surfaceHidden}}):[],m=Bf(e);if(m){const x=e.sessionId||e.instanceId,y=c,g=(d=e.activeChat)==null?void 0:d.activeModal,C=g&&Array.isArray(g.buttons)&&g.buttons.length>0,I=bt((h=e.activeChat)==null?void 0:h.status,{activeModal:(f=e.activeChat)==null?void 0:f.activeModal})||bt((N=(j=e.agents)==null?void 0:j[0])==null?void 0:N.status)||"idle",v=e.activeChat||{title:"",messages:[]};let T=v.title&&String(v.title).trim()?String(v.title).trim():"";const S=(p=e.activeChat)==null?void 0:p.id,k=e.chats;if(S&&Array.isArray(k)&&k.length>0){const _=k.find(H=>H.id===S||H.id&&String(H.id)===String(S));_!=null&&_.title&&String(_.title).trim()&&(T=String(_.title).trim())}const b=(Qe(e)||Ve(e),e.type),B=(Qe(e)||Ve(e))&&jo(T,y,b)?"":T,L=v.messages||[];r.push({routeId:e.id,sessionId:x,providerSessionId:e.providerSessionId,nativeSessionId:x,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:Qe(e)?e.mode||"terminal":"chat",agentName:y,agentType:b,status:I,title:B,messages:L,resume:e.resume,hostIdeType:!Qe(e)&&!Ve(e)?e.type:void 0,workspaceName:i,displayPrimary:B||i||(Qe(e)?e.mode==="chat"?y:"Terminal":y),displaySecondary:l,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:C?g.buttons:void 0,modalMessage:C?g.message:void 0,streamSource:"native",tabKey:wn(x,e.id),machineName:n,connectionState:a})}if(m&&(Qe(e)||Ve(e)))return r;for(const x of u){const y=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,g=Du(x),C=Of(x),I=`${e.id}:${C}`,v=x.title&&String(x.title).trim()||"",T=jo(v,x.agentName,x.agentType)?"":v,S=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||S.length>0||y||T||!["idle","panel_hidden","disconnected","not_monitored"].includes(g))&&r.push({routeId:e.id,sessionId:x.sessionId||x.instanceId,providerSessionId:x.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:x.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:x.sessionCapabilities,mode:"chat",agentName:x.agentName,agentType:x.agentType,status:g,title:T,messages:S,hostIdeType:e.type,workspaceName:i,displayPrimary:T||i||x.agentName||l,displaySecondary:`${l} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,modalButtons:y?x.activeModal.buttons:void 0,modalMessage:y?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:wn(x.sessionId||x.instanceId,I),machineName:n,connectionState:a})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:i,displayPrimary:i||l,displaySecondary:l,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:wn(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function Hf(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=Hf(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Ac=[{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:"🏄"}],Lc=[{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:"🧩"}],Rc=[{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:"🟠"}],Ff=Ac,Uf=Lc,zf=Rc;function ds(...e){return sd(rd(e))}function Vf({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:ds("dashboard-header",i),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function _c({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(Vf,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ds("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const la="adhdev:themechange";function Gf(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function hs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function xs(e){return e==="system"?Gf():e}function Pc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Ir(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(la,{detail:{preference:e,theme:t}}))}function qf(){const e=hs(),t=xs(e);Pc(t),Ir(e,t)}function Fa(){const[e,t]=o.useState(hs),[r,n]=o.useState(()=>xs(hs()));o.useEffect(()=>{Pc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const m=u.matches?"light":"dark";n(m),Ir("system",m)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const m=u.detail||{},d=m.preference,h=m.theme;t(d==="dark"||d==="light"||d==="system"?d:hs()),n(h==="dark"||h==="light"?h:xs(hs()))},l=u=>{if(u.key!=="theme")return;const m=hs(),d=xs(m);t(m),n(d)};return window.addEventListener(la,c),window.addEventListener("storage",l),()=>{window.removeEventListener(la,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=xs(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Ir(c,l)},[]),i=o.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=xs(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Ir(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const $o={dark:"Dark",light:"Light",system:"System"};function Yf({collapsed:e}){const{preference:t,cycleTheme:r}=Fa(),n=t==="dark"?s.jsx(Ud,{size:16}):t==="light"?s.jsx(Fd,{size:16}):s.jsx(zd,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${$o[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:$o[t]})]})}function jn(e,t){return e?typeof e=="function"?e(t):e:null}function Xf({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:u="sidebar-collapsed"}){const[m,d]=o.useState(!1),[h,f]=o.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),j=()=>d(!0),N=()=>d(!1),p=()=>{f(C=>{const I=!C;try{localStorage.setItem(u,I?"1":"0")}catch{}return I})},x=o.useMemo(()=>({collapsed:h,mobileMenuOpen:m,openMobileMenu:j,closeMobileMenu:N,toggleCollapsed:p}),[h,m]),y=C=>`nav-item${C.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${C.className?` ${C.className}`:""}`,g=C=>s.jsxs("div",{className:y(C),id:`nav-${C.id}`,onClick:()=>{C.onSelect(),N()},title:h?C.title??(typeof C.label=="string"?C.label:void 0):C.title,children:[s.jsx("span",{className:"nav-icon",children:C.icon}),!h&&C.label]},C.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:j,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),m&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:N,onKeyDown:C=>C.key==="Escape"&&N()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:jn(t,x)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:N,children:s.jsx(vt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(g)}),n.map(C=>s.jsxs("div",{className:C.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&C.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:C.title}):null,C.items.map(g)]},C.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(g),jn(i,x),s.jsx(Yf,{collapsed:h}),jn(c,x)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function kt({title:e,icon:t,description:r,accentColor:n,className:a,children:i}){return s.jsxs("div",{className:ds("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function Dc({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ds("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Jf={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"},Qf={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function gr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ds("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Jf[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Qf[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 Zf={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"},ep={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function tp({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ds("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Zf[e],r),children:[s.jsx("span",{className:ds("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",ep[e])}),n]})}function Xt({label:e,description:t,checked:r,disabled:n,onChange:a,extra:i}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,s.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function sp({onPrefChange:e}){const[t,r]=zu(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>i("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(St,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>i("browserNotifications",c)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{Qi().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Gd,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(er,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function Vr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function rp(e,t){const r=Vr(e),n=Vr(t);if(!r||!n)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function Ec(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function qs(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||rp(r,t)>=0)return!1;const n=Vr(r),a=Vr(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function np(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function kn(e,t){return e instanceof Error?e.message:t}function ap({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(Dc,{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(ip,{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 Js.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:i,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function op(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Ff,...Uf,...zf].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 ip({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var F,O;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[m,d]=o.useState(null),[h,f]=o.useState("idle"),[j,N]=o.useState(""),p=e.version||null,x=((F=e.machine)==null?void 0:F.platform)||((O=e.system)==null?void 0:O.platform)||"",y=Mt(e,{fallbackId:e.id}),g=x==="win32"?"🪟":x==="darwin"?"🍎":"🐧",C=t.filter(M=>M.daemonId===e.id&&M.transport==="cdp-page"),I=t.filter(M=>M.daemonId===e.id&&M.transport==="pty"),v=t.filter(M=>M.daemonId===e.id&&M.transport==="acp"),T=e.p2p,S=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const M=np(await r(e.id,"daemon_upgrade",{}));M.alreadyLatest?(c("done"),u(`Already on v${M.version||"latest"}.`)):M.upgraded||M.success?(c("done"),u(`Upgrade to v${M.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(M.error||"Upgrade failed"))}catch(M){c("error"),u(kn(M,"Connection lost during upgrade"))}}},k=async()=>{if(d(null),!!n){f("loading");try{await n(e.id),f("done"),N("Machine disconnected.")}catch(M){f("error"),N(kn(M,"Failed to disconnect"))}}},b=async()=>{if(d(null),!!a){f("loading");try{await a(e.id),f("done"),N("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(M){f("error"),N(kn(M,"Failed to revoke token"))}}},B="0.9.44",L=Ec(e,B),_=qs(e,B),H=C.length+I.length+v.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:g}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:y}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),p&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!L&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&L&&s.jsx("button",{onClick:S,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${B}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${_?"↑ Update now":`↑ Update${` to v${B}`}`}`}),n&&s.jsx("button",{onClick:()=>d("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>d("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(tp,{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:[T&&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 ${T.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${T.state==="connecting"||T.state==="new"?"animate-pulse":""}`,style:T.state==="connecting"||T.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",T.state==="connected"?"connected":T.state==="connecting"||T.state==="new"?"connecting...":T.state||"off"]}),T.peers!==void 0&&T.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",T.peers," peer",T.peers!==1?"s":"",")"]})]}),T&&H>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),H>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(M=>{const A=op(M.type),U=M.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:A.icon}),s.jsx("span",{children:A.name}),U!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${U?"bg-green-400":"animate-pulse"}`,style:U?void 0:{background:"var(--status-warning)"},title:U?"CDP connected":"CDP connecting..."})]},M.id)}),I.map(M=>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:M.cliName||"CLI"})]},M.id)),v.map(M=>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:M.cliName||"ACP"})]},M.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||j)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-red-400":i==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:j||l})]}),m==="disconnect"&&s.jsx(Bo,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
|
|
29
|
+
`)))return}const U=(c==null?void 0:c[A.id])??p[A.id];try{const $=await k(A.invokeScript),E=pr($);if(E&&!E.ok||hr($))throw new Error((E==null?void 0:E.error)||Ds($)||`Could not run ${A.label}`);E&&b(A,U??!0,E)}catch($){B(A,U);const E=$ instanceof Error?$.message:`Could not run ${A.label}`;it.showToast(E,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${m}33`,background:`${m}12`,color:m},children:a}),L.map(A=>{const U=String(x[A.id]||""),$=um(A,y,U),E=C===A.id,z=v===A.id,Y=Mr(A,y),ve="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(A.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${ve} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${m}55`:"var(--border-default)",background:E?`${m}10`:"var(--surface-tertiary)",color:U?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void _(A),title:A.label,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:z?"Loading…":$||A.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),E&&Y.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>I(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:A.label}),Y.map(re=>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:re.value===U?`${m}14`:"transparent",color:re.value===U?"var(--text-primary)":"var(--text-secondary)",borderLeft:re.value===U?`2px solid ${m}`:"2px solid transparent"},title:re.description||re.label,onMouseEnter:ye=>{ye.currentTarget.style.background=`${m}10`},onMouseLeave:ye=>{ye.currentTarget.style.background=re.value===U?`${m}14`:"transparent"},onClick:()=>void H(A,re.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:re.label}),re.value===U&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},re.value))]})]})]},A.id);case"cycle":return s.jsxs("button",{type:"button",className:`${ve} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:U?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void F(A),title:`Click to cycle: ${Y.map(re=>re.label).join(" → ")}`,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$||A.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},A.id);case"toggle":return s.jsxs("button",{type:"button",className:`${ve} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:U?`${m}44`:"var(--border-default)",background:U?`${m}14`:"var(--surface-tertiary)",color:U?m:"var(--text-muted)"},onClick:()=>void O(A),"aria-pressed":!!U,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),A.label]},A.id);case"action":return s.jsxs("button",{type:"button",className:`${ve} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void T(A),children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:A.resultDisplay==="inline"&&U?`${A.label}: ${U}`:A.label})]},A.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:U?"var(--text-primary)":"var(--text-muted)"},children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:U?`${A.label}: ${U}`:A.label})]},A.id);default:return null}})]})})}function pm({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:m}=zi(),d=Ma(l,{hostIdeType:a,providerType:i});return!e||t||d.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(fm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:d,controlValues:u})})}function hm({hasDraft:e,isBusy:t=!1}){return!e||t}const Zi=o.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1,animateVisibility:m=!0}){const d=o.useRef(null),[h,f]=o.useState(""),{isVisible:j,toggleVisibility:N}=zi();o.useEffect(()=>{f("")},[t]),o.useEffect(()=>{var x;l&&((x=d.current)==null||x.focus({preventScroll:!0}))},[t,l]);const p=async()=>{const x=h.trim();if(!x||a)return;await c(x)!==!1&&f("")};return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":""].filter(Boolean).join(" "),style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[s.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[u&&s.jsx("button",{type:"button",onClick:N,"aria-label":j?"Hide controls":"Show controls","aria-pressed":j,title:j?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("input",{ref:d,type:"text",placeholder:i||`Send message to ${r}...`,value:h,onChange:x=>f(x.target.value),onPaste:x=>{const y=x.clipboardData.getData("text");y&&f(g=>g+y),x.preventDefault()},onKeyDown:x=>{if(x.key==="Enter"){if(x.nativeEvent.isComposing){x.preventDefault();return}x.preventDefault(),p()}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),s.jsx("button",{onClick:()=>{p()},disabled:hm({hasDraft:!!h.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${h.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:h.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:h.trim()?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),Qe=e=>e.transport==="pty",Ls=(e,t)=>Qe(e)?e.mode||"terminal":"chat",ec=(e,t)=>Qe(e)&&Ls(e)==="terminal",Ve=e=>e.transport==="acp";function Ut(e){return e.streamSource!=="agent-stream"}function ms(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function tc(e){return e.machineName||""}function Rs(e){return ms(e)}function $t(e){return e.agentType||""}function Hr(e){return e.hostIdeType||""}function Ia(e){return e.displayPrimary||e.agentName||"Agent"}function sc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function xm(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function rc(e){const t=xm(e),r=ks(t==null?void 0:t.content),n=ks(e.lastMessagePreview);return r||n||""}function bm(e){return rc(e)||e.displaySecondary||""}function nc(e){return[e.displaySecondary,tc(e)].filter(Boolean)}function Ns(e){return e.agentName||rt($t(e))}function gm(e){var t,r;if(!Ut(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return rt(Hr(e)||$t(e))}function ac(e){return Ut(e)?e.sessionId:e.nativeSessionId}function No(e){return Ut(e)?"native":e.tabKey}function ym(e){return e.sessionId}function vm(e,t){if(t)return Ut(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function wm(e,t){const r=$t(e),n=Ut(e),a=Qe(e)||Ve(e),i=n?a?Ns(e)||(t==null?void 0:t.cliName)||rt(Hr(e)||r):t!=null&&t.type?rt(t.type):rt(Hr(e)||r):Ns(e);return{isNativeConversation:n,isCli:Qe(e),isAcp:Ve(e),isCliTerminal:ec(e),providerType:r,displayLabel:i,targetEntry:vm(e,t)}}function gt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ot(e,t){const r=gt(t);return r?`${e}:${r}`:void 0}function Ft(e,t,r){const n=Ot(t,r),a=gt(r);n&&e.push(n),a&&e.push(a)}function bs(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function oc(e){return gt(e.providerSessionId)||gt(e.sessionId)||gt(e.tabKey)||gt(e.routeId)}function Aa(e){return bs([gt(e.providerSessionId),gt(e.sessionId)])}function vs(e){const t=[];return Ft(t,"provider",e.providerSessionId),Ft(t,"session",e.sessionId),Ft(t,"tab",e.tabKey),Ft(t,"route",e.routeId),bs(t)}function jm(e){const t=[];return gt(e.providerSessionId)?(Ft(t,"provider",e.providerSessionId),bs(t)):gt(e.sessionId)?(Ft(t,"session",e.sessionId),bs(t)):gt(e.tabKey)?(Ft(t,"tab",e.tabKey),bs(t)):gt(e.routeId)?(Ft(t,"route",e.routeId),bs(t)):[]}function La(e){return Ot("provider",e.providerSessionId)||Ot("session",e.sessionId)||Ot("tab",e.tabKey)||Ot("route",e.routeId)||"unknown:"}function or(e){return Aa(e)[0]}function km(e){const t=gt(e.providerSessionId),r=gt(e.sessionId),n=gt(e.tabKey),a=gt(e.routeId),i=[Ot("provider",t),Ot("session",r),Ot("tab",n),Ot("route",a)].filter(u=>typeof u=="string"),c=vs({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=La({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:oc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:or({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function ra(e,t){const r=km(e);return jm(t).some(n=>r.lookupKeys.includes(n))}function Co(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Qt(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],r=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,n=Co(t==null?void 0:t.receivedAt)||Co(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function na(e,t=0){return Qt(e)||e.lastUpdated||t||0}function ic(e){return Qt(e)||e.lastUpdated||0}function cc(e,t,r=ic){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(t.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(t.displaySecondary);return c!==0?c:e.tabKey.localeCompare(t.tabKey)}function aa(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 Sm(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!aa(e)&&!e.title.trim()}function Nm(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(aa(r))-Number(aa(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:cc(t,r)})[0]||null}function _t(e,t){const r=e.filter(c=>c.routeId===t);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,a=r.filter(c=>c.streamSource==="agent-stream"),i=Nm(a);return n?i&&Sm(n)?i:n:i||r[0]||null}function zt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ra(e){return or(e)||e.tabKey||e.routeId||null}function lc(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(t)return t;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=_t(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?Ra(a):null}function dc({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Is(),c=ms(e),l=tc(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",m=e.streamSource==="agent-stream"&&!!e.agentName,d=!m&&(e.transport==="pty"||e.transport==="acp"),h=Ns(e),f=gm(e),j=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),N=o.useCallback(()=>{if(r){r();return}const p=Ra(e);p&&i(zt(p))},[e,i,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:N,title:f,children:[s.jsx(St,{size:12}),s.jsx("span",{children:f})]}):s.jsxs("span",{className:"conversation-meta-chip",title:f,children:[s.jsx(St,{size:12}),s.jsx("span",{children:f})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(er,{size:12}),s.jsx("span",{children:h})]}),d&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(er,{size:12}),s.jsx("span",{children:h})]}),l&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:j,title:l,children:[s.jsx(is,{size:12}),s.jsx("span",{children:l})]}):s.jsxs("span",{className:"conversation-meta-chip",title:l,children:[s.jsx(is,{size:12}),s.jsx("span",{children:l})]}))]})}function gn(e,t){return`${e}:${t}`}function Cm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Es(e,t){Cm()&&console.debug(`[subscription-manager] ${e}`,t)}class Tm{constructor(){ze(this,"active",new Map);ze(this,"retryTimers",new Map)}subscribe(t,r,n,a,i){var d;const c=gn(n.topic,n.key),l=this.active.get(c);let u=!0;if(l)l.handlers.add(a),l.lastUpdate&&a(l.lastUpdate);else{const h={daemonId:r,request:n,handlers:new Set([a])};this.active.set(c,h),Es("subscribe",{daemonId:r,topic:n.topic,key:n.key}),u=((d=t.sendData)==null?void 0:d.call(t,r,n))??!1,!u&&(i!=null&&i.retryIntervalMs)&&this.scheduleRetry(c,t,i.retryIntervalMs)}const m=()=>{var j;this.clearRetry(c);const h=this.active.get(c);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(c);const f={type:"unsubscribe",topic:n.topic,key:n.key};Es("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(j=t.sendData)==null||j.call(t,r,f)};return m.initialSendAccepted=u,m}publish(t){const r=gn(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,js.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),n.handlers.forEach(a=>{a(t),js.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,r,n){const a=gn(t,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(t){var r;Es("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=t.sendData)==null||r.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,r){var a;const n=Array.from(this.active.values()).filter(i=>i.daemonId===t);Es("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}scheduleRetry(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var l;this.retryTimers.delete(t);const i=this.active.get(t);if(!i)return;const c=((l=r.sendData)==null?void 0:l.call(r,i.daemonId,i.request))??!1;Es("subscribe_retry",{id:t,accepted:c,topic:i.request.topic,key:i.request.key}),c||this.scheduleRetry(t,r,n)},n);this.retryTimers.set(t,a)}clearRetry(t){const r=this.retryTimers.get(t);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(t))}}const Vt=new Tm;function Mm(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 Im(e){const t=[],r=new Map;for(const n of e)if(n.parentId){const a=r.get(n.parentId)||[];a.push(n),r.set(n.parentId,a)}else t.push(n);return{topLevel:t,childrenByParent:r}}function Fr(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=t,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:m,childrenByParent:d}=Im(u),h=Mm(i,n),f=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,j=m.filter(x=>x.kind==="workspace"&&x.transport==="cdp-page"),N=m.filter(x=>x.kind==="agent"&&x.transport==="pty"),p=m.filter(x=>x.kind==="agent"&&x.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...f&&{machine:f,platform:f.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:j.some(x=>!!x.cdpConnected)});for(const x of j){const y=h.get(x.id),g=Fs(x,y),C=(d.get(x.id)||[]).map(I=>Fs(I,h.get(I.id)));r.push({id:`${n}:ide:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:g.parentId,sessionKind:g.kind,transport:g.transport,sessionCapabilities:g.capabilities,type:g.providerType,status:g.cdpConnected?"online":"detected",daemonId:n,instanceId:x.id,workspace:g.workspace,terminals:0,childSessions:C,agents:C.map(I=>({id:I.id,name:I.providerName||I.providerType,type:I.providerType,status:I.status})),activeChat:g.activeChat,chats:[],cdpConnected:g.cdpConnected,...g.lastMessagePreview!==void 0&&{lastMessagePreview:g.lastMessagePreview},...g.lastMessageRole!==void 0&&{lastMessageRole:g.lastMessageRole},...g.lastMessageAt!==void 0&&{lastMessageAt:g.lastMessageAt},...g.lastMessageHash!==void 0&&{lastMessageHash:g.lastMessageHash},lastUpdated:g.lastUpdated,unread:g.unread,lastSeenAt:g.lastSeenAt,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,seenCompletionMarker:g.seenCompletionMarker,surfaceHidden:g.surfaceHidden,...g.controlValues!==void 0&&{controlValues:g.controlValues},...g.providerControls!==void 0&&{providerControls:g.providerControls},...g.summaryMetadata!==void 0&&{summaryMetadata:g.summaryMetadata},timestamp:l})}for(const x of N){const y=h.get(x.id),g=Fs(x,y);r.push({id:`${n}:cli:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:g.parentId,sessionKind:g.kind,transport:g.transport,sessionCapabilities:g.capabilities,type:g.providerType,agentType:g.providerType,status:g.status||"running",daemonId:n,instanceId:x.id,cliName:g.providerName||g.providerType,mode:g.mode||(y==null?void 0:y.mode)||"terminal",workspace:g.workspace||"",activeChat:g.activeChat,...g.resume!==void 0&&{resume:g.resume},...g.runtimeKey!==void 0&&{runtimeKey:g.runtimeKey},...g.runtimeDisplayName!==void 0&&{runtimeDisplayName:g.runtimeDisplayName},...g.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:g.runtimeWorkspaceLabel},...g.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:g.runtimeWriteOwner},...g.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:g.runtimeAttachedClients},...g.lastMessagePreview!==void 0&&{lastMessagePreview:g.lastMessagePreview},...g.lastMessageRole!==void 0&&{lastMessageRole:g.lastMessageRole},...g.lastMessageAt!==void 0&&{lastMessageAt:g.lastMessageAt},...g.lastMessageHash!==void 0&&{lastMessageHash:g.lastMessageHash},lastUpdated:g.lastUpdated,unread:g.unread,lastSeenAt:g.lastSeenAt,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,seenCompletionMarker:g.seenCompletionMarker,surfaceHidden:g.surfaceHidden,...g.controlValues!==void 0&&{controlValues:g.controlValues},...g.providerControls!==void 0&&{providerControls:g.providerControls},...g.summaryMetadata!==void 0&&{summaryMetadata:g.summaryMetadata},timestamp:l,_isCli:!0})}for(const x of p){const y=h.get(x.id),g=Fs(x,y);r.push({id:`${n}:acp:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:g.parentId,sessionKind:g.kind,transport:g.transport,sessionCapabilities:g.capabilities,type:g.providerType,agentType:g.providerType,status:g.status||"running",daemonId:n,instanceId:x.id,cliName:g.providerName||g.providerType,mode:"chat",workspace:g.workspace||"",activeChat:g.activeChat,...g.runtimeKey!==void 0&&{runtimeKey:g.runtimeKey},...g.runtimeDisplayName!==void 0&&{runtimeDisplayName:g.runtimeDisplayName},...g.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:g.runtimeWorkspaceLabel},...g.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:g.runtimeWriteOwner},...g.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:g.runtimeAttachedClients},...g.lastMessagePreview!==void 0&&{lastMessagePreview:g.lastMessagePreview},...g.lastMessageRole!==void 0&&{lastMessageRole:g.lastMessageRole},...g.lastMessageAt!==void 0&&{lastMessageAt:g.lastMessageAt},...g.lastMessageHash!==void 0&&{lastMessageHash:g.lastMessageHash},lastUpdated:g.lastUpdated,unread:g.unread,lastSeenAt:g.lastSeenAt,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,seenCompletionMarker:g.seenCompletionMarker,surfaceHidden:g.surfaceHidden,...g.controlValues!==void 0&&{controlValues:g.controlValues},...g.providerControls!==void 0&&{providerControls:g.providerControls},...g.summaryMetadata!==void 0&&{summaryMetadata:g.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const Am=15e3,Lm=15e3,Rm=6e4,_m=1200,To=12,Pm=8e3,Dm=4e3,yn=new Map,vn=new Map,xr=new Set,Gs=new Map;function Em(e){if(!e||typeof e!="object")return null;const t=e,r=t.status;if(r&&typeof r=="object")return r;const n=t.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return t}function Mo(e,t){const r=Gs.get(e);!r||r.size===0||(Gs.delete(e),r.forEach(n=>n(t)))}function $m(e,t){return new Promise(r=>{const n=Gs.get(e)||new Set;Gs.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&Gs.delete(e),r(c)},i=setTimeout(()=>a(!1),t);n.add(a)})}function ir(){const{sendCommand:e,sendData:t}=wt(),{injectEntries:r,getIdes:n}=Qs();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??Rm,l=vn.get(a)||0;if(!(i!=null&&i.force)&&xr.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=yn.get(a);if(u)return u;const m=(async()=>{if(t&&!xr.has(a)){const p=Vt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},x=>{const y=n(),g=y.find(I=>I.id===a),C=Fr(x.status,{daemonId:a,existingDaemon:g,existingEntries:y,timestamp:x.timestamp});C.length>0&&r(C),vn.set(a,Date.now()),Mo(a,!0)});if(p.initialSendAccepted?xr.add(a):xr.delete(a),!(i!=null&&i.force)&&p.initialSendAccepted&&await $m(a,_m))return}const d=await e(a,"get_status_metadata"),h=Em(d);if(!h)return;const f=n(),j=f.find(p=>p.id===a),N=Fr(h,{daemonId:a,existingDaemon:j,existingEntries:f,timestamp:h.timestamp||Date.now()});N.length>0&&r(N,{authoritativeDaemonIds:[a]}),vn.set(a,Date.now()),Mo(a,!0)})().finally(()=>{yn.delete(a)});return yn.set(a,m),m},[n,r,e,t])}function sn(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}function ws(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:Qe(e)||Ve(e)?{agentType:$t(e)}:e.streamSource==="agent-stream"?{agentType:$t(e)}:t}function sr(e){return e?Rs(e):""}function $s(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function _a(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Bm(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 Km=60,Om=1e3;function uc(e={}){return e.isCliLike?Om:Km}function Wm(e={}){return uc(e)}const cr=60,Hm=1e3,Pa=12e4,Fm=new Set(["generating","waiting_approval","starting","streaming","working"]),Io=new Map;function Da(e,t){return`${e}::${t}`}function oa(e=cr){return{liveMessages:[],cursor:mc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function ia(e){return Mi(e)}function mc(e,t=cr){return{knownMessageCount:e.length,lastMessageSignature:ia(e[e.length-1]),tailLimit:t}}function br(e,t){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function Ao(e){for(let t=e.length-1;t>=0;t-=1){const r=sn(e[t]);if(r>0)return r}return 0}function Um(e,t){if(t.length===0)return!1;if(e.length===0)return!0;const r=Ao(e),n=Ao(t);return!(r>0&&n<=0||r>0&&n>0&&n<r||r>0&&n===r&&t.length<e.length)}function zm(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 Vm{constructor(t){ze(this,"manager");ze(this,"sendData");ze(this,"daemonId");ze(this,"sessionId");ze(this,"historySessionId");ze(this,"subscriptionKey");ze(this,"snapshot");ze(this,"transportSubscription",null);ze(this,"listeners",new Set);ze(this,"retainCount",0);ze(this,"loadHistoryPromise",null);ze(this,"pendingDisconnectTimer",null);this.manager=t.manager||Vt,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=oa(Math.max(0,t.tailLimit??cr))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);if(r!==this.snapshot.cursor.tailLimit){const n=r>this.snapshot.cursor.tailLimit,a=n?0:Math.min(this.snapshot.cursor.knownMessageCount,this.snapshot.liveMessages.length),i=n?"":this.snapshot.cursor.lastMessageSignature;this.snapshot={...this.snapshot,cursor:{knownMessageCount:a,lastMessageSignature:i,tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect())}}}getSnapshot(){return this.snapshot}hydrateLiveMessages(t){const r=Array.isArray(t)?t:[];if(!Um(this.snapshot.liveMessages,r))return;const n=r,a=mc(n,this.snapshot.cursor.tailLimit);br(this.snapshot.liveMessages)===br(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a},this.emit())}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await t(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},knownMessageCount:this.snapshot.cursor.knownMessageCount,lastMessageSignature:this.snapshot.cursor.lastMessageSignature,...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:Hm}))}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=ia(this.snapshot.liveMessages[this.snapshot.liveMessages.length-1]);if(t.syncMode!=="full"&&r&&n===r){const u={knownMessageCount:Math.max(this.snapshot.cursor.knownMessageCount,Number(t.totalMessages||0)),lastMessageSignature:r,tailLimit:this.snapshot.cursor.tailLimit};this.snapshot.cursor.knownMessageCount===u.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===u.lastMessageSignature||(this.snapshot={...this.snapshot,cursor:u},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:u.knownMessageCount,lastMessageSignature:u.lastMessageSignature}));return}const a=zm(this.snapshot.liveMessages,t),i={knownMessageCount:a.length,lastMessageSignature:typeof t.lastMessageSignature=="string"?t.lastMessageSignature:ia(a[a.length-1]),tailLimit:this.snapshot.cursor.tailLimit};br(this.snapshot.liveMessages)===br(a)&&this.snapshot.cursor.knownMessageCount===i.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===i.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:a,cursor:i},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:i.knownMessageCount,lastMessageSignature:i.lastMessageSignature}),this.emit())}}function fc(e){const t=Da(e.daemonId,e.sessionId),r=Io.get(t);if(r)return r.updateOptions(e),r;const n=new Vm(e);return Io.set(t,n),n}function Gm(e,t){return{...e,loadHistoryPage:t}}function qm(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Ym(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Fm.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??Pa)),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 Xm(e=Pa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Jm(e,t={}){const r=new Set,n=[];for(const a of e){if(!Ym(a,t))continue;const i=Rs(a),c=a.sessionId||"";if(!i||!c)continue;const l=Da(i,c);if(r.has(l))continue;r.add(l);const u=or(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(qm),{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=or(e)||c,u=`daemon:${i}:session:${c}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??cr),d=o.useMemo(()=>!a||!i||!c?null:fc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:m}),[i,a,l,r,c,u,m]),[h,f]=o.useState(()=>(d==null?void 0:d.getSnapshot())||oa(m));o.useEffect(()=>{if(!d){f(oa(m));return}d.retain(),f(d.getSnapshot());const N=d.subscribe(p=>{f(p)});return()=>{N(),d.release()}},[d,m]),o.useEffect(()=>{d&&(d.hydrateLiveMessages(e.messages),f(d.getSnapshot()))},[e.messages,d]);const j=o.useCallback(async()=>{!d||!i||!c||await d.loadHistoryPage(async()=>{const N=e.agentType,p=await n(i,"chat_history",{agentType:N,offset:d.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),x=p&&typeof p=="object"&&"result"in p?p.result||{}:p||{};return{messages:Array.isArray(x.messages)?x.messages:[],hasMore:x.hasMore===!0}})},[e.agentType,d,i,l,n,c]);return o.useMemo(()=>Gm(h,j),[j,h])}function Zm(e,t){const{sendData:r}=wt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??cr),i=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Pa)),c=Xm(i),[l,u]=o.useState(0),[m,d]=o.useState(()=>new Map);o.useEffect(()=>{if(!n||e.length===0)return;const f=setInterval(()=>{u(j=>j+1)},c);return()=>{clearInterval(f)}},[e.length,n,c]);const h=o.useMemo(()=>Jm(e,{recentActivityMs:i}),[e,i,l]);return o.useEffect(()=>{if(!n||!r||h.descriptors.length===0){d(x=>x.size===0?x:new Map);return}const f=h.descriptors.map(x=>({key:Da(x.daemonId,x.sessionId),controller:fc({...x,sendData:r,tailLimit:a})})),j=new Set(f.map(({key:x})=>x)),N=(x,y)=>{d(g=>{const C=new Map(g);for(const I of C.keys())j.has(I)||C.delete(I);return C.set(x,y),C})},p=f.map(({key:x,controller:y})=>(y.retain(),N(x,y.getSnapshot()),y.subscribe(g=>N(x,g))));return()=>{p.forEach(x=>x()),f.forEach(({controller:x})=>x.release())}},[h.signature,n,r,a]),m}function Lo(e,t){const r=e[e.length-1];if(!r)return`empty:${t||""}`;let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return[t||"",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function Ur(e){for(let t=e.length-1;t>=0;t-=1){const r=sn(e[t]);if(r>0)return r}return 0}function ef(e){const t=Rs(e),r=e.sessionId||"";return t&&r?`${t}::${r}`:""}function tf(e,t){if(t.length===0)return!1;const r=Array.isArray(e.messages)?e.messages:[];if(r.length===0)return!0;const n=Ur(r),a=Ur(t);if(n<=0||a<=n)return!1;const i=Lo(r,e.status),c=Lo(t,e.status);return i!==c}function sf(e,t){const r=t[t.length-1],n=sn(r),a=ks(r==null?void 0:r.content);return{...e,messages:t,...a?{lastMessagePreview:a}:{},...n>0?{lastMessageAt:n}:{}}}function rf(e,t){const r=Array.isArray(e.messages)?e.messages:[],n=(t==null?void 0:t.liveMessages)||[];if(n.length===0)return r;if(r.length===0)return n;const a=Ur(r),i=Ur(n);return a>0&&(i<=0||a>=i)?r:n}function nf(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,i=Math.max(0,r.length-n)>0?r.slice(-n):r;return t.length===0?i:[...t,...i]}function Ro(e,t){if(t.size===0||e.length===0)return e;let r=!1;const n=e.map(a=>{var l;const i=ef(a);if(!i)return a;const c=((l=t.get(i))==null?void 0:l.liveMessages)||[];return tf(a,c)?(r=!0,sf(a,c)):a});return r?n:e}function af(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function of(e){return af(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const cf=60;function ca({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:m=!1,scrollToBottomRequestNonce:d,isInputActive:h=!0,isVisible:f=!0}){var le,be,ge,G,ne;const j=o.useRef(new Map),N=ir();ar("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const p=jt.useMemo(()=>As(e),[e.status,e.connectionState]),x=o.useMemo(()=>wm(e,t),[e,t]),y=o.useMemo(()=>{var q;return Ma((q=x.targetEntry)==null?void 0:q.providerControls,{hostIdeType:e.hostIdeType,providerType:x.providerType})},[e.hostIdeType,x.providerType,(le=x.targetEntry)==null?void 0:le.providerControls]),g=uc({isCliLike:x.isCli||x.isAcp}),C=Wm({isCliLike:x.isCli||x.isAcp}),I=Qm(e,{enabled:f&&!!e.sessionId,tailLimit:C}),[v,M]=o.useState(g),S=e.tabKey,k=I.historyMessages,b=I.hasMoreHistory,B=I.historyError,L=rf(e,I);o.useEffect(()=>{M(g)},[g,S]);const _=Math.max(0,L.length-v),H=Ia(e),F=Rs(e),O=of(e),T=_a(e),A=a||T,U=!!T,[$,E]=o.useState(!1);o.useEffect(()=>{const q=x.targetEntry;F&&(!q||q.providerControls===void 0||q.controlValues===void 0)&&N(F,{minFreshMs:3e4}).catch(()=>{})},[F,x.isAcp,(be=x.targetEntry)==null?void 0:be.providerControls,(ge=x.targetEntry)==null?void 0:ge.controlValues,N]);const z=o.useCallback(async()=>{if(!$){if(L.length>v){M(q=>Math.min(L.length,q+cf));return}E(!0);try{await I.loadHistoryPage()}finally{E(!1)}}},[I,$,L.length,v]),{allMessages:Y,receivedAtMap:ve}=o.useMemo(()=>{const q=nf({historyMessages:k,liveMessages:L,visibleLiveCount:v}),ue={};return q.forEach((ce,je)=>{const ae=`${e.tabKey}:${Kr(ce,je)}`;let fe=sn(ce)||j.current.get(ae)||0;fe||(fe=Date.now(),j.current.set(ae,fe)),ue[Kr(ce,je)]=fe}),{allMessages:q,receivedAtMap:ue}},[e.tabKey,_,k,L,v]),re=o.useMemo(()=>l.filter(q=>q.routeId===e.tabKey).sort((q,ue)=>q.timestamp-ue.timestamp),[l,e.tabKey]),ye=o.useMemo(()=>{if(L.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((p.isGenerating||e.status==="streaming")&&E(!1),e.status==="not_monitored"&&O)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(er,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ss,{size:14})," Open ",H," 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"&&O)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(_i,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ss,{size:14})," Open ",H," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!$)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,O,i,c,$,L.length,H,p.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&s.jsx(dc,{conversation:e,className:"chat-pane-meta-row"}),s.jsx(pu,{messages:Y,actionLogs:re,agentName:Ns(e)||H||"Agent",userName:u,isCliMode:x.isCli||x.isAcp,isWorking:p.isGenerating,contextKey:e.tabKey,receivedAtMap:ve,lastMessageHash:e.lastMessageHash,onLoadMore:z,isLoadingMore:$,hasMoreHistory:b,hiddenLiveCount:_,loadError:B??void 0,emptyState:ye,scrollToBottomRequestNonce:d,isVisible:f}),s.jsx(pm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:x.providerType,displayLabel:x.displayLabel,controls:(G=x.targetEntry)==null?void 0:G.providerControls,controlValues:(ne=x.targetEntry)==null?void 0:ne.controlValues,isActive:h,isCliTerminal:x.isCliTerminal}),!x.isCliTerminal&&s.jsx(Zi,{contextKey:e.tabKey,panelLabel:H,isSending:n,isBusy:U,statusMessage:A,onSend:r,isActive:h,showControlsToggle:y.length>0})]})}let pc=os;function hc(){return pc()}class lf{constructor(){ze(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{var n;(n=this.listeners.get(t))==null||n.delete(r)}}emit(t,...r){var n;(n=this.listeners.get(t))==null||n.forEach(a=>a(...r))}}let xc=new lf;class df{sendPtyInput(t,r,n){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,r){return!1}get(t){}onScreenshot(t,r){return()=>{}}onRuntimeEvent(t,r,n){return()=>{}}requestRuntimeSnapshot(t,r,n){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let lt=new df;function uf(e){e.dashboardWS&&(xc=e.dashboardWS),e.connectionManager&&(lt=e.connectionManager),e.useDaemonsHook&&(pc=e.useDaemonsHook)}const mf=.5,ff=1.25;function at(e){return Ia(e)}function ls(e){return nc(e).join(" · ")}function bc(e){const t=rc(e);return t||(e.title?e.title:ls(e)||"No messages yet")}function gc(e,t){const{isReconnecting:r,isConnecting:n}=As(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function pf(e,t){const r=["Chat",...nc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function Zt(e){return gc(e)||ls(e)}function hf(e){return`${at(e)} · ${bc(e)}`}function xf(e){const t=Hr(e),r=t?rt(t):Ns(e);return`${at(e)} — ${r||"Agent"}`}function bf(e){return Ns(e)||"CLI"}function yc(e){return sc(e)}function vc(e){return e?`Remote · ${at(e)||e.workspaceName||"Session"}`:"Remote"}function gf({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var W;os();const{sendPtyInput:u}=wt(),[m,d]=o.useState(!1),h=o.useRef(!1);h.current=m;const[f,j]=o.useState("Runtime terminal unavailable"),[N,p]=o.useState(!1),[x,y]=o.useState(null),[g,C]=o.useState(!1),[I,v]=o.useState(!1),[M,S]=o.useState(1),[k,b]=o.useState({width:0,height:0}),[B,L]=o.useState({width:0,height:0}),[_,H]=o.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[F,O]=o.useState(null),T=o.useRef(null),A=o.useRef(null),U=o.useRef(!1),$=o.useRef(!1),E=o.useRef(c),z=o.useRef(0),Y=o.useRef(!1),ve=o.useRef(""),re=o.useRef(null),ye=o.useRef(!1),le=o.useRef(!1),be=o.useRef(null),ge=o.useRef(null),G=o.useRef(null),ne=32*1024,q=()=>{var w,R,P,V;return((R=(w=T.current)==null?void 0:w.ownerDocument)==null?void 0:R.defaultView)||((V=(P=A.current)==null?void 0:P.ownerDocument)==null?void 0:V.defaultView)||window},ue=w=>{const R=q();return{ownerWindow:R,frameId:R.requestAnimationFrame(w)}},ce=()=>{const w=be.current;if(w){try{w.ownerWindow.cancelAnimationFrame(w.frameId)}catch{}be.current=null}},je=()=>{const w=ge.current;if(w){try{w.ownerWindow.clearTimeout(w.timeoutId)}catch{}ge.current=null}},ae=()=>{const w=G.current;if(w){try{w.ownerWindow.clearTimeout(w.timeoutId)}catch{}G.current=null}},fe=()=>{c&&be.current===null&&(be.current=ue(()=>{Ze()}))},oe=e.tabKey,te=e.sessionId||"",ee=e.daemonId||((W=e.routeId)==null?void 0:W.split(":")[0])||e.routeId||"",X=_a(e),J=m?i||X:f,de=mf,D=ff,ie=.05,Q=()=>{const w=B.width,R=B.height;if(!Number.isFinite(k.width)||k.width<=0||!Number.isFinite(k.height)||k.height<=0||!Number.isFinite(w)||w<=0||!Number.isFinite(R)||R<=0)return 1;const P=k.width/w,V=k.height/R;return Number(Math.min(D,Math.max(de,Math.min(P,V))).toFixed(2))},we=Q(),Ne=U.current&&M>we,Ae=Number.isFinite(B.width)&&B.width>0?Math.max(k.width,Math.round(B.width*M)):k.width,Me=Number.isFinite(B.height)&&B.height>0?Math.max(k.height,Math.round(B.height*M)):k.height,Ue=()=>{ue(()=>{const w=A.current;w&&(w.scrollLeft=0,w.scrollTop=w.scrollHeight-w.clientHeight)})},We=()=>{var w,R;z.current=0,Y.current=!1,ve.current="",re.current=null,ye.current=!1,le.current=!1,U.current||($.current=!1,S(1)),be.current!==null&&ce(),d(!1),j("Runtime terminal unavailable"),ae(),je(),y(null),O(null),p(!1),C(!1),v(!1),(R=(w=r.current)==null?void 0:w.reset)==null||R.call(w)},Ke=()=>{var w,R;z.current=0,Y.current=!1,ve.current="",re.current=null,ye.current=!1,le.current=!1,be.current!==null&&ce(),d(!0),j(""),ae(),je(),y(null),O(null),p(!1),C(!1),v(!1),(R=(w=r.current)==null?void 0:w.reset)==null||R.call(w)},Ge=()=>{le.current&&(le.current=!1,ue(()=>{var w,R;(R=(w=r.current)==null?void 0:w.scrollToTop)==null||R.call(w)}))},Ze=()=>{if(be.current=null,!c)return;const w=ve.current;if(!w)return;const R=w.slice(0,ne);ve.current=w.slice(R.length);const P=r.current;if(!P){ve.current=R+ve.current,fe();return}P.write(R,()=>{if(ve.current.length>0){fe();return}Ge()})},Je=w=>{w&&(ve.current+=w,fe())},Ye=(w,R=0,P,V,Z={})=>{var he,Se,Re,ke;const me=!!Z.force;!me&&R>0&&z.current>=R||!me&&R===0&&Y.current||(z.current=R,R>0&&C(!0),d(!0),j(""),typeof P=="number"&&typeof V=="number"&&P>0&&V>0&&((Se=(he=r.current)==null?void 0:he.resize)==null||Se.call(he,P,V)),ve.current="",(ke=(Re=r.current)==null?void 0:Re.reset)==null||ke.call(Re),w?Je(w):Ge())};o.useEffect(()=>{We()},[te]),o.useEffect(()=>{var R;if(!te)return;const w=((R=lt.onRuntimeEvent)==null?void 0:R.call(lt,te,P=>{if(!(!P||P.sessionId!==te)){if(P.type==="runtime_snapshot"){if(!c){re.current={text:P.text||"",seq:P.seq||0,cols:P.cols,rows:P.rows,force:!!P.force};return}Ye(P.text||"",P.seq||0,P.cols,P.rows,{force:!!P.force});return}if(P.type==="session_output"){Y.current=!0,typeof P.seq=="number"&&(z.current=Math.max(z.current,P.seq),P.seq>0&&C(!0)),h.current||d(!0),h.current||j(""),typeof P.data=="string"&&Je(P.data);return}if(P.type==="session_cleared"){if(!c){ye.current=!0,ve.current="",re.current=null;return}Ke();return}if(P.type==="session_io_error"){const V=typeof P.error=="string"&&P.error?P.error:typeof P.reason=="string"&&P.reason?P.reason:"unknown error";d(!1),j(`Runtime input failed: ${V}`);return}}},ee))||(()=>{});return()=>{w()}},[ee,te,r,c]);const mt=async(w={})=>{var R;if(!ee||!te)return{success:!1,error:"daemonId and sessionId are required"};w.preserveStatus||j(w.loadingMessage||"Loading runtime terminal...");try{const P=await((R=lt.requestRuntimeSnapshot)==null?void 0:R.call(lt,ee,te,{sinceSeq:w.sinceSeq,force:w.force}));return P&&P.success===!1?(w.preserveStatus||(d(!1),j(`Runtime terminal unavailable: ${P.error}`)),P):P||{success:!0}}catch(P){const V=(P==null?void 0:P.message)||String(P);return w.preserveStatus||(d(!1),j(`Runtime terminal unavailable: ${V}`)),{success:!1,error:V}}},pt=async w=>{var me,he;const R=((me=T.current)==null?void 0:me.ownerDocument)||document,P=R.defaultView||window,V=(he=P.navigator)==null?void 0:he.clipboard;if(V!=null&&V.writeText&&P.isSecureContext)try{return await V.writeText(w),!0}catch{}let Z=null;try{return Z=R.createElement("textarea"),Z.value=w,Z.setAttribute("readonly","true"),Z.style.position="fixed",Z.style.left="-9999px",Z.style.top="0",R.body.appendChild(Z),Z.focus(),Z.select(),R.execCommand("copy")}catch{return!1}finally{Z==null||Z.remove()}},dt=w=>{je(),O(w);const R=q();ge.current={ownerWindow:R,timeoutId:R.setTimeout(()=>{ge.current=null,O(P=>P===w?null:P)},2200)}},Ce=w=>{ae(),y(w);const R=q();G.current={ownerWindow:R,timeoutId:R.setTimeout(()=>{G.current=null,y(P=>P===w?null:P)},2200)}},He=async()=>{var Z,me,he,Se;const w=((me=(Z=r.current)==null?void 0:Z.getSelection)==null?void 0:me.call(Z))||"",R=((Se=(he=r.current)==null?void 0:he.getVisibleText)==null?void 0:Se.call(he))||"",P=w.trimEnd()||R.trimEnd();if(!P){dt("Nothing to copy");return}if(!await pt(P)){dt("Copy failed");return}dt(w.trimEnd()?"Copied selection":"Copied visible terminal")},Xe=async()=>{if(N)return;p(!0),y("Loading older terminal output..."),le.current=!0;const w=await mt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),(w==null?void 0:w.success)===!1){le.current=!1,y(`Older terminal output unavailable: ${w.error}`);return}v(!0),Ce("Older terminal output loaded"),ue(()=>{var R;(R=r.current)==null||R.bumpResize()})};o.useEffect(()=>{var R,P;if(!te)return;ee&&((R=lt.getState)==null?void 0:R.call(lt,ee))==="connected"&&mt();const w=(P=lt.onStateChange)==null?void 0:P.call(lt,(V,Z)=>{V!==ee||Z!=="connected"||mt()});return()=>{w==null||w()}},[ee,te,r]),o.useEffect(()=>{t&&We()},[t,oe,r]),o.useEffect(()=>{var V,Z;const w=T.current,R=(Z=(V=w==null?void 0:w.ownerDocument)==null?void 0:V.defaultView)==null?void 0:Z.ResizeObserver;if(!w||!R)return;const P=new R(me=>{const he=me[0];if(!he)return;const{width:Se,height:Re}=he.contentRect;b(ke=>{const Ee=Math.round(Se),$e=Math.round(Re);return ke.width===Ee&&ke.height===$e?ke:{width:Ee,height:$e}})});return P.observe(w),()=>P.disconnect()},[]),o.useEffect(()=>{if(U.current)return;const w=Q();!Number.isFinite(w)||w<=0||S(R=>$.current?w<R-ie?w:R:($.current=!0,w))},[B.height,B.width,k.height,k.width]),o.useEffect(()=>{Ne&&Ue()},[Ne,Me,Ae]),o.useEffect(()=>{var P;const w=E.current;if(E.current=c,!c)return;w||v(!1),ye.current&&(ye.current=!1,Ke());const R=re.current;R&&(re.current=null,Ye(R.text,R.seq,R.cols,R.rows,{force:!!R.force})),ee&&te&&((P=lt.getState)==null?void 0:P.call(lt,ee))==="connected"&&mt(),ve.current&&be.current===null&&fe(),ue(()=>{var V;(V=r.current)==null||V.bumpResize()})},[ee,c,te]),o.useEffect(()=>()=>{be.current!==null&&ce(),je(),ae()},[]),o.useEffect(()=>{const w=V=>{var me;const Z=V.detail;Z!=null&&Z.sessionId&&Z.sessionId!==te||m&&((me=r.current)==null||me.bumpResize())},R=q(),P=R===window?[window]:[window,R];for(const V of P)V.addEventListener("adhdev:fit-cli-terminal",w);return()=>{for(const V of P)V.removeEventListener("adhdev:fit-cli-terminal",w)}},[m,te,r]);const ft=m&&g&&!I&&(_.atTop||!_.canScroll)||N||!!x;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:T,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[ft&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Xe()},disabled:!te||N,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:N?"Loading older...":"Load older terminal output"}),x&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:x})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[F&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:F}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{He()},disabled:!m,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{U.current=!0,S(w=>{const R=Math.max(we,Number((w-.1).toFixed(2)));return R>we&&Ue(),R})},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:()=>{U.current=!0,S(w=>{const R=Math.min(D,Number((w+.1).toFixed(2)));return R>we&&Ue(),R})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:A,className:Ne?"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:Ae>0?`${Ae}px`:"100%",height:Me>0?`${Me}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:M},children:s.jsx(Wi,{ref:r,readOnly:!m||!c,sizingMode:"measured",onViewportMetrics:L,onScrollMetrics:H,onInput:w=>{!m||(u==null||u(ee,te,w))}})})})}),!m&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:f})]}),s.jsx(Zi,{contextKey:e.tabKey,panelLabel:at(e),isSending:a,isBusy:!!X,statusMessage:J,onSend:async w=>X?!1:n(w),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const yf=5e3;function vf(e){return e==="disconnected"||e==="reconnecting"}function wf({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=yf}){const i=vf(e),[c,l]=o.useState(()=>!i||a<=0),u=o.useRef(!1);o.useEffect(()=>{if(!i){l(!1);return}if(u.current=!1,a<=0){u.current=!0,l(!0);return}l(!1);const y=setTimeout(()=>{u.current=!0,l(!0)},a);return()=>clearTimeout(y)},[a,i]);const m=i?c:e==="offline"||e==="auth_failed",d=o.useMemo(()=>!t||e!=="connected"?!1:a<=0||u.current,[a,t,e]),h=e==="auth_failed"?"red":e==="offline"?"orange":"accent",f={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},j={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)"},N={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},p="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",x={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[m&&s.jsx("div",{className:p,style:x,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-4 py-3 text-[13px] font-semibold flex items-center gap-2.5 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:f[h],border:j[h],color:N[h]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),n&&e!=="auth_failed"&&s.jsx("button",{type:"button",className:"ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:n,disabled:e==="offline",children:"Reconnect now"})]})}),d&&s.jsx("div",{className:p,style:x,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function jf({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=o.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=o.useState(!1);if(o.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!t||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",u=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!0)};return s.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[l," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:u,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Ea({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(ja,{size:n}):s.jsx(Wt,{size:n})})}const Dt="New session",wc="A connected machine is ready. Start a new session to begin chatting, or open a workspace to launch an IDE, CLI, or ACP session.";function kf({wsStatus:e,isConnected:t,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),i=a.filter(l=>l==="connected").length,c=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&c>0&&i===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:t?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function _o({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Po({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=Qr(e.updatedAt),l=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),i()},children:"Delete"})]})]})}function Sf({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:u,onHideConversation:m,hiddenConversations:d=[],onShowConversation:h,onShowAllHidden:f,onResetPanelsToMain:j,inboxOpen:N,onInboxOpenChange:p,hiddenOpen:x,onHiddenOpenChange:y,onOpenNewSession:g,onOpenDashboardGuide:C,guideNudgeVisible:I=!1,actionShortcuts:v,notifications:M,notificationUnreadCount:S,onOpenNotification:k,onMarkNotificationRead:b,onMarkNotificationUnread:B,onDeleteNotification:L}){const{ides:_,p2pStates:H={}}=os(),F=!!e&&Qe(e)&&!Ve(e),O=!!e&&Ve(e),T=l||(e?ec(e)?"terminal":"chat":null),[A,U]=o.useState(!1),$=o.useRef(null),E=o.useRef(null),z=_.filter(q=>q.type==="adhdev-daemon"),Y=kf({wsStatus:t,isConnected:r,daemonCount:z.length,p2pStates:H}),ve=Y.subtitle,re=Y.tone==="connected"?"#22c55e":Y.tone==="limited"?"#eab308":"#ef4444",ye=Y.tone==="connected"?"0 0 4px #22c55e80":Y.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",le=o.useMemo(()=>M.filter(q=>!q.readAt),[M]),be=o.useMemo(()=>M.filter(q=>!!q.readAt),[M]),ge=o.useMemo(()=>le.slice(0,9),[le]),G=S;o.useEffect(()=>{if(!N)return;const q=ue=>{var ce;(ce=$.current)!=null&&ce.contains(ue.target)||p(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[N,p]),o.useEffect(()=>{if(!x)return;const q=ue=>{var ce;(ce=E.current)!=null&&ce.contains(ue.target)||y(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[x,y]),o.useEffect(()=>{if(!x&&!N)return;const q=ue=>{if(!ue.altKey)return;const ce=ue.code.match(/^Digit([1-9])$/);if(!ce)return;const je=Number(ce[1])-1,ae=x?d[je]:void 0,fe=N?ge[je]:void 0;if(!(!ae&&!fe)){if(ue.preventDefault(),ue.stopPropagation(),ae){h==null||h(ae),y(!1);return}fe&&(k(fe),p(!1))}};return window.addEventListener("keydown",q,!0),()=>window.removeEventListener("keydown",q,!0)},[d,x,N,ge,y,p,k,h]);const ne=q=>{if(!q)return;const ue=n.find(ce=>ce.tabKey===q);ue&&(m==null||m(ue))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Wt,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?at(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:re,boxShadow:ye}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[s.jsx("span",{title:Y.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:re,boxShadow:ye}}),ve&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ve]}),g&&s.jsx("button",{type:"button",onClick:g,className:"btn btn-secondary btn-sm ml-2",title:Dt,"aria-label":Dt,children:s.jsx(Ei,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[C&&s.jsxs("button",{type:"button",onClick:C,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),I&&s.jsx("span",{children:"Guide"})]}),e&&(F||O||!Ve(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:ls(e)||at(e),children:at(e)}),(F||O)&&c&&s.jsxs(s.Fragment,{children:[F&&u&&T&&s.jsx(Ea,{mode:T,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:O?"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})})]}),!Ve(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(wa,{size:14})}),!F&&!Ve(e)&&s.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(St,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:$,children:[s.jsxs("div",{className:`dashboard-header-hidden${A?" is-drop-target":""}`,ref:E,onDragEnter:q=>{q.dataTransfer.types.includes("text/tab-key")&&(q.preventDefault(),U(!0))},onDragOver:q=>{q.dataTransfer.types.includes("text/tab-key")&&(q.preventDefault(),q.dataTransfer.dropEffect="move",U(!0))},onDragLeave:q=>{q.currentTarget.contains(q.relatedTarget)||U(!1)},onDrop:q=>{const ue=q.dataTransfer.getData("text/tab-key");q.preventDefault(),U(!1),ne(ue)},children:[s.jsxs("button",{type:"button",onClick:()=>y(!x),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Pi,{size:16}),d.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),x&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(_o,{value:v==null?void 0:v.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[j&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:j,children:"Reset panels"}),d.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),y(!1)},children:"Restore all"})]})]}),e&&m&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(_o,{value:v==null?void 0:v.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:at(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(q=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(q),y(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:at(q)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(q)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(q)+1]}):null,ls(q)]})]},q.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!N),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Jr,{size:16}),G>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:G})]}),N&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[le.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),le.map(q=>s.jsx(Po,{notification:q,shortcutIndex:ge.indexOf(q)>=0?ge.indexOf(q)+1:void 0,onOpen:()=>k(q),onMarkRead:()=>b(q.id),onMarkUnread:()=>B(q.id),onDelete:()=>L(q.id)},q.id))]}),be.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),be.map(q=>s.jsx(Po,{notification:q,onOpen:()=>k(q),onMarkRead:()=>b(q.id),onMarkUnread:()=>B(q.id),onDelete:()=>L(q.id)},q.id))]}),M.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 Nf(e,t){return String(e||"")!==String(t||"")}function Cf(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),i=!!t.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(u=>String(u||"").toLowerCase()).join(`
|
|
30
|
+
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!qi(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
|
|
31
|
+
`).includes(a)))}function Tf(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const i=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function jc(e,t={}){return Tf(Cf(e,t),t.sortMode||"recent")}function zr(e){return e?"Resume saved history":"Start fresh"}function $a(e){return e?"Resuming saved history…":"Starting fresh…"}function Mf(){return"Start fresh"}function kc(e,t=!1){return e==="cli"?zr(t):e==="ide"?"Start IDE":"Start ACP session"}function Sc(e,t=!1){return e==="cli"?$a(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function If(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Af(){return"Open saved history"}function Lf(){return"Saved History"}function Ba(){return"Use saved history when you want continuity in the same provider conversation."}function Rf(){return"No saved history found yet."}function _f(){return"Refresh saved history"}function Pf(){return"Refreshing saved history…"}function es(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function ts(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Cs(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ts(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Ka(e){return`Resume saved history with ${e}?`}function Oa(){return"Review or change the target workspace before resuming saved history."}function Df(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function Wa({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:m,onNewChat:d,onSwitchSession:h,onRefreshHistory:f,onResumeSavedSession:j}){var k;const N=t.find(b=>b.id===e.routeId),p=(N==null?void 0:N.chats)||[],x=(k=N==null?void 0:N.activeChat)==null?void 0:k.id,y=Qe(e)&&!Ve(e),[g,C]=o.useState(()=>ht()),I=l||g,v=b=>{if(u){u(b);return}C(b)},M=o.useMemo(()=>jc(a,{textQuery:I.textQuery,workspaceQuery:I.workspaceQuery,modelQuery:I.modelQuery,resumableOnly:I.resumableOnly,sortMode:I.sortMode}),[I.modelQuery,I.resumableOnly,I.sortMode,I.textQuery,I.workspaceQuery,a]),S=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:m,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:y?Lf():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:xf(e)}),y&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ba()})]}),s.jsx("button",{onClick:m,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!y&&s.jsx("button",{onClick:d,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),y?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:I.textQuery,onChange:b=>v({...I,textQuery:b.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:I.workspaceQuery,onChange:b=>v({...I,workspaceQuery:b.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:I.modelQuery,onChange:b=>v({...I,modelQuery:b.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:I.sortMode,onChange:b=>v({...I,sortMode:b.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:I.resumableOnly,onChange:b=>v({...I,resumableOnly:b.target.checked})}),"Resume-ready only"]})]}),M.map(b=>{const B=e.providerSessionId===b.providerSessionId,L=B||!b.canResume||!!c;return s.jsxs("button",{type:"button",onClick:()=>{L||!j||j(b)},disabled:L,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${B?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${L?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${B?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:b.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:b.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Df(b.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:b.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[b.workspace||"Workspace unknown",cs(b.summaryMetadata)?` · ${cs(b.summaryMetadata)}`:"",b.messageCount>0?` · ${b.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:B?"ACTIVE":b.canResume?c===b.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},b.id)})]}):p.map(b=>s.jsxs("div",{onClick:()=>{h(e.routeId,b.id),m()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===b.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${x===b.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:b.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[b.id.substring(0,12),"..."]}),x===b.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},b.id)),(y&&!i&&M.length===0||!y&&p.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Wd,{size:32})}),s.jsx("div",{className:"text-[13px]",children:y?a.length>0?"No saved history matches these filters.":Rf():"No recent chat sessions found."})]}),y&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Pf()})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:f,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(nr,{size:13})," ",y?_f():"Refresh History"]})})})]})]});return typeof document>"u"?S:Js.createPortal(S,document.body)}const Do={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Done"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Attention"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Update"}};function Nc({toasts:e,onDismiss:t,onClickToast:r}){return s.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const a=Do[n.type]||Do.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=n.actions)!=null&&i.length||r&&r(n)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(vt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:l=>{l.stopPropagation(),i.onClick(),t(n.id)},children:i.label},c))})]})]},n.id)})})}const Ef=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function $f(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Bf(e){return e.sessionId||e.instanceId||e.agentType}function wn(e,t){return e||t}function Cc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Tt(r,{fallbackId:r.id}));return t}function Tc(e,t={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=t.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Ha(e,t={}){return Kf(e,Tc(e,t))}function Kf(e,t={}){var d,h,f,j,N,p;const r=[],n=t.machineName,a=t.connectionState,i=$f(e),c=_u(e.type,{agentName:e.cliName}),l=Qe(e)||Ve(e)?c:rt(e.type),u=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var y,g;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||rt(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((y=x.activeChat)==null?void 0:y.messages)||[],activeModal:((g=x.activeChat)==null?void 0:g.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,surfaceHidden:x.surfaceHidden}}):[],m=Ef(e);if(m){const x=e.sessionId||e.instanceId,y=c,g=(d=e.activeChat)==null?void 0:d.activeModal,C=g&&Array.isArray(g.buttons)&&g.buttons.length>0,I=bt((h=e.activeChat)==null?void 0:h.status,{activeModal:(f=e.activeChat)==null?void 0:f.activeModal})||bt((N=(j=e.agents)==null?void 0:j[0])==null?void 0:N.status)||"idle",v=e.activeChat||{title:"",messages:[]};let M=v.title&&String(v.title).trim()?String(v.title).trim():"";const S=(p=e.activeChat)==null?void 0:p.id,k=e.chats;if(S&&Array.isArray(k)&&k.length>0){const _=k.find(H=>H.id===S||H.id&&String(H.id)===String(S));_!=null&&_.title&&String(_.title).trim()&&(M=String(_.title).trim())}const b=(Qe(e)||Ve(e),e.type),B=(Qe(e)||Ve(e))&&jo(M,y,b)?"":M,L=v.messages||[];r.push({routeId:e.id,sessionId:x,providerSessionId:e.providerSessionId,nativeSessionId:x,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:Qe(e)?e.mode||"terminal":"chat",agentName:y,agentType:b,status:I,title:B,messages:L,resume:e.resume,hostIdeType:!Qe(e)&&!Ve(e)?e.type:void 0,workspaceName:i,displayPrimary:B||i||(Qe(e)?e.mode==="chat"?y:"Terminal":y),displaySecondary:l,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:C?g.buttons:void 0,modalMessage:C?g.message:void 0,streamSource:"native",tabKey:wn(x,e.id),machineName:n,connectionState:a})}if(m&&(Qe(e)||Ve(e)))return r;for(const x of u){const y=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,g=Pu(x),C=Bf(x),I=`${e.id}:${C}`,v=x.title&&String(x.title).trim()||"",M=jo(v,x.agentName,x.agentType)?"":v,S=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||S.length>0||y||M||!["idle","panel_hidden","disconnected","not_monitored"].includes(g))&&r.push({routeId:e.id,sessionId:x.sessionId||x.instanceId,providerSessionId:x.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:x.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:x.sessionCapabilities,mode:"chat",agentName:x.agentName,agentType:x.agentType,status:g,title:M,messages:S,hostIdeType:e.type,workspaceName:i,displayPrimary:M||i||x.agentName||l,displaySecondary:`${l} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,modalButtons:y?x.activeModal.buttons:void 0,modalMessage:y?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:wn(x.sessionId||x.instanceId,I),machineName:n,connectionState:a})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:i,displayPrimary:i||l,displaySecondary:l,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:wn(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function Of(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function Mc(e,t){const r=Of(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Ic=[{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"trae",name:"Trae",icon:"🔮"},{id:"vscode",name:"VS Code",icon:"💙"},{id:"vscodium",name:"VSCodium",icon:"💚"},{id:"windsurf",name:"Windsurf",icon:"🏄"}],Ac=[{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],Lc=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"claude-code-vscode",name:"Claude Code (VS Code)",icon:"🟠"}],Wf=Ic,Hf=Ac,Ff=Lc;function ds(...e){return td(sd(e))}function Uf({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:ds("dashboard-header",i),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function Rc({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Uf,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ds("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const la="adhdev:themechange";function zf(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function hs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function xs(e){return e==="system"?zf():e}function _c(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Ir(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(la,{detail:{preference:e,theme:t}}))}function Vf(){const e=hs(),t=xs(e);_c(t),Ir(e,t)}function Fa(){const[e,t]=o.useState(hs),[r,n]=o.useState(()=>xs(hs()));o.useEffect(()=>{_c(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const m=u.matches?"light":"dark";n(m),Ir("system",m)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const m=u.detail||{},d=m.preference,h=m.theme;t(d==="dark"||d==="light"||d==="system"?d:hs()),n(h==="dark"||h==="light"?h:xs(hs()))},l=u=>{if(u.key!=="theme")return;const m=hs(),d=xs(m);t(m),n(d)};return window.addEventListener(la,c),window.addEventListener("storage",l),()=>{window.removeEventListener(la,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=xs(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Ir(c,l)},[]),i=o.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=xs(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Ir(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const Eo={dark:"Dark",light:"Light",system:"System"};function Gf({collapsed:e}){const{preference:t,cycleTheme:r}=Fa(),n=t==="dark"?s.jsx(Fd,{size:16}):t==="light"?s.jsx(Hd,{size:16}):s.jsx(Ud,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Eo[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Eo[t]})]})}function jn(e,t){return e?typeof e=="function"?e(t):e:null}function qf({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:u="sidebar-collapsed"}){const[m,d]=o.useState(!1),[h,f]=o.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),j=()=>d(!0),N=()=>d(!1),p=()=>{f(C=>{const I=!C;try{localStorage.setItem(u,I?"1":"0")}catch{}return I})},x=o.useMemo(()=>({collapsed:h,mobileMenuOpen:m,openMobileMenu:j,closeMobileMenu:N,toggleCollapsed:p}),[h,m]),y=C=>`nav-item${C.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${C.className?` ${C.className}`:""}`,g=C=>s.jsxs("div",{className:y(C),id:`nav-${C.id}`,onClick:()=>{C.onSelect(),N()},title:h?C.title??(typeof C.label=="string"?C.label:void 0):C.title,children:[s.jsx("span",{className:"nav-icon",children:C.icon}),!h&&C.label]},C.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:j,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),m&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:N,onKeyDown:C=>C.key==="Escape"&&N()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:jn(t,x)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:N,children:s.jsx(vt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(g)}),n.map(C=>s.jsxs("div",{className:C.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&C.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:C.title}):null,C.items.map(g)]},C.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(g),jn(i,x),s.jsx(Gf,{collapsed:h}),jn(c,x)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function kt({title:e,icon:t,description:r,accentColor:n,className:a,children:i}){return s.jsxs("div",{className:ds("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function Pc({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ds("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Yf={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"},Xf={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function gr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ds("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Yf[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Xf[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 Jf={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 Zf({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ds("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Jf[e],r),children:[s.jsx("span",{className:ds("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Qf[e])}),n]})}function Xt({label:e,description:t,checked:r,disabled:n,onChange:a,extra:i}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,s.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function ep({onPrefChange:e}){const[t,r]=Uu(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>i("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(St,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>i("browserNotifications",c)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{Ji().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vd,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(er,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function Vr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function tp(e,t){const r=Vr(e),n=Vr(t);if(!r||!n)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function Dc(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function qs(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||tp(r,t)>=0)return!1;const n=Vr(r),a=Vr(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function sp(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function kn(e,t){return e instanceof Error?e.message:t}function rp({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(ap,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function $o({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return Js.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:i,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function np(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Wf,...Hf,...Ff].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 ap({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var F,O;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[m,d]=o.useState(null),[h,f]=o.useState("idle"),[j,N]=o.useState(""),p=e.version||null,x=((F=e.machine)==null?void 0:F.platform)||((O=e.system)==null?void 0:O.platform)||"",y=Tt(e,{fallbackId:e.id}),g=x==="win32"?"🪟":x==="darwin"?"🍎":"🐧",C=t.filter(T=>T.daemonId===e.id&&T.transport==="cdp-page"),I=t.filter(T=>T.daemonId===e.id&&T.transport==="pty"),v=t.filter(T=>T.daemonId===e.id&&T.transport==="acp"),M=e.p2p,S=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const T=sp(await r(e.id,"daemon_upgrade",{}));T.alreadyLatest?(c("done"),u(`Already on v${T.version||"latest"}.`)):T.upgraded||T.success?(c("done"),u(`Upgrade to v${T.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(T.error||"Upgrade failed"))}catch(T){c("error"),u(kn(T,"Connection lost during upgrade"))}}},k=async()=>{if(d(null),!!n){f("loading");try{await n(e.id),f("done"),N("Machine disconnected.")}catch(T){f("error"),N(kn(T,"Failed to disconnect"))}}},b=async()=>{if(d(null),!!a){f("loading");try{await a(e.id),f("done"),N("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(T){f("error"),N(kn(T,"Failed to revoke token"))}}},B="0.9.46",L=Dc(e,B),_=qs(e,B),H=C.length+I.length+v.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:g}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:y}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),p&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!L&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&L&&s.jsx("button",{onClick:S,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${B}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${_?"↑ Update now":`↑ Update${` to v${B}`}`}`}),n&&s.jsx("button",{onClick:()=>d("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>d("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Zf,{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:[M&&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 ${M.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${M.state==="connecting"||M.state==="new"?"animate-pulse":""}`,style:M.state==="connecting"||M.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",M.state==="connected"?"connected":M.state==="connecting"||M.state==="new"?"connecting...":M.state||"off"]}),M.peers!==void 0&&M.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",M.peers," peer",M.peers!==1?"s":"",")"]})]}),M&&H>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),H>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(T=>{const A=np(T.type),U=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:A.icon}),s.jsx("span",{children:A.name}),U!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${U?"bg-green-400":"animate-pulse"}`,style:U?void 0:{background:"var(--status-warning)"},title:U?"CDP connected":"CDP connecting..."})]},T.id)}),I.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)),v.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||j)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-red-400":i==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:j||l})]}),m==="disconnect"&&s.jsx($o,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
|
|
32
32
|
|
|
33
33
|
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
34
34
|
|
|
35
|
-
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:k,onCancel:()=>d(null)}),m==="revoke"&&s.jsx(
|
|
35
|
+
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:k,onCancel:()=>d(null)}),m==="revoke"&&s.jsx($o,{title:"⚠️ Remove Machine",message:`Remove "${y}" from your dashboard?
|
|
36
36
|
|
|
37
37
|
This will:
|
|
38
38
|
• Immediately disconnect the machine
|
|
39
39
|
• Delete the machine registration
|
|
40
40
|
• Require restarting ADHDev on that machine
|
|
41
41
|
|
|
42
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:b,onCancel:()=>d(null)})]})}const cp=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function lp(){const{preference:e,setPreference:t}=Fa();return s.jsx("div",{className:"flex gap-2",children:cp.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 dp(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 up(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Sn(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Ko(e){const{r:t,g:r,b:n}=up(e);return .2126*Sn(t)+.7152*Sn(r)+.0722*Sn(n)}function Oo(e,t){const r=Ko(e),n=Ko(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function $c(e){const t=dp(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Oo(t,r)>=Oo(t,n)?r:n}const da={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},ua={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},mp=[{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"}}}],Bc="adhdev-chat-theme",Kc="adhdev-chat-theme-custom";function Ar(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Bc)||"ember"}catch{return"ember"}}function Rt(e){try{const t=localStorage.getItem(Kc);if(t){const r=JSON.parse(t);return{...e==="dark"?da:ua,...r[e]}}}catch{}return e==="dark"?da:ua}function yr(e,t){try{localStorage.setItem(Kc,JSON.stringify({dark:e,light:t}))}catch{}}function Nt(e,t){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${t})`}function Gr(e,t){const r=Math.min(255,parseInt(e.slice(1,3),16)+t),n=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const fp={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Ys(e,t){var a;const r=(a=fp[e])==null?void 0:a[t];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Gr(r,24)),n.style.setProperty("--accent-on-primary",$c(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Gr(r,18)})`),n.style.setProperty("--border-accent",Nt(r,.35)),n.style.setProperty("--nav-active-bg",Nt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Nt(r,.06)}`)}function ss(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Nt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Nt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Nt(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",Nt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Nt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Gr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",$c(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Gr(e.accentColor,40)})`),t.style.setProperty("--border-accent",Nt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Nt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Nt(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${Nt(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function Ua(){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 pp(e){try{localStorage.setItem(Bc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=rs()?"dark":"light";ss(Rt(t))}else Ua(),Ys(e,rs()?"dark":"light")}function hp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Ar();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=rs()?"dark":"light";ss(Rt(t))}else Ua(),Ys(e,rs()?"dark":"light")}function rs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function xt({label:e,value:t,onChange:r}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Bs({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function xp({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=o.useState(()=>Rt(r));o.useEffect(()=>{a(Rt(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const m={...u,[c]:l},h=Rt(r==="dark"?"light":"dark");return r==="dark"?yr(m,h):yr(h,m),ss(m),t(m),m})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",s.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(Bs,{title:"App Background",children:[s.jsx(xt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(xt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(xt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Bs,{title:"App Text",children:[s.jsx(xt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(xt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(xt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Bs,{title:"Borders & Accent",children:[s.jsx(xt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(xt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(xt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Bs,{title:"Chat Bubbles",children:[s.jsx(xt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(xt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(xt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(xt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Bs,{title:"Chat Layout",children:[s.jsx(xt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(xt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(xt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?da:ua,u=Rt(e?"light":"dark");e?yr(c,u):yr(u,c),a(c),ss(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function bp(){const[e,t]=o.useState(Ar),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Rt("dark"));o.useEffect(()=>{n(rs());const u=new MutationObserver(()=>{const h=rs();n(h);const f=Ar();f==="custom"?ss(Rt(h?"dark":"light")):Ys(f,h?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const h=rs();n(h);const f=Ar();f==="custom"?ss(Rt(h?"dark":"light")):Ys(f,h?"dark":"light")};return m.addEventListener("change",d),()=>{u.disconnect(),m.removeEventListener("change",d)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ss(Rt(r?"dark":"light")):(Ua(),Ys(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Rt(r?"dark":"light"))},[r]);const c=u=>{t(u),pp(u)},l=[...mp,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const m=e===u.id,d=r?u.preview.dark:u.preview.light,h=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:d.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.userBubble,color:h},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[m&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&s.jsx(xp,{dark:r,onColorsChange:u=>i(u)})]})}const za="adhdev_mobileDashboardMode_v1",ma="adhdev:mobile-dashboard-mode-change";function Va(){try{return localStorage.getItem(za)==="workspace"?"workspace":"chat"}catch{return"chat"}}function gp(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Va())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==za||t()};return window.addEventListener(ma,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ma,r),window.removeEventListener("storage",n)}}function yp(e){try{localStorage.setItem(za,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ma,{detail:e}))}function vp(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(Va()==="chat")},[]),s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Wt,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{t(r),yp(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Nn=new Map,Wo=new Map;function wp(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 jp(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 Oc(){const{sendCommand:e}=wt(),{injectEntries:t,getIdes:r}=Qs();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??_m,c=Wo.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=Nn.get(n);if(l)return l;const u=(async()=>{const m=await e(n,"get_machine_runtime_stats"),d=wp(m);if(!d)return;const h=r().find(j=>j.id===n),f=jp(h,n,d.machine,d.timestamp||Date.now());t([f]),Wo.set(n,Date.now())})().finally(()=>{Nn.delete(n)});return Nn.set(n,u),u},[r,t,e])}function kp(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 Sp(e,t){const{sendData:r}=wt(),{injectEntries:n,getIdes:a}=Qs(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>Vt.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const h=a().find(j=>j.id===u),f=kp(h,u,d);n([f])}));return()=>{l.forEach(u=>u())}},[i,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function Np(e,t){const{sendData:r}=wt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(t!=null&&t.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const u=Vt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},m=>{l&&(clearTimeout(l),l=null),a(m.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},$m):c(!1),()=>{l&&clearTimeout(l),u()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:a}}function Cp(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Wc(e){const{sendData:t}=wt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=Cp(e);if(!a||!e.sessionId||!t){n({});return}const i=Vt.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),js.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return i.initialSendAccepted||n({}),()=>{i()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const Hc="adhdev_hiddenTabs";function Mp(){try{const e=localStorage.getItem(Hc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function fs(e){try{localStorage.setItem(Hc,JSON.stringify([...e]))}catch{}}function Cn(e){return La(e)}function Ga(e,t){return vs(t).some(r=>e.has(r))}function Tp(){const[e,t]=o.useState(Mp),r=o.useCallback(m=>{const d=Cn(m);t(h=>{const f=new Set(h);return f.has(d)?f.delete(d):f.add(d),fs(f),f})},[]),n=o.useCallback(m=>{const d=Cn(m);t(h=>{if(h.has(d))return h;const f=new Set(h);return f.add(d),fs(f),f})},[]),a=o.useCallback(m=>{const d=Cn(m);t(h=>{if(!h.has(d))return h;const f=new Set(h);return f.delete(d),fs(f),f})},[]),i=o.useCallback(()=>{t(m=>{if(m.size===0)return m;const d=new Set;return fs(d),d})},[]),c=o.useCallback((m,d)=>{t(h=>{const f=new Set(h);for(const j of d)f.add(j);return fs(f),f})},[]),l=o.useCallback((m,d)=>{t(h=>{const f=new Set(h);for(const j of d)f.delete(j);return fs(f),f})},[]),u=o.useCallback(m=>Ga(e,m),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Fc(e){return e instanceof Error?e.message:String(e||"")}function Uc(e){const t=Fc(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 zc(e){const t=Fc(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Vc({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Qe(e)||Ve(e))return;const i=Ls(e);if(i===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(ms(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:$t(e),mode:t})}catch(l){const u=zc(l);c&&!u&&a(m=>{const d={...m};return i===Gc(r,c)?delete d[c]:d[c]=i,d}),Uc(l)?console.warn(u?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function 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 Ip(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(u=>Ho(u,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Gc(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 Ap(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))Gc(t,a)===i&&(delete n[a],r=!0);return r?n:e}function Lp({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Qi()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:vc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Yu(a),o.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),m={};for(const[d,h]of Object.entries(l))u-h<5e3&&(m[d]=h);return Object.keys(m).length===Object.keys(l).length?l:m})},5500);return()=>clearTimeout(c)},[t,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(m=>m.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function Rp(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 Mn(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 _p(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?_p(ks(r.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((r==null?void 0:r.id)||""),String((r==null?void 0:r.index)??""),String((r==null?void 0:r.receivedAt)??(r==null?void 0:r.timestamp)??""),n].join(":")}function Pp(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 Dp(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 Ep(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const i of vs({routeId:n.routeId}))r.set(i,a);for(const i of vs({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of vs({tabKey:n.tabKey}))r.set(i,n)}return r}function $p(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Bp(e){const t=$p(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const r=String(t.role||""),n=ks(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Kp({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>Rp(e),[e]),i=o.useMemo(()=>Mc(e),[e]),c=o.useRef([]),l=o.useRef([]),u=o.useRef([]),m=o.useRef(new Map),d=o.useRef(new Map),h=o.useMemo(()=>{const I=new Map,v=[];for(const b of a){const{connectionState:B="new",machineName:L}=Tc(b,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),_=Pp(b),H=m.current.get(b.id);if(H&&H.ide===b&&H.sourceSignature===_&&H.connectionState===B&&H.machineName===L){I.set(b.id,H),v.push(...H.conversations);continue}const F=Ha(b,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),O={ide:b,sourceSignature:_,connectionState:B,machineName:L,conversations:F};I.set(b.id,O),v.push(...F)}m.current=I;const T=new Map,S=b=>{const B=Bp(b),L=d.current.get(b.tabKey);if(L&&L.signature===B)return T.set(b.tabKey,L),L.timestamp;const _={signature:B,timestamp:cc(b)||(L==null?void 0:L.timestamp)||0};return T.set(b.tabKey,_),_.timestamp},k=[...v].sort((b,B)=>lc(b,B,S));return d.current=T,k},[a,t,i]),f=o.useMemo(()=>{const I=Dp(h,r);return Mn(c.current,I)?c.current:(c.current=I,I)},[h,r]),j=o.useMemo(()=>{const I=new Map,v=Array.from(new Set(f.map(T=>T.routeId)));for(const T of v){const S=_t(f,T);S&&I.set(T,S)}return I},[f]),N=o.useMemo(()=>{const I=new Map;for(const v of f){const T=j.get(v.routeId),S=v.streamSource==="native"&&T?T:v;for(const k of vs({providerSessionId:v.providerSessionId,sessionId:v.sessionId}))I.set(k,S)}return I},[f,j]),p=o.useMemo(()=>Ep(f,j),[f,j]),x=o.useCallback(I=>{if(I)return N.get(I)},[N]),y=o.useCallback(I=>{if(I)return p.get(I)},[p]),g=o.useMemo(()=>{const I=f.filter(v=>!Ga(n,v));return Mn(l.current,I)?l.current:(l.current=I,I)},[f,n]),C=o.useMemo(()=>{const I=g.map(v=>v.tabKey);return Mn(u.current,I)?u.current:(u.current=I,I)},[g]);return{chatIdes:a,conversations:f,visibleConversations:g,visibleTabKeys:C,resolveConversationBySessionId:x,resolveConversationByTarget:y}}function Op({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),i=o.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=o.useCallback(()=>{t&&n(l=>{const u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Wp({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{it.setIdes(e)},[e]),o.useEffect(()=>{it.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),o.useEffect(()=>{const a=it.onToast(i=>{r(l=>l.some(m=>m.message===i.message&&i.timestamp-m.timestamp<3e3)?l:[...l.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions}]);const c=i.duration||5e3;setTimeout(()=>r(l=>l.filter(u=>u.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=bc.on("status_event",i=>{it.handleRawEvent(i,"ws")});return()=>{a()}},[]),o.useEffect(()=>{var i;const a=c=>{var p;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const u=l.targetSessionId||l.targetKey||l.daemonId,m=n(u),d=(m==null?void 0:m.routeId)||l.daemonId;if(!d)return;const h=Number(l.buttonIndex),f=l.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[h])||"Approve",j=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(j);t(d,"resolve_action",{action:N?"approve":"reject",button:f,...Number.isFinite(h)&&{buttonIndex:h},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};return(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,t])}const Hp="adhdev_dashboardLayout_v1",Fp="adhdev_dashboardDockview_v1",Up="adhdev_dashboardDockviewHiddenRestore_v1",Ks={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function qa(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function zp(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function qc(e){return`${Hp}:${e}`}function Vp(e){const t=qc(e);return qa(t,null)}function Gp(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=qc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Yc(e){return`${Fp}:${e}`}function qp(e){const t=Yc(e);return qa(t,null)}function Yp(e,t){try{const r=Yc(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Xc(e){return`${Up}:${e}`}function Xp(e){const t=Xc(e);return qa(t,{})}function Jp(e,t){try{const r=Xc(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Qp(){return{groupAssignments:[...Ks.groupAssignments],focusedGroup:Ks.focusedGroup,groupActiveTabIds:{...Ks.groupActiveTabIds},groupTabOrders:{...Ks.groupTabOrders},groupSizes:[...Ks.groupSizes]}}function Zp(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function eh(){const[e]=o.useState(()=>zp(typeof window<"u"?window.innerWidth:1280)),[t,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[m,d]=o.useState([]),[h,f]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[j,N]=o.useState(!1),p=o.useCallback(()=>{if(j)return;const b=Vp(e)??Qp();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),u(b.groupTabOrders),d(b.groupSizes),N(!0)},[j,e]);o.useEffect(()=>{j&&Gp(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:m})},[j,e,t,n,i,l,m]),o.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),B=L=>f(L.matches);return b.addEventListener("change",B),()=>b.removeEventListener("change",B)},[]);const x=o.useCallback(b=>{r(b)},[]),y=o.useCallback(b=>{a(b)},[]),g=o.useCallback(b=>{c(b)},[]),C=o.useCallback(b=>{u(b)},[]),I=o.useCallback(b=>{d(b)},[]),v=o.useCallback(b=>{y(b)},[y]),T=o.useCallback((b,B)=>{c(L=>(L[b]??null)===(B??null)?L:{...L,[b]:B})},[]),S=o.useCallback((b,B)=>{u(L=>{const _=L[b];return Zp(_,B)?L:{...L,[b]:B}})},[]),k=o.useCallback((b,B)=>{const L=B.get(b)??0;return T(L,b),v(L),L},[v,T]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:n,updateFocusedGroup:y,focusGroup:v,groupActiveTabIds:i,updateGroupActiveTabIds:g,setGroupActiveTab:T,groupTabOrders:l,updateGroupTabOrders:C,setGroupTabOrder:S,groupSizes:m,updateGroupSizes:I,isMobile:h,hasHydratedStoredLayout:j,hydrateStoredLayout:p,focusConversationTab:k}}function th(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Aa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function sh({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:u,activeConv:m,isRefreshingHistory:d,ides:h,handleRefreshHistory:f}){const j=o.useRef(!1),N=o.useRef(!1),p=o.useRef(null),x=o.useRef(!1);o.useEffect(()=>{if(!e||j.current||t.length===0)return;if(!a){i();return}const y=r(e);y&&(c(y.tabKey,n),j.current=!0,N.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(g=>{const C=new URLSearchParams(g);return C.delete("activeTab"),C},{replace:!0}))},[e,t,r,n,a,i,c,l]),o.useEffect(()=>{if(!(N.current||a)&&t.length!==0){if(!e){i(),N.current=!0;return}if(j.current){N.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(N.current||a)&&(i(),N.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,i]),o.useEffect(()=>{if(!u){x.current=!1;return}if(!m||x.current||d)return;const y=h.find(g=>g.id===m.routeId);y&&(!y.chats||y.chats.length===0||th(y.chats,m))&&(x.current=!0,f())},[u,m,d,h,f])}function Tn(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=Aa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Jc({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[u,m]=o.useState(!1),d=o.useCallback(async N=>{try{await e("standalone","launch_ide",{ideType:N,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=o.useCallback(async(N,p)=>{try{const x=N||(t==null?void 0:t.daemonId)||"",y=await e(x,"switch_chat",{id:p,sessionId:p,...ws(t)}),g=y==null?void 0:y.result;if((y==null?void 0:y.success)===!0||g==="switched"||g==="switched-by-title")return;g===!1||g==="not_found"?$s(a,"⚠️ Session tab not found — try refreshing history"):typeof g=="string"&&g.startsWith("error:")?$s(a,`⚠️ Switch error: ${g}`):$s(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),$s(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,a]),f=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const N=sr(t);await e(N,"new_chat",{...ws(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(N){console.error("New chat failed",N)}finally{l(!1)}}},[t,c,e,i]),j=o.useCallback(async()=>{var N,p;if(!(!t||u)){m(!0);try{const x=sr(t),y=async()=>e(x,"list_chats",{forceExpand:!0,...ws(t)});let g=await y(),C=(g==null?void 0:g.chats)||((N=g==null?void 0:g.result)==null?void 0:N.chats);Tn(C,t)&&(await new Promise(I=>setTimeout(I,450)),g=await y(),C=(g==null?void 0:g.chats)||((p=g==null?void 0:g.result)==null?void 0:p.chats)),g!=null&&g.success&&Array.isArray(C)&&(n(t.routeId,C),Tn(C,t)&&!Tn(r,t)&&$s(a,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{m(!1)}}},[t,r,u,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:h,handleNewChat:f,handleRefreshHistory:j}}function rh(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 nh(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 u=a[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function 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 ah(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 oh(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 ih({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:m}){const d=o.useRef(null),h=o.useMemo(()=>vr(e,m),[e,m]),f=h.assignments,j=o.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),N=j>1,p=o.useCallback((v,T)=>{t(S=>{const k=new Map(vr(S,m).assignments);return T===0?k.delete(v):k.set(v,T),k}),n(S=>({...S,[T]:v})),r(T)},[t,m,n,r]),x=o.useCallback(v=>{t(T=>{const S=vr(T,m).assignments,k=new Map;for(const[b,B]of S)B!==v&&(B>v?k.set(b,B-1):k.set(b,B));return k}),c(T=>{if(T.length<=1)return[];const S=[...T];S.splice(v,1);const k=S.reduce((b,B)=>b+B,0);return k>0?S.map(b=>b/k*100):[]}),r(0)},[t,m,c,r]),y=o.useCallback((v,T)=>{T.preventDefault();const S=d.current;if(!S)return;const k=T.clientX,b=S.offsetWidth,B=i.length===j?[...i]:Go(j),L=H=>{const O=(H.clientX-k)/b*100,M=[...B];M[v]=Math.max(15,B[v]+O),M[v+1]=Math.max(15,B[v+1]-O),c(M)},_=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",_),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",_)},[i,j,c]),g=o.useCallback((v,T,S)=>{if(j>=4)return;const k=S==="left"?T:T+1;t(b=>{const B=vr(b,m).assignments,L=new Map;for(const _ of u){const H=B.get(_.tabKey)??0,F=H>=k?H+1:H;F>0&&L.set(_.tabKey,F)}return k>0&&L.set(v,k),L}),c(b=>{const B=b.length===j?[...b]:Go(j),L=B[T]??100/j,_=Math.max(15,L/2),H=Math.max(15,L/2),F=[...B];F[T]=_,F.splice(k,0,H);const O=F.reduce((M,A)=>M+A,0);return F.map(M=>M/O*100)}),n(b=>{const B=Vo(b,k);return B[k]=v,B}),a(b=>{const B=Vo(b,k);return B[k]=[v],B}),r(k)},[j,t,m,u,c,n,a,r]);o.useEffect(()=>{rh(e,f)||t(f)},[e,f,t]),o.useEffect(()=>{const{mapping:v,usedGroups:T}=h;n(S=>{const k=zo(S,v);return Uo(S,k)?S:k}),a(S=>{const k=zo(S,v);return Uo(S,k)?S:k}),r(S=>{const k=l?0:ah(S,T,v);return S===k?S:k}),c(S=>{const k=l?[]:oh(S,T,h.groupCount);return nh(S,k)?S:k})},[h,l,n,a,r,c]);const C=o.useMemo(()=>{const v=Array.from({length:j},()=>[]);for(const T of u){const S=f.get(T.tabKey)??0,k=Math.min(S,j-1);v[k].push(T)}return v},[u,f,j]),I=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:d,normalizedGroupAssignments:f,numGroups:j,isSplitMode:N,groupedConvs:C,moveTabToGroup:p,closeGroup:x,handleResizeStart:y,splitTabRelative:g,clearAllSplits:I}}function ch({ides:e,sendDaemonCommand:t}){const r="0.9.44",n=o.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:Ec(d,r)).sort((d,h)=>Number(qs(h,r))-Number(qs(d,r))),[r,e]),a=o.useMemo(()=>n.some(d=>qs(d,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),m=o.useCallback(async d=>{var h,f;u(j=>({...j,[d]:"upgrading"}));try{const j=await t(d,"daemon_upgrade",{});(h=j==null?void 0:j.result)!=null&&h.upgraded||(f=j==null?void 0:j.result)!=null&&f.success?u(N=>({...N,[d]:"done"})):u(N=>({...N,[d]:"error"}))}catch{u(j=>({...j,[d]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:m}}const Qc=80;function Lr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function lh(e){return{...e,createdAt:Lr(e.createdAt),updatedAt:Lr(e.updatedAt,e.createdAt),lastEventAt:Lr(e.lastEventAt,e.updatedAt||e.createdAt)}}function dh(e){const t=La(e);return t==="unknown:"?e.id:t}function uh(e){return[e.type,ic(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function mh(e,t=Qc){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=dh(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 fh(e,t){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?t.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=Zr(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const u=Lr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),m=uh({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(lh({id:m,dedupKey:m,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:rc(a),preview:ym(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return mh(n)}function ph(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function hh(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Qc}=e,a=o.useMemo(()=>fh(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>ph(a),[a]);return{notifications:a,unreadCount:i}}function xh({notifications:e,sendDaemonCommand:t}){const r=o.useCallback(i=>{const c=e.find(u=>u.id===i),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,t]),n=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}function rn(...e){const t=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();t.has(c)||(t.add(c),r.push(i))};for(const a of e){if(Array.isArray(a)){for(const i of a)n(i);continue}n(a)}return r}function bh(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const r=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function nn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=bh(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 gh(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 yh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function an(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=yh(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.includes("\\")?"\\":"/",l=(m,d)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${d}`:m==="/"||m==="\\"?`${c}${d}`:`${m.replace(/[\\/]+$/,"")}${c}${d}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:typeof(m==null?void 0:m.path)=="string"&&m.path.trim()?m.path:l(i,m.name)})).sort((m,d)=>m.name.localeCompare(d.name)):[];return{path:i,directories:u}}function vh(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 wh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function jh({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(m=>{var N,p,x,y;if(!m||m.type==="adhdev-daemon"||vh(m.daemonId||m.id)!==n.machineId||(tr(m)?"cli":gs(m)?"acp":"ide")!==n.kind||String(m.agentType||m.type||"")!==n.providerType)return!1;if(n.resumeSessionId)return String(m.providerSessionId||"")===n.resumeSessionId;if(c){const g=qo(m.workspace||m.runtimeWorkspaceLabel);return g?g===c:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((y=(x=(p=(N=m.activeChat)==null?void 0:N.messages)==null?void 0:p.at)==null?void 0:x.call(p,-1))==null?void 0:y.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const u=dc({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});u&&(a(null),r(u))},[t,e,r,n]),o.useEffect(()=>{if(!n)return;const c=window.setTimeout(()=>{a(l=>!l||l.startedAt!==n.startedAt?l:null)},45e3);return()=>window.clearTimeout(c)},[n]),{trackPendingLaunch:i}}function kh({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=o.useCallback(async(f,j)=>an(e,f,j),[e]),l=o.useCallback(async(f,j)=>{if(!j.trim())return{ok:!1,error:"Choose a workspace path first."};try{const N=await e(f,"workspace_add",{path:j.trim()});return N!=null&&N.success?{ok:!0}:{ok:!1,error:(N==null?void 0:N.error)||"Could not save workspace"}}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not save workspace"}}},[e]),u=o.useCallback(async(f,j,N)=>{var p;try{const x={ideType:j,enableCdp:!0};(p=N==null?void 0:N.workspacePath)!=null&&p.trim()&&(x.workspace=N.workspacePath.trim());const y=await e(f,"launch_ide",x);return!(y!=null&&y.success)&&(y==null?void 0:y.success)!==void 0?{ok:!1,error:(y==null?void 0:y.error)||"Could not launch IDE"}:(t({machineId:f,kind:"ide",providerType:j,workspacePath:(N==null?void 0:N.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Could not launch IDE"}}},[e,t]),m=o.useCallback(async(f,j,N,p)=>{var y,g,C;const x=Date.now();try{const I={cliType:N};(y=p==null?void 0:p.workspacePath)!=null&&y.trim()?I.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(I.workspaceId=p.workspaceId),(g=p==null?void 0:p.resumeSessionId)!=null&&g.trim()&&(I.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(I.cliArgs=p.cliArgs),(C=p==null?void 0:p.initialModel)!=null&&C.trim()&&(I.initialModel=p.initialModel.trim());const v=await e(f,"launch_cli",I),T=(v==null?void 0:v.result)||v,S=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);return v!=null&&v.success&&S?(r(S),{ok:!0}):v!=null&&v.success?(t({machineId:f,kind:j,providerType:N,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:x}),{ok:!0}):{ok:!1,error:(v==null?void 0:v.error)||(T==null?void 0:T.error)||`Could not launch ${j.toUpperCase()} session`}}catch(I){return wh(I)?(t({machineId:f,kind:j,providerType:N,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:x}),{ok:!0}):{ok:!1,error:I instanceof Error?I.message:`Could not launch ${j.toUpperCase()} session`}}},[r,e,t]),d=o.useCallback(async(f,j)=>{if(!f||!j)return[];try{const N=await e(f,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),p=(N==null?void 0:N.result)??N;return Array.isArray(p==null?void 0:p.sessions)?p.sessions:[]}catch(N){return console.error("List saved sessions failed",N),[]}},[e]),h=o.useCallback(async f=>{await Vc({conversation:n,mode:f,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:i})},[n,a,e,i]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineSavedSessions:d,setActiveCliViewMode:h}}function Sh(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":return!0;case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function Nh(e,t,r=Date.now()){return!e||!Sh(t)?null:{tabKey:e,nonce:r}}function Ch({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,u]=o.useState(null),[m,d]=o.useState(null),h=o.useMemo(()=>{var x,y;if(!e){if(l){const g=t.find(C=>C.tabKey===l);if(g)return g}return r[0]}const p=n[a];if(p){const g=t.find(C=>C.tabKey===p);if(g)return g}return((x=i[a])==null?void 0:x[0])||((y=i[0])==null?void 0:y[0])},[t,l,a,n,i,e,r]),f=o.useCallback(p=>{u(p)},[]),j=o.useCallback(p=>{u(p.tabKey),c(x=>{const y=new URLSearchParams(x),g=wm(p);return g?y.set("activeTab",g):y.delete("activeTab"),y},{replace:!0})},[c]),N=o.useCallback((p,x)=>{const y=Nh(p,x);y&&d(y)},[]);return{activeConv:h,openDesktopConversation:j,requestScrollToBottom:N,scrollToBottomRequest:m,setDesktopActiveTab:f}}function Mh(e){const t=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:r===e.autoReadKey?r:null}:r===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:r}:{shouldSchedule:!0,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!r,nextPendingKey:null}}function Th(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&t&&t!==r),autoReadKey:i,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Ih({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=o.useRef(null),i=o.useRef(null),c=o.useRef(null),l=o.useRef(null),u=o.useRef(null);o.useEffect(()=>{const m=()=>{c.current&&(clearTimeout(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null),i.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const d=Or(e,r),h=Th({tabKey:e.tabKey,historySessionId:or(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Qt(e),liveState:d}),f=h.autoReadKey,j=Mh({autoReadKey:f,shouldMarkSeen:h.shouldMarkSeen,completedKey:a.current,pendingKey:i.current});if(!h.shouldMarkSeen){j.shouldCancelPending&&m(),a.current=f;return}if(!j.shouldSchedule)return;j.shouldCancelPending&&m();const N=()=>{if(document.visibilityState!=="visible"||a.current===f)return;a.current=f,i.current=null,c.current=null,l.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null);const x=h.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:x,completionMarker:h.completionMarker}).catch(()=>{})};if(i.current=j.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(N,1500);const x=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};u.current=x,document.addEventListener("visibilitychange",x);return}const p=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(N,800),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null))};u.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),o.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function Ah({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:u}){var M;const[m,d]=o.useState(!1),[h,f]=o.useState([]),[j,N]=o.useState(()=>ht()),[p,x]=o.useState(!1),[y,g]=o.useState(null),C=o.useRef(null),I=o.useMemo(()=>r||t||e,[e,r,t]),v=!!I&&Qe(I)&&!Ve(I),T=o.useMemo(()=>{if(!I||!v)return null;const A=I.daemonId||I.routeId||"",U=$t(I);return`${A}:${U}`},[I,v]),{isCreatingChat:S,isRefreshingHistory:k,handleSwitchSession:b,handleNewChat:B,handleRefreshHistory:L}=Jc({sendDaemonCommand:a,activeConv:I,chats:(M=n.find(A=>A.id===(I==null?void 0:I.routeId)))==null?void 0:M.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),_=o.useCallback(()=>{d(!0)},[]),H=o.useCallback(()=>{d(!1)},[]),F=o.useCallback(async()=>{if(!(!I||!v||p)){x(!0);try{const A=I.daemonId||I.routeId,U=$t(I),$=await a(A,"list_saved_sessions",{agentType:U,providerType:U,kind:"cli",limit:50}),E=($==null?void 0:$.result)??$;f(Array.isArray(E==null?void 0:E.sessions)?E.sessions:[])}catch(A){console.error("Refresh saved sessions failed",A),f([])}finally{x(!1)}}},[I,p,v,a]);o.useEffect(()=>{if(!m){C.current=null;return}if(!v){C.current=null,f([]),x(!1);return}!T||p||C.current!==T&&(C.current=T,F())},[F,m,p,v,T]);const O=o.useCallback(async A=>{if(!I||!v||!A.providerSessionId||!A.workspace)return;const U=I.daemonId||I.routeId,$=$t(I);try{g(A.providerSessionId);const E=await a(U,"launch_cli",{cliType:$,dir:A.workspace,resumeSessionId:A.providerSessionId,initialModel:Xi(A.summaryMetadata,"model",{preferShortValue:!0})||void 0}),z=(E==null?void 0:E.result)??E,Y=typeof(z==null?void 0:z.sessionId)=="string"?z.sessionId:typeof(z==null?void 0:z.id)=="string"?z.id:"";Y&&u(ve=>{const re=new URLSearchParams(ve);return re.set("activeTab",Y),re},{replace:!0}),H()}catch(E){console.error("Resume saved session failed",E)}finally{g(null)}},[H,I,v,a,u]);return{historyModalOpen:m,openHistoryModal:_,closeHistoryModal:H,historyTargetConv:I,isSavedSessionHistoryTarget:v,isHistoryCreatingChat:S,isHistoryRefreshingHistory:k,handleHistorySwitchSession:b,handleHistoryNewChat:B,handleHistoryRefresh:L,savedHistorySessions:h,savedHistoryFilters:j,setSavedHistoryFilters:N,isSavedHistoryLoading:p,resumingSavedHistorySessionId:y,handleRefreshSavedHistory:F,handleResumeSavedHistorySession:O}}function Lh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,m]=o.useState(null),[d,h]=o.useState(null),f=o.useMemo(()=>{if(e||!n)return null;const y=l(n);return y&&!Qe(y)&&!Ve(y)?y:null},[e,n,l]),j=o.useMemo(()=>{const y=u==null?void 0:u.routeId;if(!y)return null;const g=u!=null&&u.tabKey?i.find(C=>C.tabKey===u.tabKey):a?i.find(C=>C.tabKey===a):null;return(g==null?void 0:g.routeId)===y?g:_t(i,y)},[i,u,a]),N=o.useMemo(()=>{if(j)return c.find(y=>y.id===j.routeId)},[c,j]);o.useEffect(()=>{f&&(m({routeId:f.routeId,tabKey:Co(f)}),h(f),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,f]);const p=o.useCallback(y=>{y&&(m({routeId:y.routeId,tabKey:Co(y)}),h(y))},[]),x=o.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:j,remoteDialogIdeEntry:N,remoteDialogActiveConv:d,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:x}}function Rh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:u,sendDaemonCommand:m}){const{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:j,openRemoteDialog:N,closeRemoteDialog:p}=Lh({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[x,y]=o.useState(!1),[g,C]=o.useState(null),I=o.useCallback(async S=>{const k=S||u;!k||!Qe(k)&&!Ve(k)||(C(k),y(!0))},[u]),v=o.useCallback(()=>{y(!1),C(null)},[]),T=o.useCallback(async S=>{const k=g||u;if(!k||!Qe(k)&&!Ve(k)){v();return}y(!1);try{const b=$t(k),B=k.routeId||k.daemonId||"";await m(B,"stop_cli",{cliType:b,targetSessionId:k.sessionId,mode:S})}catch(b){console.error("Stop CLI failed:",b)}finally{C(null)}},[u,v,g,m]);return{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:j,openRemoteDialog:N,closeRemoteDialog:p,cliStopDialogOpen:x,cliStopTargetConv:g,requestCliStop:I,cancelCliStop:v,confirmCliStop:T}}function Zc(){return"select_session"}function _h(){return"open_panel"}function Ph({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Dh(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 Ya(e){return e instanceof Error?e.message:String(e||"")}function Jo(e){const t=Ya(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Qo(e,t){const r=Ya(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function on({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[u,m]=o.useState(null),d=o.useRef(!1),h=o.useRef(null);o.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const f=o.useCallback(async x=>{if(!t)return!1;const y=x.trim(),g=_a(t);if(Ph({hasMessage:!!y,blockedMessage:g,sendInFlight:d.current}))return g&&m(g),!1;const C=Date.now(),I={tabKey:t.tabKey,message:y,timestamp:C};if(Dh(h.current,I))return m(null),!0;d.current=!0,l(!0),m(null),h.current=I;try{const v=sr(t);if(!v)return h.current=Yo(h.current,I),m("Unable to send message right now."),!1;const T=await e(v,"send_chat",{message:y,...ws(t)}),S=Xo(T);if(S!=null&&S.deduplicated)return m(null),!0;if((S==null?void 0:S.sent)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");if((S==null?void 0:S.success)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");return m(null),!0}catch(v){const T=Ya(v);return T.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",T):console.warn("Send blocked/failed",v),h.current=Yo(h.current,I),m(Om(v)),!1}finally{d.current=!1,l(!1)}},[t,e]),j=o.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(x){console.error("Relaunch failed",x)}},[t,e]),N=o.useCallback(async x=>{if(t)try{const g=(t.modalButtons||[]).indexOf(x),C=x.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),I=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(C),v=sr(t);if(!v)return;const T=await e(v,"resolve_action",{button:x,action:I?"approve":"reject",...g>=0&&{buttonIndex:g},...ws(t)}),S=Xo(T);S.success||r(k=>[...k,{routeId:t.tabKey,text:Qo(x,S==null?void 0:S.error),timestamp:Date.now()}])}catch(y){Jo(y)||console.error("[ModalButton] Error:",y),r(g=>[...g,{routeId:t.tabKey,text:Jo(y)?Qo(x,y):`❌ **${x}** error`,timestamp:Date.now()}])}},[t,e,r]),p=o.useCallback(async()=>{if(!(!t||a)){i(!0);try{await e(t.routeId,_h(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(x){console.error("Focus agent failed",x)}finally{i(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:u,isFocusingAgent:a,handleSendChat:f,handleRelaunch:j,handleModalButton:N,handleFocusAgent:p}}function In(e,t=!0){return(e??!0)&&t}const Xa=o.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d=null,handleFocusAgent:h,isFocusingAgent:f,actionLogs:j,userName:N,scrollToBottomRequestNonce:p,isInputActive:x=!0,isVisible:y=!0}){const g=n,C=!n,I=In(y,g),v=In(y,C),T=In(y),S=Wc(t),k=S.status||S.modalMessage||S.modalButtons?{...t,...S.status?{status:S.status}:{},...S.modalMessage!==void 0?{modalMessage:S.modalMessage}:{},...S.modalButtons!==void 0?{modalButtons:S.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(zi,{activeConv:k,onModalButton:c}),k.transport!=="pty"&&k.transport!=="acp"&&k.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(Zs,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:l,children:"Relaunch with CDP"})]})}):null,k.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:g?"visible":"hidden",pointerEvents:g?"auto":"none"},children:s.jsx(vf,{activeConv:k,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,isVisible:I,isInputActive:x&&I})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(ca,{activeConv:k,ideEntry:a,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:f,actionLogs:j,userName:N,scrollToBottomRequestNonce:p,isInputActive:x&&v,isVisible:v})})]}):s.jsx(ca,{activeConv:k,ideEntry:a,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:f,actionLogs:j,userName:N,scrollToBottomRequestNonce:p,isInputActive:x&&T,isVisible:T})]})},(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 Eh({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:m,onOpenNativeConversation:d,onOpenMachine:h,onOpenHistory:f,onOpenRemote:j,onHideConversation:N,onStopCli:p,cliViewMode:x,onSetCliViewMode:y,handleSendChat:g,handleFocusAgent:C,handleModalButton:I,handleRelaunch:v}){const T=o.useRef(null),S=Qe(e)&&!t,k=S&&x==="terminal",b=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${b} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(va,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:at(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(uc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>h(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&x&&s.jsx(Ea,{mode:x,onChange:y,compact:!0}),S&&p&&s.jsx("button",{onClick:()=>{p(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(vt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(wa,{size:14})}),!t&&!S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>j(e),type:"button",children:s.jsx(St,{size:14})}),N&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>N(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(Xa,{activeConv:e,clearToken:0,isCliTerminal:k,ideEntry:n,terminalRef:T,handleModalButton:I,handleRelaunch:v,handleSendChat:g,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:C,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const An={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function $h(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function el(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t($h())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(An[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:An[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:An[c].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function tl({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:St},{key:"chats",label:"Chats",icon:Wt}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:i})=>{const c=e===n;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(n),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(i,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function wr({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function ps({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function Os({icon:e,title:t,subtitle:r,children:n}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function jr({item:e,type:t,getAvatarText:r,onOpenConversation:n}){const a=t==="needs_attention"||t==="task_complete",i=t==="working",c=t==="earlier",l=t==="task_complete",{isReconnecting:u,isConnecting:m}=As(e.conversation),d=at(e.conversation),h=ls(e.conversation),f=yc(e.conversation,{requiresAction:t==="needs_attention"}),j=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",N=a?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",p=c?"text-text-secondary":"text-text-primary",x=c?"text-text-muted":"text-text-secondary",y=c?"text-text-secondary opacity-80":"text-text-muted",g=c?"text-text-muted opacity-80":"text-text-muted",C=!i&&!l,I="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] ${j}`,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 ${N}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(d)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${p}`,children:d}),C&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${g}`,children:Ui(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${x}`,children:[h,u?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${I} animate-pulse`,children:"Reconnecting…"})]}):m?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):f==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:I,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,children:e.preview})]}),a&&!l&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),i&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]},e.conversation.tabKey)}function 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 Bh({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:m,onShowAllHidden:d,onOpenNewSession:h,onOpenMachine:f,onOpenSettings:j,onSectionChange:N,wsStatus:p="connected",isStandalone:x=!1}){const y=p==="disconnected"||p==="reconnecting"||p==="offline"||p==="auth_failed",g=c.length>0,C=t.length>0||r.length>0||n.length>0||a.length>0,I=e==="machines"?"Machines":"Chats",v=x?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",T=x?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${v}`,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:I}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Jr,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:j,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Xr,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${T}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:y?s.jsx(Os,{icon:s.jsx(Zo,{label:"Reconnecting…"}),title:p==="offline"?"Network offline":p==="auth_failed"?"Session expired":"Reconnecting",subtitle:p==="offline"?"Waiting for network…":p==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(Os,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:x?"Waiting for your daemon":"Connect your machines",subtitle:x?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!x&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(el,{})})}):s.jsx(ps,{children:c.map((S,k)=>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] ${k>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(S.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(S.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:S.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:S.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[S.unread," new"]}):S.total>0?`${S.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:S.subtitle}),S.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[S.total," chat",S.total!==1?"s":"",S.unread>0?` · ${S.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},S.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Needs attention",className:"mb-0"}),s.jsx(ps,{children:t.map((S,k)=>s.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:S,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},S.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(ps,{children:r.map((S,k)=>s.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:S,type:"task_complete",getAvatarText:l,onOpenConversation:u})},S.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(ps,{children:n.map((S,k)=>s.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:S,type:"working",getAvatarText:l,onOpenConversation:u})},S.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(wr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(ps,{children:a.map((S,k)=>s.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:S,type:"earlier",getAvatarText:l,onOpenConversation:u})},S.conversation.tabKey))}):C?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):y?s.jsx(Os,{icon:s.jsx(Zo,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):g?s.jsx(Os,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Wt,{size:20})}),title:"No conversations yet",subtitle:jc,children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":Dt,title:Dt,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:Dt})]})}):s.jsx(Os,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[s.jsx("span",{children:"Hidden"}),s.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:d,children:"Restore all"})]}),s.jsx(ps,{className:"bg-bg-secondary/25",children:i.map((S,k)=>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 ${k>0?"border-t border-border-subtle/70":""}`,onClick:()=>m(S),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(at(S))}),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:at(S)}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:ls(S)}),s.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},S.tabKey))})]})]}),e==="chats"&&h&&C&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":Dt,title:Dt,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),s.jsx(tl,{section:e,onSectionChange:N})]})}function Kh(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 sl(e){const t=[e.workspace||"Workspace unknown"],r=cs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Kh(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function cn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:m}){const[d,h]=o.useState(r);o.useEffect(()=>{h(r)},[r]);const f=gh(r),j=d.trim();return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!f||a||u(f)},disabled:!f||a,children:[s.jsx(va,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:N=>h(N.target.value),onKeyDown:N=>{N.key!=="Enter"||!j||a||(N.preventDefault(),u(j))},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:()=>{!j||a||u(j)},disabled:!j||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(N=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(N.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Ss,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:N.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:N.path})]})]},N.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(j||r),disabled:!j&&!r||a,children:c})]})]})})}function Ja({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:m,argsValue:d,onArgsChange:h,showModelInput:f,modelValue:j,onModelChange:N,historyProviderNode:p,onConfirm:x,onCancel:y}){const g=n==null?void 0:n.find(C=>C.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:y,"aria-label":"Close launch confirmation",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:C=>i(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(C=>s.jsx("option",{value:C.key,children:C.label},C.key))}),(g==null?void 0:g.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:g.description})]}),p,r.map(C=>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:C.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:C.value})]},`${C.label}:${C.value}`)),f&&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:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:j||"",onChange:C=>N(C.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),m&&h&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:d||"",onChange:C=>h(C.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,disabled:u,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:x,disabled:u,children:[s.jsx(ka,{size:14}),u?l:c]})]})]})})}function ei(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ns(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${ei(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:ei(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(m=>m.key===u))return{options:i,selectedKey:u}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Oh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Wh(e){return[Oh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Hh(e){return e.lastLaunchedAt?Qr(e.lastLaunchedAt):""}function rl(e){return{metaText:Wh(e),updatedLabel:Hh(e)}}function Ln(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Fh({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var Ye,mt,pt,dt;const c=ir(),[l,u]=o.useState(!1),m=(((Ye=e.detectedIdes)==null?void 0:Ye.length)||0)>0,d=o.useMemo(()=>(e.workspaces||[]).map(Ce=>({id:Ce.id,path:Ce.path,label:Ce.label})),[e]),h=e.defaultWorkspaceId||null,[f,j]=o.useState(h||((mt=d[0])==null?void 0:mt.id)||""),[N,p]=o.useState(""),[x,y]=o.useState(""),[g,C]=o.useState([]),[I,v]=o.useState(!1),[T,S]=o.useState(""),[k,b]=o.useState(!1),[B,L]=o.useState(Ln(m,t.length,r.length)),_=o.useRef(null),[H,F]=o.useState(null),O=o.useRef("__home__"),[M,A]=o.useState("__home__"),[U,$]=o.useState(""),[E,z]=o.useState(""),[Y,ve]=o.useState(""),[re,ye]=o.useState([]),[le,be]=o.useState(()=>ht().textQuery),[ge,G]=o.useState(()=>ht().workspaceQuery),[ne,q]=o.useState(()=>ht().modelQuery),[ue,ce]=o.useState(()=>ht().resumableOnly),[je,ae]=o.useState(()=>ht().sortMode),[fe,oe]=o.useState(!1),[te,ee]=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 de=f==="__custom__"?N.trim():((pt=d.find(Ce=>Ce.id===f))==null?void 0:pt.path)||"",D=f==="__custom__"&&!!de&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ie=f!=="__custom__"&&((dt=d.find(Ce=>Ce.id===f))==null?void 0:dt.path)||"",Q=o.useMemo(()=>(e.recentLaunches||[]).map(Ce=>Ce.workspace),[e]),we=o.useCallback(async Ce=>{v(!0),S("");try{const He=await a(Ce);y(He.path),p(He.path),C(He.directories)}catch(He){S(He instanceof Error?He.message:"Could not load folder")}finally{v(!1)}},[a]),Ne=o.useCallback(()=>{var He;j("__custom__"),b(!0);const Ce=nn(e.platform,rn(N.trim(),ie,Q,e.defaultWorkspacePath,(He=d.find(Xe=>Xe.id===h))==null?void 0:He.path,d.map(Xe=>Xe.path)));we(Ce)},[N,h,we,Q,ie,e.platform,d]),Ae=o.useCallback(Ce=>{if(Ce!=null&&Ce.workspaceId){j(Ce.workspaceId),p("");return}if(Ce!=null&&Ce.workspacePath){j("__custom__"),p(Ce.workspacePath);return}j(""),p("")},[]),Te=o.useCallback(Ce=>{if(j(Ce),Ce==="__custom__"){Ne();return}p("")},[Ne]),Ue=o.useCallback(Ce=>{j("__custom__"),p(Ce)},[]),We=o.useCallback((Ce,He)=>{_.current=He,O.current=Ce.selectedWorkspaceKey||"__home__",A(Ce.selectedWorkspaceKey||"__home__"),$(Ce.initialArgs||""),z(Ce.initialModel||""),ve(""),ye([]);const Xe=Ce.providerType?`${e.id}:${Ce.providerType}`:null;if(Mf(J.current,Xe)){const ot=ht();be(ot.textQuery),G(ot.workspaceQuery),q(ot.modelQuery),ce(ot.resumableOnly),ae(ot.sortMode)}J.current=Xe,F(Ce),Ce.providerType&&i&&(oe(!0),i(Ce.providerType).then(ot=>ye(ot||[])).catch(ot=>console.warn("Failed to load saved sessions",ot)).finally(()=>oe(!1)))},[i,e.id]),Ke=o.useMemo(()=>kc(re,{textQuery:le,workspaceQuery:ge,modelQuery:ne,resumableOnly:ue,sortMode:je}),[ne,ue,re,je,le,ge]);o.useEffect(()=>{Y&&(Ke.some(Ce=>Ce.providerSessionId===Y)||ve(""))},[Ke,Y]);const Ge=o.useCallback(()=>{_.current&&(ee(!0),_.current().finally(()=>{_.current=null,ee(!1),F(null)}))},[]),Ze=o.useCallback(()=>{_.current=null,F(null)},[]),Je=o.useCallback(Ce=>{O.current=Ce,A(Ce)},[]);return o.useEffect(()=>{var Ce;X.current!==e.id&&(X.current=e.id,j(h||((Ce=d[0])==null?void 0:Ce.id)||"__custom__"),p(""),y(""),C([]),S(""),b(!1),be(ht().textQuery),G(ht().workspaceQuery),q(ht().modelQuery),ce(ht().resumableOnly),ae(ht().sortMode),J.current=null,L(Ln(m,t.length,r.length)))},[r.length,t.length,h,m,e.id,d]),o.useEffect(()=>{var Ce;f!=="__custom__"&&(f&&d.some(He=>He.id===f)||j(h||((Ce=d[0])==null?void 0:Ce.id)||"__custom__"))},[h,f,d]),o.useEffect(()=>{B==="ide"&&m||B==="cli"&&t.length>0||B==="acp"&&r.length>0||L(Ln(m,t.length,r.length))},[B,r.length,t.length,m]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:m,workspaceRows:d,defaultWorkspaceId:h,workspaceChoice:f,customWorkspacePath:N,browseCurrentPath:x,browseDirectories:g,browseBusy:I,browseError:T,browseDialogOpen:k,activeLauncherKind:B,launchConfirm:H,launchConfirmWorkspaceKeyRef:O,launchConfirmWorkspaceKey:M,launchConfirmArgs:U,launchConfirmModel:E,launchConfirmResumeId:Y,launchConfirmSavedSessions:re,launchConfirmTextFilter:le,launchConfirmWorkspaceFilter:ge,launchConfirmModelFilter:ne,launchConfirmResumableOnly:ue,launchConfirmSortMode:je,filteredLaunchConfirmSavedSessions:Ke,launchConfirmSessionsLoading:fe,launchConfirmBusy:te,resolvedWorkspacePath:de,canCreateMissingWorkspace:D,openBrowseDialog:Ne,loadBrowsePath:we,handleWorkspaceChoiceChange:Te,chooseCustomWorkspacePath:Ue,setCustomWorkspacePath:p,setBrowseDialogOpen:b,setActiveLauncherKind:L,openLaunchConfirm:We,handleConfirmLaunch:Ge,closeLaunchConfirm:Ze,setWorkspaceSelectionFromOption:Ae,setLaunchConfirmWorkspaceKeyAndSync:Je,setLaunchConfirmArgs:$,setLaunchConfirmModel:z,setLaunchConfirmResumeId:ve,setLaunchConfirmTextFilter:be,setLaunchConfirmWorkspaceFilter:G,setLaunchConfirmModelFilter:q,setLaunchConfirmResumableOnly:ce,setLaunchConfirmSortMode:ae}}function Uh({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:m,showBottomNav:d,onBack:h,onSectionChange:f,onOpenConversation:j,onOpenRecent:N,onOpenMachineDetails:p,onMachineUpgrade:x,onLaunchDetectedIde:y,onAddWorkspace:g,onBrowseDirectory:C,onLaunchWorkspaceProvider:I,onListSavedSessions:v}){const T=M=>M==="ide"?"IDE":M==="cli"?"CLI":"ACP",S=r.slice(0,4),k=t.slice(0,3),b=Fh({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:C,onListSavedSessions:v}),B=o.useMemo(()=>S.map(M=>{const{metaText:A,updatedLabel:U}=rl(M);return{key:`recent-launch:${M.id}`,primary:M.label,secondary:A,updatedLabel:U,onClick:()=>{const{options:$,selectedKey:E}=ns({machine:{workspaces:b.workspaceRows,defaultWorkspaceId:b.defaultWorkspaceId},currentWorkspacePath:M.workspace});b.openLaunchConfirm({title:M.kind==="ide"?es("restart-ide",M.label):M.providerSessionId?Ka(M.label):es("start-fresh",M.label),description:M.kind==="ide"?ts("restart-ide"):M.providerSessionId?Oa():ts("start-fresh"),confirmLabel:M.kind==="ide"?Cs("restart-ide"):M.providerSessionId?zr(!0):Cs("start-fresh"),busyLabel:M.kind==="ide"?Ms("restart-ide"):M.providerSessionId?$a(!0):Ms("start-fresh"),workspaceOptions:$,selectedWorkspaceKey:E,details:[{label:"Mode",value:T(M.kind)},...M.providerType?[{label:"Provider",value:M.providerType}]:[]]},async()=>{const z=$.find(Y=>Y.key===b.launchConfirmWorkspaceKeyRef.current);b.setWorkspaceSelectionFromOption(z),await N({...M,workspace:(z==null?void 0:z.workspacePath)??null})})}}}),[b,N,S]),L=o.useMemo(()=>k.map(M=>({key:`recent-chat:${M.conversation.tabKey}`,primary:at(M.conversation),secondary:xf(M.conversation,{timestampLabel:M.timestamp?Ui(M.timestamp):null}),unread:M.unread,onClick:()=>j(M.conversation)})),[j,k]),_=b.showAllRecent?B:B.slice(0,4),H=B.length>0,F=L.length>0,O=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${O} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:s.jsx(va,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Mt(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[F&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:L.map(M=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${M.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:M.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:M.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:M.secondary})]},M.key))})]}),H&&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:_.map(M=>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:M.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:M.primary}),M.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:M.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:M.secondary})]},M.key))}),B.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>b.setShowAllRecent(M=>!M),children:b.showAllRecent?"Show fewer":`Show ${B.length-4} more`})})]}),(b.hasIdeOptions||n.length>0||a.length>0)&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:s.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),s.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),s.jsx("select",{value:b.workspaceChoice,onChange:M=>b.handleWorkspaceChoiceChange(M.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:b.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[b.workspaceRows.map(M=>s.jsxs("option",{value:M.id,children:[M.id===b.defaultWorkspaceId?"⭐ ":"",en(M.path,M.label)||M.path]},M.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),b.workspaceChoice==="__custom__"&&s.jsxs("div",{className:"flex flex-col gap-2.5",children:[s.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Ss,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),s.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:b.resolvedWorkspacePath||b.browseCurrentPath||"No folder selected yet."})]})]})}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:b.openBrowseDialog,children:"Select workspace…"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{b.resolvedWorkspacePath&&g(b.resolvedWorkspacePath)},disabled:!b.resolvedWorkspacePath||b.browseBusy,children:"Save as workspace"})]})]}),b.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:b.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[b.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${b.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>b.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${b.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>b.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${b.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>b.setActiveLauncherKind("acp"),children:"ACP"})]}),b.activeLauncherKind&&s.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[s.jsx("div",{className:"text-xs font-bold text-text-secondary",children:b.activeLauncherKind==="ide"?"Choose an IDE":b.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:b.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(M=>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:A,selectedKey:U}=ns({machine:{workspaces:b.workspaceRows,defaultWorkspaceId:b.defaultWorkspaceId},currentWorkspaceId:b.workspaceChoice!=="__custom__"?b.workspaceChoice:null,currentWorkspacePath:b.resolvedWorkspacePath});b.openLaunchConfirm({title:`Launch ${M.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:A,selectedWorkspaceKey:U,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:M.name}]},async()=>{const $=A.find(E=>E.key===b.launchConfirmWorkspaceKeyRef.current);b.setWorkspaceSelectionFromOption($),y(M.type,{workspacePath:($==null?void 0:$.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:M.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:b.resolvedWorkspacePath||"Use selected workspace"})]},M.type)):(b.activeLauncherKind==="cli"?n:a).map(M=>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 A=b.activeLauncherKind==="cli"?"cli":"acp",{options:U,selectedKey:$}=ns({machine:{workspaces:b.workspaceRows,defaultWorkspaceId:b.defaultWorkspaceId},currentWorkspaceId:b.workspaceChoice!=="__custom__"?b.workspaceChoice:null,currentWorkspacePath:b.resolvedWorkspacePath});b.openLaunchConfirm({title:`Launch ${M.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${A.toUpperCase()}`,workspaceOptions:U,selectedWorkspaceKey:$,details:[{label:"Mode",value:A.toUpperCase()},{label:"Provider",value:M.displayName}],showArgsInput:!0,showModelInput:A==="acp",initialArgs:"",initialModel:"",providerType:M.type},async()=>{const E=U.find(z=>z.key===b.launchConfirmWorkspaceKeyRef.current);b.setWorkspaceSelectionFromOption(E),I(A,M.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.workspacePath)??null,args:b.launchConfirmArgs,model:b.launchConfirmModel,resumeSessionId:b.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[M.icon?`${M.icon} `:"",M.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:b.resolvedWorkspacePath||"Use selected workspace"})]},M.type))})]}),l.message&&s.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,b.canCreateMissingWorkspace&&s.jsx("div",{className:"mt-2",children:s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>g(b.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:x,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:p,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),b.browseDialogOpen&&s.jsx(cn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:b.browseCurrentPath,directories:b.browseDirectories,busy:b.browseBusy,error:b.browseError,confirmLabel:"Use this folder",onClose:()=>b.setBrowseDialogOpen(!1),onNavigate:M=>{b.loadBrowsePath(M)},onConfirm:M=>{b.chooseCustomWorkspacePath(M),b.setBrowseDialogOpen(!1)}}),b.launchConfirm&&s.jsx(Ja,{title:b.launchConfirm.title,description:b.launchConfirm.description,details:b.launchConfirm.details,workspaceOptions:b.launchConfirm.workspaceOptions,selectedWorkspaceKey:b.launchConfirmWorkspaceKey,onWorkspaceChange:b.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:b.launchConfirm.providerType?zr(!!b.launchConfirmResumeId):b.launchConfirm.confirmLabel,busyLabel:b.launchConfirm.providerType?void 0:b.launchConfirm.busyLabel,busy:b.launchConfirmBusy,showArgsInput:b.launchConfirm.showArgsInput,argsValue:b.launchConfirmArgs,onArgsChange:b.setLaunchConfirmArgs,showModelInput:b.launchConfirm.showModelInput,modelValue:b.launchConfirmModel,onModelChange:b.setLaunchConfirmModel,historyProviderNode:b.launchConfirm.providerType&&(b.launchConfirmSessionsLoading||b.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),b.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Ba()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:b.launchConfirmTextFilter,onChange:M=>b.setLaunchConfirmTextFilter(M.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:b.launchConfirmWorkspaceFilter,onChange:M=>b.setLaunchConfirmWorkspaceFilter(M.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:b.launchConfirmModelFilter,onChange:M=>b.setLaunchConfirmModelFilter(M.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),s.jsxs("select",{value:b.launchConfirmSortMode,onChange:M=>b.setLaunchConfirmSortMode(M.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:b.launchConfirmResumableOnly,onChange:M=>b.setLaunchConfirmResumableOnly(M.target.checked),disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:b.launchConfirmResumeId,onChange:M=>b.setLaunchConfirmResumeId(M.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Af()}),b.filteredLaunchConfirmSavedSessions.map(M=>s.jsxs("option",{value:M.providerSessionId,disabled:!M.canResume,children:[M.title||M.providerSessionId," ",M.canResume?"":"(workspace missing)"]},M.providerSessionId))]}),!b.launchConfirmSessionsLoading&&b.launchConfirmSavedSessions.length>0&&b.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),b.launchConfirmResumeId&&(()=>{const M=b.filteredLaunchConfirmSavedSessions.find(U=>U.providerSessionId===b.launchConfirmResumeId);if(!M)return null;const A=sl(M);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:A.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:A.providerSessionId}),s.jsx("div",{className:"mt-1",children:A.metaLine}),A.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:A.updatedLabel}),A.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:A.preview})]})})()]}),onConfirm:b.handleConfirmLaunch,onCancel:b.closeLaunchConfirm}),d&&s.jsx(tl,{section:m,onSectionChange:f})]})}function Rr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function zh(e,t=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=t.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:Rr(e)}function Vh(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 Gh(e,t){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:cs(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,m,d;const a=tr(n)?"cli":gs(n)?"acp":"ide",i=cs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(tr(n)?n.cliName||n.type:gs(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:gs(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((d=(m=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:m.call(u,-1))==null?void 0:d.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function qh(e,t){const r=new Map;for(const n of t){const a=ms(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((h,f)=>f.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=ta(n),u=a.filter(h=>h.unread||h.requiresAction).length,m=Vh(n),d=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Mt(n,{fallbackId:n.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?bf(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 Yh(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 Xh({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:j,setSelectedTabKey:N,setScreen:p,setSelectedMachineId:x,setSection:y,setMachineBackTarget:g,resetMachineAction:C}){const I=o.useRef(null),v=o.useCallback(T=>{if(!(T!=null&&T.sessionId))return;const S=Or(T,c),k=Math.max(Date.now(),Qt(T),S.lastUpdated||0);kr("mark_read:start",{tabKey:T.tabKey,sessionId:T.sessionId,displayPrimary:at(T),inboxBucket:S.inboxBucket,unread:S.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:Qt(T),readAt:k}),l(ms(T)||T.routeId,"mark_session_seen",{sessionId:T.sessionId,providerSessionId:T.providerSessionId,seenAt:k,completionMarker:S.completionMarker}).then(b=>{kr("mark_read:result",{tabKey:T.tabKey,sessionId:T.sessionId,result:b})}).catch(b=>{kr("mark_read:error",{tabKey:T.tabKey,sessionId:T.sessionId,error:b instanceof Error?b.message:String(b)})})},[c,l]);return o.useEffect(()=>{var S;if(!n){Yh(i)&&p("inbox"),N(((S=e[0])==null?void 0:S.tabKey)||null),I.current=null;return}if(i!=="chat"){I.current=null;return}const T=`${n.tabKey}:${n.sessionId||""}`;I.current!==T&&(I.current=T,v(n))},[e,v,i,n,p,N]),o.useEffect(()=>{if(!u)return;const T=e.find(S=>S.tabKey===u);T&&(N(T.tabKey),p("chat"),m==null||m())},[e,m,u,p,N]),o.useEffect(()=>{if(!d)return;const T=t.find(S=>S.id===d);T&&(x(T.id),C(),y("machines"),g("inbox"),p("machine"),h==null||h())},[t,h,d,C,g,p,y,x]),o.useEffect(()=>{f&&(y(f),p("inbox"),j==null||j())},[j,f,p,y]),o.useEffect(()=>{const T=r.filter(S=>S.inboxBucket==="task_complete"||S.unread);T.length!==0&&kr("inbox_state",{screen:i,selectedTabKey:a,items:T.map(S=>{const k=Or(S.conversation,c);return{liveState:k,tabKey:S.conversation.tabKey,sessionId:S.conversation.sessionId,displayPrimary:at(S.conversation),serverBucket:k.inboxBucket,computedBucket:S.inboxBucket,serverUnread:k.unread,computedUnread:S.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:Qt(S.conversation)}})})},[r,c,i,a]),{markConversationRead:v}}function Jh(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 Qh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Zh({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,m]=o.useState(null),d=o.useCallback(()=>{i("idle"),l(""),m(null)},[]),h=o.useCallback(async(g,C,I)=>{var v;try{i("loading"),l(`Launching ${C}…`);const T={ideType:C,enableCdp:!0};(v=I==null?void 0:I.workspacePath)!=null&&v.trim()&&(T.workspace=I.workspacePath.trim()),await e(g,"launch_ide",T),i("done"),l(`${C} launch requested`)}catch(T){i("error"),l(T instanceof Error?T.message:"Launch IDE failed"),console.error("Launch IDE failed",T)}},[e]),f=o.useCallback(async(g,C,I)=>{if(C.trim())try{i("loading"),l(I!=null&&I.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(g,"workspace_add",{path:C.trim(),createIfMissing:(I==null?void 0:I.createIfMissing)===!0});if(v!=null&&v.success){i("done"),l(I!=null&&I.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((v==null?void 0:v.error)||"Could not save workspace")}catch(v){i("error"),l(v instanceof Error?v.message:"Could not save workspace")}},[e]),j=o.useCallback(async g=>{var C,I,v,T,S,k;try{i("loading"),l("Starting daemon upgrade…");const b=await e(g,"daemon_upgrade",{});if((C=b==null?void 0:b.result)!=null&&C.alreadyLatest){i("done"),l(`Already on v${((I=b==null?void 0:b.result)==null?void 0:I.version)||"latest"}.`);return}if((v=b==null?void 0:b.result)!=null&&v.upgraded||(T=b==null?void 0:b.result)!=null&&T.success){i("done"),l(`Upgrade to v${((S=b==null?void 0:b.result)==null?void 0:S.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((k=b==null?void 0:b.result)==null?void 0:k.error)||"Upgrade failed")}catch(b){i("error"),l(b instanceof Error?b.message:"Upgrade failed")}},[e]),N=o.useCallback(async(g,C,I,v)=>{var k,b,B;const T=Date.now(),S={machineId:g,kind:C,providerType:I,workspaceId:(v==null?void 0:v.workspaceId)||null,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:T};try{i("loading"),l(`Launching ${I}…`),m(S);const L={cliType:I};(k=v==null?void 0:v.workspacePath)!=null&&k.trim()?L.dir=v.workspacePath.trim():v!=null&&v.workspaceId&&(L.workspaceId=v.workspaceId),v!=null&&v.resumeSessionId&&(L.resumeSessionId=v.resumeSessionId),(b=v==null?void 0:v.args)!=null&&b.trim()&&(L.cliArgs=v.args.trim().split(/\s+/).filter(Boolean)),(B=v==null?void 0:v.model)!=null&&B.trim()&&(L.initialModel=v.model.trim());const _=await e(g,"launch_cli",L),H=(_==null?void 0:_.result)||_,F=(H==null?void 0:H.sessionId)||(H==null?void 0:H.id);if(_!=null&&_.success&&F){m(null),i("done"),l(`${I} launched`),t(zt(F));return}if(_!=null&&_.success){i("loading"),l(`${I} launch requested — waiting for session…`);return}m(null),i("error"),l((_==null?void 0:_.error)||(H==null?void 0:H.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(L){if(Qh(L)){i("loading"),l(`${I} launch requested — waiting for session…`);return}m(null),i("error"),l(L instanceof Error?L.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),p=o.useCallback(async(g,C)=>{try{const I=await e(g,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),v=(I==null?void 0:I.result)??I;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(I){return console.error("Failed to list saved sessions on mobile:",I),[]}},[e]),x=o.useCallback(async(g,C)=>an(e,g,C),[e]);o.useEffect(()=>{if(!u)return;const g=ti(u.workspacePath),C=r.find(v=>{var L,_,H,F;if(!v||v.type==="adhdev-daemon"||Jh(v.daemonId||v.id)!==u.machineId||(v.transport==="acp"?"acp":v.transport==="pty"?"cli":null)!==u.kind||String(v.agentType||v.type||"")!==u.providerType)return!1;const b=String(v.providerSessionId||"");if(u.resumeSessionId&&b)return b===u.resumeSessionId;if(g){const O=ti(v.workspace||v.runtimeWorkspaceLabel);return O?O===g:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((F=(H=(_=(L=v.activeChat)==null?void 0:L.messages)==null?void 0:_.at)==null?void 0:H.call(_,-1))==null?void 0:F.timestamp)||0)>=u.startedAt-5e3});if(!C)return;const I=dc({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:n});I&&(m(null),i("done"),l(`${u.providerType} launched`),t(zt(I)))},[n,r,t,u]),o.useEffect(()=>{if(!u)return;const g=window.setTimeout(()=>{m(C=>!C||C.startedAt!==u.startedAt?C:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(g)},[u]);const y=o.useCallback(async(g,C)=>{if(C.kind==="ide"&&C.providerType){await h(g,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await N(g,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[h,N]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:h,handleAddWorkspace:f,handleMachineUpgrade:j,handleLaunchWorkspaceProvider:N,handleListSavedSessions:p,handleBrowseDirectory:x,handleOpenRecent:y}}function ex({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:m}){const d=o.useCallback(y=>{i(y.tabKey),c("chat"),n(y)},[n,c,i]),h=o.useCallback(y=>{const g=e.find(C=>C.routeId===y.routeId&&C.streamSource==="native");g&&(i(g.tabKey),c("chat"),n(g))},[e,n,c,i]),f=o.useCallback(()=>{n(t),c("inbox")},[n,t,c]),j=o.useCallback((y,g="inbox")=>{l(y),a(),u("machines"),m(g),c("machine")},[a,m,c,u,l]),N=o.useCallback(y=>{const g=ms(y);g&&j(g,"chat")},[j]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),x=o.useCallback(y=>{u(y),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:h,backFromConversation:f,openMachine:j,openConversationMachine:N,backFromMachine:p,changeMachineSection:x}}function us(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function tx(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function sx({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:j,onOpenHistory:N,onOpenRemote:p,onStopCli:x,wsStatus:y,isConnected:g,onShowHiddenConversation:C,onShowAllHiddenConversations:I,onHideConversation:v,onOpenNewSession:T,liveSessionInboxState:S,setCliViewModeOverrides:k}){const[b,B]=o.useState(()=>{var Q;return((Q=e[0])==null?void 0:Q.tabKey)||null}),[L,_]=o.useState(()=>e[0]?"chat":"inbox"),[H,F]=o.useState("chats"),[O,M]=o.useState(null),[A,U]=o.useState("inbox"),$=o.useRef([]),E=Is(),z="0.9.44",Y=o.useMemo(()=>e.find(Q=>Q.tabKey===b)||e[0]||null,[e,b]),ve=o.useMemo(()=>Y?r.find(Q=>Q.id===Y.routeId):void 0,[r,Y]),re=o.useMemo(()=>!Y||Ve(Y)||!Qe(Y)?null:Ls(Y),[Y]),ye=o.useMemo(()=>r.filter(Q=>Q.type==="adhdev-daemon").sort(Ca),[r]),le=o.useMemo(()=>ye.find(Q=>Q.id===O)||null,[ye,O]),be=on({sendDaemonCommand:a,activeConv:Y||void 0,setActionLogs:i,isStandalone:c}),ge=Zh({sendDaemonCommand:a,navigate:E,ides:r,conversations:e}),G=o.useMemo(()=>e.map(Q=>{const we=L==="chat"&&(Y==null?void 0:Y.tabKey)===Q.tabKey,Ne=Zr(Q,S,{hideOpenTaskCompleteUnread:!0,isOpenConversation:we}),Ae=Qt(Q),Te=gc(Q);return{conversation:Q,timestamp:Ae,preview:Te,unread:Ne.unread,requiresAction:Ne.requiresAction,isWorking:Ne.isWorking,inboxBucket:Ne.inboxBucket}}),[e,S,L,Y]),{markConversationRead:ne}=Xh({conversations:e,machineEntries:ye,items:G,selectedConversation:Y,selectedTabKey:b,screen:L,liveSessionInboxState:S,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:j,setSelectedTabKey:B,setScreen:_,setSelectedMachineId:M,setSection:F,setMachineBackTarget:U,resetMachineAction:ge.resetMachineAction}),q=ex({conversations:e,selectedConversation:Y,machineBackTarget:A,markConversationRead:ne,resetMachineAction:ge.resetMachineAction,setSelectedTabKey:B,setScreen:_,setSelectedMachineId:M,setSection:F,setMachineBackTarget:U}),ue=o.useMemo(()=>Rr(G.filter(Q=>Q.requiresAction)),[G]),ce=o.useMemo(()=>Rr(G.filter(Q=>Q.unread&&!Q.requiresAction)),[G]),je=o.useMemo(()=>zh(G.filter(Q=>!Q.unread&&!Q.requiresAction&&Q.isWorking),$.current),[G]);o.useEffect(()=>{$.current=je.map(Q=>Q.conversation.tabKey)},[je]);const ae=o.useMemo(()=>Rr(G.filter(Q=>!Q.unread&&!Q.requiresAction&&!Q.isWorking)),[G]),fe=o.useMemo(()=>le?G.filter(Q=>ms(Q.conversation)===le.id):[],[G,le]),oe=o.useMemo(()=>Gh(le,r),[r,le]),te=(le==null?void 0:le.version)||null,ee=!!le&&!!te&&!0&&te!==z,X=o.useMemo(()=>(le==null?void 0:le.availableProviders)||[],[le]),J=o.useMemo(()=>X.filter(Q=>us(Q,"cli")).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[X]),de=o.useMemo(()=>X.filter(Q=>us(Q,"acp")).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[X]),D=o.useMemo(()=>qh(ye,G),[G,ye]),ie=o.useCallback(async Q=>{le&&await ge.handleOpenRecent(le.id,Q)},[ge,le]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:L==="chat"&&Y?s.jsx(Eh,{selectedConversation:Y,isAcp:Ve(Y),isStandalone:c,selectedIdeEntry:ve,actionLogs:n,userName:l,isSendingChat:be.isSendingChat,sendFeedbackMessage:be.sendFeedbackMessage,isFocusingAgent:be.isFocusingAgent,handleModalButton:be.handleModalButton,handleRelaunch:be.handleRelaunch,onBack:q.backFromConversation,onOpenNativeConversation:q.openNativeConversation,onOpenMachine:q.openConversationMachine,onHideConversation:v,onOpenHistory:N,onOpenRemote:p,onStopCli:x,cliViewMode:re,onSetCliViewMode:async Q=>{await Vc({conversation:Y,mode:Q,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:k})},handleSendChat:be.handleSendChat,handleFocusAgent:be.handleFocusAgent}):L==="machine"&&le?s.jsx(Uh,{selectedMachineEntry:le,selectedMachineConversations:fe,selectedMachineRecentLaunches:oe,cliProviders:J,acpProviders:de,selectedMachineNeedsUpgrade:ee,appVersion:z,machineAction:ge.machineAction,isStandalone:c,section:H,showBottomNav:A==="inbox",onBack:q.backFromMachine,onSectionChange:q.changeMachineSection,onOpenConversation:q.openConversation,onOpenRecent:ie,onOpenMachineDetails:()=>E(`/machines/${le.id}`),onMachineUpgrade:()=>ge.handleMachineUpgrade(le.id),onLaunchDetectedIde:(Q,we)=>ge.handleLaunchDetectedIde(le.id,Q,we),onAddWorkspace:(Q,we)=>ge.handleAddWorkspace(le.id,Q,we),onBrowseDirectory:Q=>ge.handleBrowseDirectory(le.id,Q),onLaunchWorkspaceProvider:(Q,we,Ne)=>ge.handleLaunchWorkspaceProvider(le.id,Q,we,Ne),onListSavedSessions:Q=>ge.handleListSavedSessions(le.id,Q)}):s.jsx(Bh,{section:H,attentionItems:ue,unreadItems:ce,workingItems:je,completedItems:ae,hiddenConversations:t,machineCards:D,getAvatarText:tx,onOpenConversation:q.openConversation,onShowConversation:C,onShowAllHidden:I,onOpenNewSession:T,onOpenMachine:q.openMachine,onOpenSettings:()=>E("/settings"),onSectionChange:F,wsStatus:y,isConnected:g,isStandalone:c})})}function Rn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function rx({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[m,d]=o.useState(null),h=o.useCallback(()=>{c.current=0,u(!1),d(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const f=o.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),j=o.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!Rn(t,r)){d("merge");return}const y=x.currentTarget.getBoundingClientRect(),g=x.clientX-y.left,C=y.width/3;g<C?d("split-left"):g>C*2?d("split-right"):d("merge")},[t,r]),N=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),d(null))},[]),p=o.useCallback(x=>{c.current=0,u(!1);const y=x.dataTransfer.getData("text/tab-key"),g=y?e.some(I=>I.tabKey===y):!1,C=m;if(d(null),i(),!!y){if(x.preventDefault(),C==="split-left"&&Rn(t,r)){r==null||r(y,"split-left");return}if(C==="split-right"&&Rn(t,r)){r==null||r(y,"split-right");return}if(g){a(y);return}n==null||n(y)}},[e,m,t,r,n,a,i]);return{dragOver:l,dropAction:m,resetDragState:h,handleDragEnter:f,handleDragOver:j,handleDragLeave:N,handleDrop:p}}function nx(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 ax({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(t??null),[l,u]=o.useState(r??[]),[m,d]=o.useState(null),h=o.useRef(null),f=o.useRef(null),j=o.useRef(n),N=o.useRef(a);o.useEffect(()=>{j.current=n},[n]),o.useEffect(()=>{N.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{u(S=>{const k=nx(S,e);return k.length===S.length&&k.every((b,B)=>b===S[B])?S:k})},[e]);const p=o.useMemo(()=>{const S=m??l;if(S.length===0)return e;const k=new Map(S.map((b,B)=>[b,B]));return[...e].sort((b,B)=>{const L=k.get(b.tabKey)??999,_=k.get(B.tabKey)??999;return L-_})},[e,m,l]);o.useEffect(()=>{var k,b;if(p.length===0){i!==null&&(c(null),(k=j.current)==null||k.call(j,null));return}if(i&&p.some(B=>B.tabKey===i))return;const S=p[0].tabKey;S!==i&&(c(S),(b=j.current)==null||b.call(j,S))},[p,i]);const x=o.useMemo(()=>p.find(S=>S.tabKey===i),[p,i]),y=o.useCallback(S=>{var k;c(S),(k=j.current)==null||k.call(j,S)},[]),g=o.useCallback((S,k,b)=>{u(B=>{var F;const L=B.filter(O=>O!==S),_=L.indexOf(k);if(_<0)return B;const H=b==="left"?_:_+1;return L.splice(H,0,S),(F=N.current)==null||F.call(N,L),L}),d(null)},[]),C=o.useCallback((S,k,b)=>{const L=(l.length>0?l:e.map(F=>F.tabKey)).filter(F=>F!==S),_=L.indexOf(k);if(_<0)return;const H=b==="left"?_:_+1;L.splice(H,0,S),h.current=L,d(L)},[l,e]),I=o.useCallback(()=>{var k;const S=h.current;S&&(u(S),(k=N.current)==null||k.call(N,S))},[]),v=o.useCallback(()=>{h.current=null,d(null)},[]),T=o.useCallback(S=>{u(k=>{var B;const b=k.filter(L=>L!==S);return b.push(S),(B=N.current)==null||B.call(N,b),b})},[]);return{activeTabId:i,activeConv:x,sortedConversations:p,previewOrderRef:h,draggingTabRef:f,selectTab:y,handleTabReorder:g,updatePreviewOrder:C,commitPreviewOrder:I,clearPreviewOrder:v,moveTabToEnd:T,setDraggingTabKey:S=>{f.current=S}}}function ox({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,u=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?jc:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:u}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),l&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:i,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Dt,"aria-label":Dt,children:[s.jsx($i,{size:14}),s.jsx("span",{children:Dt})]})}),c&&s.jsx(el,{}),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 nl="adhdev-tab-shortcuts";function al(){try{return JSON.parse(localStorage.getItem(nl)||"{}")}catch{return{}}}function ol({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>al()),[l,u]=o.useState(null),m=o.useCallback(h=>{const f=[];return h.metaKey&&f.push(a?"⌘":"Meta"),h.ctrlKey&&f.push("Ctrl"),h.altKey&&f.push(a?"⌥":"Alt"),h.shiftKey&&f.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(f.push(h.key.length===1?h.key.toUpperCase():h.key),f.join("+"))},[a]),d=o.useCallback(h=>{c(h);try{localStorage.setItem(nl,JSON.stringify(h))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const h=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){u(null);return}const j=m(f);if(!j)return;const N={...i};for(const[p,x]of Object.entries(N))x===j&&delete N[p];N[l]=j,d(N),u(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,i,d,m]),o.useEffect(()=>{if(!e)return;const h=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[j,N]of Object.entries(i))if(t.includes(j)&&m(f)===N){f.preventDefault(),r(),n(j);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,i,t,r,n,m]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const _n=e=>{e.preventDefault()},ix=o.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:m,onConversationActivated:d,onPreviewReorder:h,onReorderTab:f,onCommitPreviewOrder:j,onClearPreviewOrder:N,onDragStateReset:p,onDragTabKeyChange:x,onReceiveTab:y,onOpenContextMenu:g,longPressTimer:C,isGroupActive:I}){const v=As(t),T=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",S=v.isReconnecting,k=o.useCallback(A=>{l.current=t.tabKey,x(t.tabKey),A.dataTransfer.setData("text/tab-key",t.tabKey),A.dataTransfer.effectAllowed="move"},[t.tabKey,l,x]),b=o.useCallback(()=>{l.current=null,x(null),j(),N(),p()},[l,x,j,N,p]),B=o.useCallback(A=>{const U=l.current;if(!(!U||U===t.tabKey)&&A.dataTransfer.types.includes("text/tab-key")){A.preventDefault(),A.stopPropagation();const $=A.currentTarget.getBoundingClientRect(),E=A.clientX<$.left+$.width/2?"left":"right";h(U,t.tabKey,E)}},[t.tabKey,l,h]),L=o.useCallback(A=>{A.preventDefault(),A.stopPropagation();const U=A.dataTransfer.getData("text/tab-key");if(U&&U!==t.tabKey){const $=A.currentTarget.getBoundingClientRect(),E=A.clientX<$.left+$.width/2?"left":"right";c.includes(U)?f(U,t.tabKey,E):y&&y(U)}N()},[t.tabKey,c,f,y,N]),_=o.useCallback(A=>{A.stopPropagation(),u(),m(t.tabKey),d(t)},[t,d,u,m]),H=o.useCallback(A=>{A.preventDefault(),g(A.clientX,A.clientY,t.tabKey)},[t.tabKey,g]),F=o.useCallback(A=>{const U=A.touches[0];C.current=setTimeout(()=>{g(U.clientX,U.clientY,t.tabKey)},600)},[t.tabKey,C,g]),O=o.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),M=["adhdev-dockview-tab",T,r&&"is-active",I&&"is-group-active",S&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:M,draggable:!0,onDragStart:k,onDragEnd:b,onDragOver:B,onDrop:L,onClick:_,onContextMenu:H,onTouchStart:F,onTouchEnd:O,onTouchMove:O,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:v.isGenerating?s.jsx("div",{className:"tab-spinner"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):S?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.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:at(t),children:at(t)}),s.jsx("span",{className:"adhdev-dockview-tab-meta",children:S?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Zt(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[Zt(t),s.jsx("span",{className:"connecting-dots"})]}):Zt(t)})]}),i&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function cx({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:j,onReceiveTab:N,onHideTab:p,isGroupActive:x,allowTabShortcuts:y=!0}){const[g,C]=o.useState(null),I=o.useRef(null),v=o.useRef(null),T=o.useMemo(()=>e.map(H=>H.tabKey),[e]);ar("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(g==null?void 0:g.tabKey)||null});const{isMac:S,tabShortcuts:k,shortcutListening:b,setShortcutListening:B,saveShortcuts:L}=ol({enabled:y,sortedTabKeys:e.map(H=>H.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!g)return;const H=F=>{const O=document.querySelector("[data-pane-context-menu]");O&&O.contains(F.target)||C(null)};return window.addEventListener("mousedown",H,!0),()=>window.removeEventListener("mousedown",H,!0)},[g]),o.useEffect(()=>{const H=v.current;if(!H)return;const F=O=>{Math.abs(O.deltaY)<=Math.abs(O.deltaX)||(O.preventDefault(),H.scrollLeft+=O.deltaY)};return H.addEventListener("wheel",F,{passive:!1}),()=>H.removeEventListener("wheel",F)},[]);const _=o.useCallback((H,F,O)=>{C({x:H,y:F,tabKey:O})},[]);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:v,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(H=>s.jsx(ix,{conv:H,isActive:t===H.tabKey,isDraggedTab:a.current===H.tabKey,isTaskCompleteUnread:n.has(H.tabKey),shortcut:y?k[H.tabKey]:void 0,conversationKeys:T,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:j,onReceiveTab:N,onOpenContextMenu:_,longPressTimer:I,isGroupActive:x},H.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),g&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:g.x,top:g.y},children:[y&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:_n,onClick:H=>{H.stopPropagation(),B(g.tabKey),C(null)},children:["⌨ ",k[g.tabKey]?`Change shortcut (${k[g.tabKey]})`:"Set shortcut"]}),k[g.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:_n,onClick:()=>{const H={...k};delete H[g.tabKey],L(H),C(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[y&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:_n,onClick:()=>{p(g.tabKey),C(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&b&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>B(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:H=>H.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. ",S?"⌘+1":"Ctrl+1",", ",S?"⌥+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 lx({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:u,groupIndex:m,onFocus:d,isSplitMode:h,numGroups:f,onMoveTab:j,onReceiveTab:N,style:p,onActiveTabChange:x,initialActiveTabId:y,initialTabOrder:g,onTabOrderChange:C,onHideTab:I,isFocused:v,allowTabShortcuts:T=!0,onOpenNewSession:S,liveSessionInboxState:k}){const{sendCommand:b}=wt(),B=o.useRef(null),{activeTabId:L,activeConv:_,sortedConversations:H,draggingTabRef:F,selectTab:O,handleTabReorder:M,updatePreviewOrder:A,commitPreviewOrder:U,clearPreviewOrder:$,moveTabToEnd:E,setDraggingTabKey:z}=ax({conversations:e,initialActiveTabId:y,initialTabOrder:g,onActiveTabChange:x,onTabOrderChange:C}),Y=on({sendDaemonCommand:a,activeConv:_,setActionLogs:i,isStandalone:c}),{dragOver:ve,dropAction:re,resetDragState:ye,handleDragEnter:le,handleDragOver:be,handleDragLeave:ge,handleDrop:G}=rx({conversations:e,numGroups:f,onMoveTab:j,onReceiveTab:N,onOwnTabDrop:E,onClearPreviewOrder:$}),ne=_&&!Ve(_)&&Ls(_)==="terminal",q=o.useMemo(()=>_?t.find(ae=>ae.id===_.routeId):void 0,[t,_]),ue=o.useMemo(()=>_?n.filter(ae=>ae.routeId===_.tabKey):[],[n,_]),ce=o.useMemo(()=>new Set(H.filter(ae=>Cu(ae,k,{isOpenConversation:ae.tabKey===L})).map(ae=>ae.tabKey)),[L,k,H]);ar("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:L,dragOver:ve});const je=o.useCallback(ae=>{ae.streamSource==="agent-stream"&&ae.agentType&&b(ae.routeId,Zc(),{agentType:ae.agentType,...ae.sessionId&&{targetSessionId:ae.sessionId}}).catch(()=>{})},[b]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...p,outline:ve?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(cx,{conversations:H,activeTabId:L,groupIndex:m,numGroups:f,unreadTabKeys:ce,draggingTabRef:F,onFocus:d,onSelectTab:O,onConversationActivated:je,onPreviewReorder:A,onReorderTab:M,onCommitPreviewOrder:U,onClearPreviewOrder:$,onDragStateReset:ye,onDragTabKeyChange:z,onMoveTab:j,onReceiveTab:N,onHideTab:I,isGroupActive:v??!1,allowTabShortcuts:T}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:le,onDragOver:be,onDragLeave:ge,onDrop:G,children:[ve&&s.jsx(ox,{dropAction:re,canSplit:!!(f<4&&j)}),_?s.jsx(Xa,{activeConv:_,clearToken:r[_.tabKey]||0,isCliTerminal:!!ne,ideEntry:q,terminalRef:B,handleModalButton:Y.handleModalButton,handleRelaunch:Y.handleRelaunch,handleSendChat:Y.handleSendChat,isSendingChat:Y.isSendingChat,sendFeedbackMessage:Y.sendFeedbackMessage,handleFocusAgent:Y.handleFocusAgent,isFocusingAgent:Y.isFocusingAgent,actionLogs:ue,userName:u,isInputActive:!h||!!v}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Qa,{conversationsCount:e.length,isSplitMode:h,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:S})})]})]})}function dx({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:m,isStandalone:d,hasRegisteredMachines:h,userName:f,focusedGroup:j,focusGroup:N,moveTabToGroup:p,splitTabRelative:x,closeGroup:y,handleResizeStart:g,groupActiveTabIds:C,setGroupActiveTab:I,groupTabOrders:v,setGroupTabOrder:T,toggleHiddenTab:S,onOpenNewSession:k,allowTabShortcuts:b=!0,liveSessionInboxState:B}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((L,_)=>{const H=t&&n.length===r?`${n[_]}%`:void 0;return s.jsxs(jt.Fragment,{children:[t&&_>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:F=>g(_-1,F),onDoubleClick:()=>y(_),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(lx,{style:t?{flexBasis:H??`${100/r}%`,flexGrow:H?0:1,flexShrink:H?0:1}:void 0,conversations:L,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:m,isStandalone:d,hasRegisteredMachines:h,userName:f,groupIndex:_,isFocused:t&&j===_,onFocus:()=>N(_),isSplitMode:t,numGroups:r,onMoveTab:(F,O)=>{O==="left"&&_>0?p(F,_-1):O==="right"&&_<r-1?p(F,_+1):O==="split-left"&&r<4?x(F,_,"left"):O==="split-right"&&r<4&&x(F,_,"right")},onReceiveTab:F=>p(F,_),onActiveTabChange:F=>I(_,F),initialActiveTabId:C[_],initialTabOrder:v[_],onTabOrderChange:F=>T(_,F),onHideTab:S,onOpenNewSession:k,allowTabShortcuts:b,liveSessionInboxState:B})]},_)})})}function il({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?lt.onScreenshot("ide-page",(d,h)=>{if(d!==e)return;const f=new FileReader;f.onload=()=>i(f.result),f.readAsDataURL(h)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var d;return e?((d=lt.onStatus)==null?void 0:d.call(lt,(h,f)=>{h===e&&f!=null&&f.screenshotUsage&&l(f.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,t]),o.useEffect(()=>{const m=e?lt.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&t?m.startScreenshots(t):m.stopScreenshots(t),()=>{m.stopScreenshots(t)}},[n,r,t,e]);const u=o.useCallback(async(m,d)=>{const h=e?lt.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(m,d,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const cl="adhdev-dashboard-action-shortcuts",ux=1200,mx={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function fx(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function st(e,t){switch(e){case"openShortcutHelp":return"?";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return t?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return t?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return t?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return t?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return t?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return t?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return t?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return t?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return t?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return t?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function ll(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:st("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:st("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:st("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:st("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:st("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:st("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:st("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:st("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:st("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:st("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:st("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:st("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:st("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:st("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:st("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:st("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:st("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:st("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:st("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:st("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:st("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:st("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:st("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:st("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:st("toggleCliView",e)}]}function fa(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function qr(e){const t=Object.fromEntries(ll(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(cl)||"{}"),n={...t,...r};for(const[a,i]of Object.entries(mx))n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function dl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function px({enabled:e=!0,onTrigger:t}){const r=fx(),[n,a]=o.useState(()=>qr(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),m=o.useRef({parts:[],timer:null}),d=o.useCallback(p=>{const x=[];return p.metaKey&&x.push(r?"⌘":"Meta"),p.ctrlKey&&x.push("Ctrl"),p.altKey&&x.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&x.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(x.push(dl(p.key)),x.join("+"))},[r]),h=o.useCallback(p=>{a(p);try{localStorage.setItem(cl,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=qr(r),x=Object.entries(n),y=Object.entries(p);x.length===y.length&&x.every(([g,C])=>p[g]===C)||h(p)},[n,r,h]);const f=o.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),j=o.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},ux))},[]);o.useEffect(()=>{if(!i)return;const p=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){c(null),u([]);return}const y=d(x);if(!y)return;const C=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(y);if(l.length===0&&C){u([y]);return}const v=[...l,y].slice(0,2).join(" "),T={...n};for(const[S,k]of Object.entries(T))k===v&&delete T[S];T[i]=v,h(T),c(null),u([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,d,h,i,l]),o.useEffect(()=>{if(!e||i)return;const p=x=>{if(x.defaultPrevented)return;const y=d(x);if(!y)return;const g=x.metaKey||x.ctrlKey||x.altKey;if(fa(x.target)&&!g)return;const C=m.current.parts,I=g?[y]:[...C.slice(-1),y].slice(-2),v=I.join(" "),T=I[I.length-1],S=Object.entries(n).filter(([,_])=>!!_),k=S.find(([,_])=>_===v);if(k){x.preventDefault(),f(),t(k[0]);return}if(S.some(([,_])=>_.startsWith(`${v} `))){x.preventDefault(),m.current.parts=I,j();return}const B=S.find(([,_])=>_===T);if(B){x.preventDefault(),f(),t(B[0]);return}if(S.some(([,_])=>_.startsWith(`${T} `))){x.preventDefault(),m.current.parts=[T],j();return}f()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,j,e,d,t,f,i]),o.useEffect(()=>()=>f(),[f]);const N=o.useMemo(()=>ll(r),[r]);return{isMac:r,actionDefinitions:N,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:h}}function hx({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 ul(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?!ul(n):!0}function xx({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:ul(r)}const ml=500;function bx({detachDelayMs:e=ml,onDetach:t,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:n=globalThis.clearTimeout.bind(globalThis)}){let a=null,i=null,c=null,l=!1;const u=()=>{c!=null&&(n(c),c=null)},m=()=>{u(),a=null,i=null,l=!1},d=()=>{!a||!i||l||c!=null||(c=r(()=>{c=null,!(!a||!i||l)&&(l=!0,t({panelId:a,clientX:i.clientX,clientY:i.clientY}))},e))};return{startDrag:h=>{u(),a=h.panelId,i={clientX:h.clientX,clientY:h.clientY},l=!1},markNoDropTarget:h=>{!a||l||(i={clientX:h.clientX,clientY:h.clientY},d())},markDockTarget:h=>{!a||l||(h&&(i={clientX:h.clientX,clientY:h.clientY}),u())},endDrag:m,isDragging:()=>a!=null,hasDetached:()=>l,dispose:m}}function gx(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}const fl=o.createContext(null);function ln(){const e=o.useContext(fl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function _r(e){return at(e)||e.tabKey}function yx(e){return`remote:${e}`}function At(e){return e.startsWith("remote:")}function ri(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function vx(e){e.preventDefault()}function Pn(e){var n;const t=e==null?void 0:e.defaultView;if(!t)return;const r=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),r(e==null?void 0:e.body),r(e==null?void 0:e.documentElement),(n=t.requestAnimationFrame)==null||n.call(t,()=>{try{t.focus(),r(e==null?void 0:e.body)}catch{}})}catch{}}function Dn(e,t){e.classList.remove(qn.className,Yn.className),e.classList.add(t==="light"?qn.className:Yn.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 wx(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 jx(e,t,r){var c;const n=[t];let a;for(const l of n){let u;for(const m of l){const d=e.addPanel({id:m.tabKey,component:"conversation",title:_r(m),params:{kind:"conversation",tabKey:m.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return r??((c=t[0])==null?void 0:c.tabKey)??null}function ai(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])At(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==_r(n)&&a.api.setTitle(_r(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:_r(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function oi(e,t,r){var u,m;const n=r?yx(r):null;for(const d of[...e.panels])At(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=_t(t,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=wc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((m=e.panels.find(d=>!At(d.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function kx({params:e,api:t}){var h;const r=ln(),n=o.useRef(null),[a,i]=o.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=on({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(t.isActive);const f=[t.onDidActiveChange(j=>i(j.isActive)),t.onDidActiveGroupChange(j=>{if(!t.isActive&&!j.isActive){i(!1);return}i(t.isActive)})];return()=>{for(const j of f)j.dispose()}},[t]);const u=o.useMemo(()=>c?r.ides.find(f=>f.id===c.routeId):void 0,[r.ides,c]),m=o.useMemo(()=>c?r.actionLogs.filter(f=>f.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(Qa,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const d=!Ve(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(Xa,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:d,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:m,userName:r.userName,scrollToBottomRequestNonce:((h=r.scrollToBottomRequest)==null?void 0:h.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:a})})}function Sx({params:e}){var u;const t=ln(),r=o.useMemo(()=>_t([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=il({doId:a,targetSessionId:r?oc(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(Fi,{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 Nx(){const e=ln();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Qa,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Cx(e){var j,N;wx(e);const t=ln(),r=o.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=_t([...t.conversationsByTabKey.values()],e.params.routeId),x=((j=e.api.group.activePanel)==null?void 0:j.id)===e.api.id,y=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${x?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((N=e.api.group.activePanel)==null?void 0:N.id)===e.api.id,i=e.api.isGroupActive,c=Zr(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,u=c.isConnecting,m=c.isGenerating,d=c.isWaiting,h=c.unread,f=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:at(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var x;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((x=p.target)==null?void 0:x.ownerDocument)??document})},children:[h&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?s.jsx("div",{className:"tab-spinner"}):d?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):u?s.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:at(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Zt(n)}):u?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Zt(n)}):s.jsx("span",{children:Zt(n)})})]}),f&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:f,children:f})]})}function Mx({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:u,userName:m,toggleHiddenTab:d,actionShortcuts:h,registerActionHandlers:f,onActiveTabChange:j,onOpenNewSession:N,onRequestScrollToBottom:p,requestedActiveTabKey:x,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:g,scrollToBottomRequest:C,liveSessionInboxState:I,layoutProfile:v}){var Xe,ot,ft;const{theme:T}=Fa(),{sendCommand:S}=wt(),k=o.useRef(null),b=o.useRef(null),B=o.useRef(null),L=o.useRef(!1),_=o.useRef(!1),H=o.useRef(!1),F=o.useRef(null),O=o.useRef([]),[M,A]=o.useState(null),[U,$]=o.useState(0),E=o.useRef(typeof window>"u"?{}:Xp(v)),z=o.useMemo(()=>new Map(e.map(W=>[W.tabKey,W])),[e]),Y=o.useMemo(()=>{const W=k.current;return W?W.groups.some(w=>{try{const R=w.model.location.type;return R!=="floating"&&R!=="popout"?!1:w.panels.some(P=>z.has(P.id))}catch{return!1}}):!1},[z,U,e]),ve=o.useCallback(()=>{var W;(W=k.current)==null||W.focus()},[]),re=o.useCallback((W,w)=>{p==null||p(W,w)},[p]),ye=o.useCallback(W=>{const w=document,R=W.document;for(const he of w.querySelectorAll('link[rel="stylesheet"]')){const Se=R.createElement("link");Se.rel="stylesheet",Se.href=he.href,he.crossOrigin&&(Se.crossOrigin=he.crossOrigin),R.head.appendChild(Se)}for(const he of w.querySelectorAll("style")){const Se=R.createElement("style");Se.textContent=he.textContent,R.head.appendChild(Se)}const P=[];for(const he of w.styleSheets)try{for(const Se of he.cssRules)Se instanceof CSSStyleRule&&(Se.selectorText===":root"||Se.selectorText==="html")&&P.push(Se.cssText)}catch{}if(P.length>0){const he=R.createElement("style");he.textContent=P.join(`
|
|
43
|
-
`),R.head.appendChild(he)}const V=w.documentElement.getAttribute("data-theme");V&&R.documentElement.setAttribute("data-theme",V),R.documentElement.style.colorScheme=V==="light"?"light":"dark",R.body.className=w.body.className;const Z=w.documentElement.getAttribute("style");Z&&R.documentElement.setAttribute("style",Z);const me=R.getElementById("dv-popout-window");me instanceof HTMLElement&&(me.classList.add("adhdev-dockview"),Dn(me,
|
|
42
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:b,onCancel:()=>d(null)})]})}const op=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function ip(){const{preference:e,setPreference:t}=Fa();return s.jsx("div",{className:"flex gap-2",children:op.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 cp(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 lp(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Sn(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Bo(e){const{r:t,g:r,b:n}=lp(e);return .2126*Sn(t)+.7152*Sn(r)+.0722*Sn(n)}function Ko(e,t){const r=Bo(e),n=Bo(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Ec(e){const t=cp(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Ko(t,r)>=Ko(t,n)?r:n}const da={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},ua={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},dp=[{id:"midnight",name:"Midnight",description:"Classic violet theme",preview:{dark:{userBubble:"#8b5cf6",assistantBubble:"#18181d",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0f0f13",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#7c3aed",assistantBubble:"#ffffff",assistantBorder:"1px solid rgba(0,0,0,0.08)",containerBg:"#f0f1f5",textColor:"#52525b"}}},{id:"ember",name:"Ember",description:"Default landing-inspired amber theme",preview:{dark:{userBubble:"#f59e0b",assistantBubble:"#111726",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0a0e1a",textColor:"#9ca3af"},light:{userBubble:"#f59e0b",assistantBubble:"#fffaf4",assistantBorder:"1px solid rgba(146,64,14,0.10)",containerBg:"#fff8ee",textColor:"#6f6255"}}},{id:"aurora",name:"Aurora",description:"Pink accent theme",preview:{dark:{userBubble:"#ec4899",assistantBubble:"#1e1b2e",assistantBorder:"1px solid rgba(236,72,153,0.12)",containerBg:"#0f0d17",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#ec4899",assistantBubble:"#fef2f8",assistantBorder:"1px solid rgba(236,72,153,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}},{id:"honey",name:"Honey",description:"Warm yellow accents",preview:{dark:{userBubble:"#fbbf24",assistantBubble:"#1c1c1e",assistantBorder:"1px solid rgba(255,255,255,0.06)",containerBg:"#111113",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#fbbf24",assistantBubble:"#fffbeb",assistantBorder:"1px solid rgba(251,191,36,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}}],$c="adhdev-chat-theme",Bc="adhdev-chat-theme-custom";function Ar(){if(typeof window>"u")return"ember";try{return localStorage.getItem($c)||"ember"}catch{return"ember"}}function Rt(e){try{const t=localStorage.getItem(Bc);if(t){const r=JSON.parse(t);return{...e==="dark"?da:ua,...r[e]}}}catch{}return e==="dark"?da:ua}function yr(e,t){try{localStorage.setItem(Bc,JSON.stringify({dark:e,light:t}))}catch{}}function Nt(e,t){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${t})`}function Gr(e,t){const r=Math.min(255,parseInt(e.slice(1,3),16)+t),n=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const up={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Ys(e,t){var a;const r=(a=up[e])==null?void 0:a[t];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Gr(r,24)),n.style.setProperty("--accent-on-primary",Ec(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Gr(r,18)})`),n.style.setProperty("--border-accent",Nt(r,.35)),n.style.setProperty("--nav-active-bg",Nt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Nt(r,.06)}`)}function ss(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Nt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Nt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Nt(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",Nt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Nt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Gr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Ec(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Gr(e.accentColor,40)})`),t.style.setProperty("--border-accent",Nt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Nt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Nt(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${Nt(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function Ua(){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 mp(e){try{localStorage.setItem($c,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=rs()?"dark":"light";ss(Rt(t))}else Ua(),Ys(e,rs()?"dark":"light")}function fp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Ar();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=rs()?"dark":"light";ss(Rt(t))}else Ua(),Ys(e,rs()?"dark":"light")}function rs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function xt({label:e,value:t,onChange:r}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Bs({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function pp({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=o.useState(()=>Rt(r));o.useEffect(()=>{a(Rt(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const m={...u,[c]:l},h=Rt(r==="dark"?"light":"dark");return r==="dark"?yr(m,h):yr(h,m),ss(m),t(m),m})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",s.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(Bs,{title:"App Background",children:[s.jsx(xt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(xt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(xt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Bs,{title:"App Text",children:[s.jsx(xt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(xt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(xt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Bs,{title:"Borders & Accent",children:[s.jsx(xt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(xt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(xt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Bs,{title:"Chat Bubbles",children:[s.jsx(xt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(xt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(xt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(xt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Bs,{title:"Chat Layout",children:[s.jsx(xt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(xt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(xt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?da:ua,u=Rt(e?"light":"dark");e?yr(c,u):yr(u,c),a(c),ss(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function hp(){const[e,t]=o.useState(Ar),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Rt("dark"));o.useEffect(()=>{n(rs());const u=new MutationObserver(()=>{const h=rs();n(h);const f=Ar();f==="custom"?ss(Rt(h?"dark":"light")):Ys(f,h?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const h=rs();n(h);const f=Ar();f==="custom"?ss(Rt(h?"dark":"light")):Ys(f,h?"dark":"light")};return m.addEventListener("change",d),()=>{u.disconnect(),m.removeEventListener("change",d)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ss(Rt(r?"dark":"light")):(Ua(),Ys(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Rt(r?"dark":"light"))},[r]);const c=u=>{t(u),mp(u)},l=[...dp,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const m=e===u.id,d=r?u.preview.dark:u.preview.light,h=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:d.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.userBubble,color:h},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[m&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&s.jsx(pp,{dark:r,onColorsChange:u=>i(u)})]})}const za="adhdev_mobileDashboardMode_v1",ma="adhdev:mobile-dashboard-mode-change";function Va(){try{return localStorage.getItem(za)==="workspace"?"workspace":"chat"}catch{return"chat"}}function xp(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Va())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==za||t()};return window.addEventListener(ma,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ma,r),window.removeEventListener("storage",n)}}function bp(e){try{localStorage.setItem(za,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ma,{detail:e}))}function gp(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(Va()==="chat")},[]),s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Wt,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{t(r),bp(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Nn=new Map,Oo=new Map;function yp(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 vp(e,t,r,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n,platform:r.platform,machine:r}}function Kc(){const{sendCommand:e}=wt(),{injectEntries:t,getIdes:r}=Qs();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??Lm,c=Oo.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=Nn.get(n);if(l)return l;const u=(async()=>{const m=await e(n,"get_machine_runtime_stats"),d=yp(m);if(!d)return;const h=r().find(j=>j.id===n),f=vp(h,n,d.machine,d.timestamp||Date.now());t([f]),Oo.set(n,Date.now())})().finally(()=>{Nn.delete(n)});return Nn.set(n,u),u},[r,t,e])}function wp(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 jp(e,t){const{sendData:r}=wt(),{injectEntries:n,getIdes:a}=Qs(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>Vt.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const h=a().find(j=>j.id===u),f=wp(h,u,d);n([f])}));return()=>{l.forEach(u=>u())}},[i,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function kp(e,t){const{sendData:r}=wt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(t!=null&&t.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const u=Vt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},m=>{l&&(clearTimeout(l),l=null),a(m.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},Dm):c(!1),()=>{l&&clearTimeout(l),u()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:a}}function Sp(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Oc(e){const{sendData:t}=wt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=Sp(e);if(!a||!e.sessionId||!t){n({});return}const i=Vt.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),js.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return i.initialSendAccepted||n({}),()=>{i()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const Wc="adhdev_hiddenTabs";function Np(){try{const e=localStorage.getItem(Wc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function fs(e){try{localStorage.setItem(Wc,JSON.stringify([...e]))}catch{}}function Cn(e){return La(e)}function Ga(e,t){return vs(t).some(r=>e.has(r))}function Cp(){const[e,t]=o.useState(Np),r=o.useCallback(m=>{const d=Cn(m);t(h=>{const f=new Set(h);return f.has(d)?f.delete(d):f.add(d),fs(f),f})},[]),n=o.useCallback(m=>{const d=Cn(m);t(h=>{if(h.has(d))return h;const f=new Set(h);return f.add(d),fs(f),f})},[]),a=o.useCallback(m=>{const d=Cn(m);t(h=>{if(!h.has(d))return h;const f=new Set(h);return f.delete(d),fs(f),f})},[]),i=o.useCallback(()=>{t(m=>{if(m.size===0)return m;const d=new Set;return fs(d),d})},[]),c=o.useCallback((m,d)=>{t(h=>{const f=new Set(h);for(const j of d)f.add(j);return fs(f),f})},[]),l=o.useCallback((m,d)=>{t(h=>{const f=new Set(h);for(const j of d)f.delete(j);return fs(f),f})},[]),u=o.useCallback(m=>Ga(e,m),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Hc(e){return e instanceof Error?e.message:String(e||"")}function Fc(e){const t=Hc(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function Uc(e){const t=Hc(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function zc({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Qe(e)||Ve(e))return;const i=Ls(e);if(i===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(ms(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:$t(e),mode:t})}catch(l){const u=Uc(l);c&&!u&&a(m=>{const d={...m};return i===Vc(r,c)?delete d[c]:d[c]=i,d}),Fc(l)?console.warn(u?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function Wo(e,t){const r=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!r||e.transport!=="pty")return e;const n=t[r];return!n||e.mode===n?e:{...e,mode:n}}function Tp(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let r=!1;const n=e.map(a=>{const i=Wo(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>Wo(u,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Vc(e,t){if(!t)return null;for(const r of e){if(r.sessionId===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function Mp(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))Vc(t,a)===i&&(delete n[a],r=!0);return r?n:e}function Ip({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Ji()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:yc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return qu(a),o.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),m={};for(const[d,h]of Object.entries(l))u-h<5e3&&(m[d]=h);return Object.keys(m).length===Object.keys(l).length?l:m})},5500);return()=>clearTimeout(c)},[t,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(m=>m.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function Ap(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const i=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function Tn(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Lp(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Ho(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Lp(ks(r.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((r==null?void 0:r.id)||""),String((r==null?void 0:r.index)??""),String((r==null?void 0:r.receivedAt)??(r==null?void 0:r.timestamp)??""),n].join(":")}function Rp(e){const t=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),Ho(e.activeChat),...t.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastMessageAt||""),r.lastMessagePreview||"",r.lastMessageRole||"",String(r.lastUpdated||""),Ho(r.activeChat)].join(":"))].join("|")}function _p(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 Pp(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const i of vs({routeId:n.routeId}))r.set(i,a);for(const i of vs({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of vs({tabKey:n.tabKey}))r.set(i,n)}return r}function Dp(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Ep(e){const t=Dp(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const r=String(t.role||""),n=ks(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function $p({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>Ap(e),[e]),i=o.useMemo(()=>Cc(e),[e]),c=o.useRef([]),l=o.useRef([]),u=o.useRef([]),m=o.useRef(new Map),d=o.useRef(new Map),h=o.useMemo(()=>{const I=new Map,v=[];for(const b of a){const{connectionState:B="new",machineName:L}=Tc(b,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),_=Rp(b),H=m.current.get(b.id);if(H&&H.ide===b&&H.sourceSignature===_&&H.connectionState===B&&H.machineName===L){I.set(b.id,H),v.push(...H.conversations);continue}const F=Ha(b,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),O={ide:b,sourceSignature:_,connectionState:B,machineName:L,conversations:F};I.set(b.id,O),v.push(...F)}m.current=I;const M=new Map,S=b=>{const B=Ep(b),L=d.current.get(b.tabKey);if(L&&L.signature===B)return M.set(b.tabKey,L),L.timestamp;const _={signature:B,timestamp:ic(b)||(L==null?void 0:L.timestamp)||0};return M.set(b.tabKey,_),_.timestamp},k=[...v].sort((b,B)=>cc(b,B,S));return d.current=M,k},[a,t,i]),f=o.useMemo(()=>{const I=_p(h,r);return Tn(c.current,I)?c.current:(c.current=I,I)},[h,r]),j=o.useMemo(()=>{const I=new Map,v=Array.from(new Set(f.map(M=>M.routeId)));for(const M of v){const S=_t(f,M);S&&I.set(M,S)}return I},[f]),N=o.useMemo(()=>{const I=new Map;for(const v of f){const M=j.get(v.routeId),S=v.streamSource==="native"&&M?M:v;for(const k of vs({providerSessionId:v.providerSessionId,sessionId:v.sessionId}))I.set(k,S)}return I},[f,j]),p=o.useMemo(()=>Pp(f,j),[f,j]),x=o.useCallback(I=>{if(I)return N.get(I)},[N]),y=o.useCallback(I=>{if(I)return p.get(I)},[p]),g=o.useMemo(()=>{const I=f.filter(v=>!Ga(n,v));return Tn(l.current,I)?l.current:(l.current=I,I)},[f,n]),C=o.useMemo(()=>{const I=g.map(v=>v.tabKey);return Tn(u.current,I)?u.current:(u.current=I,I)},[g]);return{chatIdes:a,conversations:f,visibleConversations:g,visibleTabKeys:C,resolveConversationBySessionId:x,resolveConversationByTarget:y}}function Bp({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),i=o.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=o.useCallback(()=>{t&&n(l=>{const u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Kp({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{it.setIdes(e)},[e]),o.useEffect(()=>{it.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),o.useEffect(()=>{const a=it.onToast(i=>{r(l=>l.some(m=>m.message===i.message&&i.timestamp-m.timestamp<3e3)?l:[...l.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions}]);const c=i.duration||5e3;setTimeout(()=>r(l=>l.filter(u=>u.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=xc.on("status_event",i=>{it.handleRawEvent(i,"ws")});return()=>{a()}},[]),o.useEffect(()=>{var i;const a=c=>{var p;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const u=l.targetSessionId||l.targetKey||l.daemonId,m=n(u),d=(m==null?void 0:m.routeId)||l.daemonId;if(!d)return;const h=Number(l.buttonIndex),f=l.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[h])||"Approve",j=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(j);t(d,"resolve_action",{action:N?"approve":"reject",button:f,...Number.isFinite(h)&&{buttonIndex:h},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};return(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,t])}const Op="adhdev_dashboardLayout_v1",Wp="adhdev_dashboardDockview_v1",Hp="adhdev_dashboardDockviewHiddenRestore_v1",Ks={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function qa(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Fp(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Gc(e){return`${Op}:${e}`}function Up(e){const t=Gc(e);return qa(t,null)}function zp(e,t){try{const r=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,n=Gc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function qc(e){return`${Wp}:${e}`}function Vp(e){const t=qc(e);return qa(t,null)}function Gp(e,t){try{const r=qc(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Yc(e){return`${Hp}:${e}`}function qp(e){const t=Yc(e);return qa(t,{})}function Yp(e,t){try{const r=Yc(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Xp(){return{groupAssignments:[...Ks.groupAssignments],focusedGroup:Ks.focusedGroup,groupActiveTabIds:{...Ks.groupActiveTabIds},groupTabOrders:{...Ks.groupTabOrders},groupSizes:[...Ks.groupSizes]}}function Jp(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Qp(){const[e]=o.useState(()=>Fp(typeof window<"u"?window.innerWidth:1280)),[t,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[m,d]=o.useState([]),[h,f]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[j,N]=o.useState(!1),p=o.useCallback(()=>{if(j)return;const b=Up(e)??Xp();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),u(b.groupTabOrders),d(b.groupSizes),N(!0)},[j,e]);o.useEffect(()=>{j&&zp(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:m})},[j,e,t,n,i,l,m]),o.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),B=L=>f(L.matches);return b.addEventListener("change",B),()=>b.removeEventListener("change",B)},[]);const x=o.useCallback(b=>{r(b)},[]),y=o.useCallback(b=>{a(b)},[]),g=o.useCallback(b=>{c(b)},[]),C=o.useCallback(b=>{u(b)},[]),I=o.useCallback(b=>{d(b)},[]),v=o.useCallback(b=>{y(b)},[y]),M=o.useCallback((b,B)=>{c(L=>(L[b]??null)===(B??null)?L:{...L,[b]:B})},[]),S=o.useCallback((b,B)=>{u(L=>{const _=L[b];return Jp(_,B)?L:{...L,[b]:B}})},[]),k=o.useCallback((b,B)=>{const L=B.get(b)??0;return M(L,b),v(L),L},[v,M]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:n,updateFocusedGroup:y,focusGroup:v,groupActiveTabIds:i,updateGroupActiveTabIds:g,setGroupActiveTab:M,groupTabOrders:l,updateGroupTabOrders:C,setGroupTabOrder:S,groupSizes:m,updateGroupSizes:I,isMobile:h,hasHydratedStoredLayout:j,hydrateStoredLayout:p,focusConversationTab:k}}function Zp(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Aa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function eh({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:u,activeConv:m,isRefreshingHistory:d,ides:h,handleRefreshHistory:f}){const j=o.useRef(!1),N=o.useRef(!1),p=o.useRef(null),x=o.useRef(!1);o.useEffect(()=>{if(!e||j.current||t.length===0)return;if(!a){i();return}const y=r(e);y&&(c(y.tabKey,n),j.current=!0,N.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(g=>{const C=new URLSearchParams(g);return C.delete("activeTab"),C},{replace:!0}))},[e,t,r,n,a,i,c,l]),o.useEffect(()=>{if(!(N.current||a)&&t.length!==0){if(!e){i(),N.current=!0;return}if(j.current){N.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(N.current||a)&&(i(),N.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,i]),o.useEffect(()=>{if(!u){x.current=!1;return}if(!m||x.current||d)return;const y=h.find(g=>g.id===m.routeId);y&&(!y.chats||y.chats.length===0||Zp(y.chats,m))&&(x.current=!0,f())},[u,m,d,h,f])}function Mn(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=Aa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Xc({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[u,m]=o.useState(!1),d=o.useCallback(async N=>{try{await e("standalone","launch_ide",{ideType:N,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=o.useCallback(async(N,p)=>{try{const x=N||(t==null?void 0:t.daemonId)||"",y=await e(x,"switch_chat",{id:p,sessionId:p,...ws(t)}),g=y==null?void 0:y.result;if((y==null?void 0:y.success)===!0||g==="switched"||g==="switched-by-title")return;g===!1||g==="not_found"?$s(a,"⚠️ Session tab not found — try refreshing history"):typeof g=="string"&&g.startsWith("error:")?$s(a,`⚠️ Switch error: ${g}`):$s(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),$s(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,a]),f=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const N=sr(t);await e(N,"new_chat",{...ws(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(N){console.error("New chat failed",N)}finally{l(!1)}}},[t,c,e,i]),j=o.useCallback(async()=>{var N,p;if(!(!t||u)){m(!0);try{const x=sr(t),y=async()=>e(x,"list_chats",{forceExpand:!0,...ws(t)});let g=await y(),C=(g==null?void 0:g.chats)||((N=g==null?void 0:g.result)==null?void 0:N.chats);Mn(C,t)&&(await new Promise(I=>setTimeout(I,450)),g=await y(),C=(g==null?void 0:g.chats)||((p=g==null?void 0:g.result)==null?void 0:p.chats)),g!=null&&g.success&&Array.isArray(C)&&(n(t.routeId,C),Mn(C,t)&&!Mn(r,t)&&$s(a,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{m(!1)}}},[t,r,u,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:h,handleNewChat:f,handleRefreshHistory:j}}function th(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 sh(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Fo(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length!==n.length?!1:r.every(a=>t[Number(a)]===e[Number(a)])}function vr(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const u=a[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function Uo(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=t[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function rh(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 nh(e,t,r){if(t.length<=1)return[];const n=t.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===t.length?n:Array(r).fill(100/r),i=a.reduce((c,l)=>c+l,0);return i>0?a.map(c=>c/i*100):Array(r).fill(100/r)}function zo(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=t?i+1:i]=a}return r}function Vo(e){return Array(e).fill(100/e)}function ah({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:m}){const d=o.useRef(null),h=o.useMemo(()=>vr(e,m),[e,m]),f=h.assignments,j=o.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),N=j>1,p=o.useCallback((v,M)=>{t(S=>{const k=new Map(vr(S,m).assignments);return M===0?k.delete(v):k.set(v,M),k}),n(S=>({...S,[M]:v})),r(M)},[t,m,n,r]),x=o.useCallback(v=>{t(M=>{const S=vr(M,m).assignments,k=new Map;for(const[b,B]of S)B!==v&&(B>v?k.set(b,B-1):k.set(b,B));return k}),c(M=>{if(M.length<=1)return[];const S=[...M];S.splice(v,1);const k=S.reduce((b,B)=>b+B,0);return k>0?S.map(b=>b/k*100):[]}),r(0)},[t,m,c,r]),y=o.useCallback((v,M)=>{M.preventDefault();const S=d.current;if(!S)return;const k=M.clientX,b=S.offsetWidth,B=i.length===j?[...i]:Vo(j),L=H=>{const O=(H.clientX-k)/b*100,T=[...B];T[v]=Math.max(15,B[v]+O),T[v+1]=Math.max(15,B[v+1]-O),c(T)},_=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",_),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",_)},[i,j,c]),g=o.useCallback((v,M,S)=>{if(j>=4)return;const k=S==="left"?M:M+1;t(b=>{const B=vr(b,m).assignments,L=new Map;for(const _ of u){const H=B.get(_.tabKey)??0,F=H>=k?H+1:H;F>0&&L.set(_.tabKey,F)}return k>0&&L.set(v,k),L}),c(b=>{const B=b.length===j?[...b]:Vo(j),L=B[M]??100/j,_=Math.max(15,L/2),H=Math.max(15,L/2),F=[...B];F[M]=_,F.splice(k,0,H);const O=F.reduce((T,A)=>T+A,0);return F.map(T=>T/O*100)}),n(b=>{const B=zo(b,k);return B[k]=v,B}),a(b=>{const B=zo(b,k);return B[k]=[v],B}),r(k)},[j,t,m,u,c,n,a,r]);o.useEffect(()=>{th(e,f)||t(f)},[e,f,t]),o.useEffect(()=>{const{mapping:v,usedGroups:M}=h;n(S=>{const k=Uo(S,v);return Fo(S,k)?S:k}),a(S=>{const k=Uo(S,v);return Fo(S,k)?S:k}),r(S=>{const k=l?0:rh(S,M,v);return S===k?S:k}),c(S=>{const k=l?[]:nh(S,M,h.groupCount);return sh(S,k)?S:k})},[h,l,n,a,r,c]);const C=o.useMemo(()=>{const v=Array.from({length:j},()=>[]);for(const M of u){const S=f.get(M.tabKey)??0,k=Math.min(S,j-1);v[k].push(M)}return v},[u,f,j]),I=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:d,normalizedGroupAssignments:f,numGroups:j,isSplitMode:N,groupedConvs:C,moveTabToGroup:p,closeGroup:x,handleResizeStart:y,splitTabRelative:g,clearAllSplits:I}}function oh({ides:e,sendDaemonCommand:t}){const r="0.9.46",n=o.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:Dc(d,r)).sort((d,h)=>Number(qs(h,r))-Number(qs(d,r))),[r,e]),a=o.useMemo(()=>n.some(d=>qs(d,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),m=o.useCallback(async d=>{var h,f;u(j=>({...j,[d]:"upgrading"}));try{const j=await t(d,"daemon_upgrade",{});(h=j==null?void 0:j.result)!=null&&h.upgraded||(f=j==null?void 0:j.result)!=null&&f.success?u(N=>({...N,[d]:"done"})):u(N=>({...N,[d]:"error"}))}catch{u(j=>({...j,[d]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:m}}const Jc=80;function Lr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function ih(e){return{...e,createdAt:Lr(e.createdAt),updatedAt:Lr(e.updatedAt,e.createdAt),lastEventAt:Lr(e.lastEventAt,e.updatedAt||e.createdAt)}}function ch(e){const t=La(e);return t==="unknown:"?e.id:t}function lh(e){return[e.type,oc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function dh(e,t=Jc){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=ch(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 uh(e,t){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?t.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=Zr(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const u=Lr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),m=lh({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(ih({id:m,dedupKey:m,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:sc(a),preview:bm(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return dh(n)}function mh(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function fh(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Jc}=e,a=o.useMemo(()=>uh(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>mh(a),[a]);return{notifications:a,unreadCount:i}}function ph({notifications:e,sendDaemonCommand:t}){const r=o.useCallback(i=>{const c=e.find(u=>u.id===i),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,t]),n=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}function rn(...e){const t=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();t.has(c)||(t.add(c),r.push(i))};for(const a of e){if(Array.isArray(a)){for(const i of a)n(i);continue}n(a)}return r}function hh(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const r=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function nn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=hh(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 xh(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 bh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function an(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=bh(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.includes("\\")?"\\":"/",l=(m,d)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${d}`:m==="/"||m==="\\"?`${c}${d}`:`${m.replace(/[\\/]+$/,"")}${c}${d}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:typeof(m==null?void 0:m.path)=="string"&&m.path.trim()?m.path:l(i,m.name)})).sort((m,d)=>m.name.localeCompare(d.name)):[];return{path:i,directories:u}}function gh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Go(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function yh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function vh({ides:e,conversations:t,onOpenSession:r}){const[n,a]=o.useState(null),i=o.useCallback(c=>{a(c)},[]);return o.useEffect(()=>{if(!n)return;const c=Go(n.workspacePath),l=e.find(m=>{var N,p,x,y;if(!m||m.type==="adhdev-daemon"||gh(m.daemonId||m.id)!==n.machineId||(tr(m)?"cli":gs(m)?"acp":"ide")!==n.kind||String(m.agentType||m.type||"")!==n.providerType)return!1;if(n.resumeSessionId)return String(m.providerSessionId||"")===n.resumeSessionId;if(c){const g=Go(m.workspace||m.runtimeWorkspaceLabel);return g?g===c:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((y=(x=(p=(N=m.activeChat)==null?void 0:N.messages)==null?void 0:p.at)==null?void 0:x.call(p,-1))==null?void 0:y.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const u=lc({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});u&&(a(null),r(u))},[t,e,r,n]),o.useEffect(()=>{if(!n)return;const c=window.setTimeout(()=>{a(l=>!l||l.startedAt!==n.startedAt?l:null)},45e3);return()=>window.clearTimeout(c)},[n]),{trackPendingLaunch:i}}function wh({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=o.useCallback(async(f,j)=>an(e,f,j),[e]),l=o.useCallback(async(f,j)=>{if(!j.trim())return{ok:!1,error:"Choose a workspace path first."};try{const N=await e(f,"workspace_add",{path:j.trim()});return N!=null&&N.success?{ok:!0}:{ok:!1,error:(N==null?void 0:N.error)||"Could not save workspace"}}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not save workspace"}}},[e]),u=o.useCallback(async(f,j,N)=>{var p;try{const x={ideType:j,enableCdp:!0};(p=N==null?void 0:N.workspacePath)!=null&&p.trim()&&(x.workspace=N.workspacePath.trim());const y=await e(f,"launch_ide",x);return!(y!=null&&y.success)&&(y==null?void 0:y.success)!==void 0?{ok:!1,error:(y==null?void 0:y.error)||"Could not launch IDE"}:(t({machineId:f,kind:"ide",providerType:j,workspacePath:(N==null?void 0:N.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Could not launch IDE"}}},[e,t]),m=o.useCallback(async(f,j,N,p)=>{var y,g,C;const x=Date.now();try{const I={cliType:N};(y=p==null?void 0:p.workspacePath)!=null&&y.trim()?I.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(I.workspaceId=p.workspaceId),(g=p==null?void 0:p.resumeSessionId)!=null&&g.trim()&&(I.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(I.cliArgs=p.cliArgs),(C=p==null?void 0:p.initialModel)!=null&&C.trim()&&(I.initialModel=p.initialModel.trim());const v=await e(f,"launch_cli",I),M=(v==null?void 0:v.result)||v,S=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);return v!=null&&v.success&&S?(r(S),{ok:!0}):v!=null&&v.success?(t({machineId:f,kind:j,providerType:N,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:x}),{ok:!0}):{ok:!1,error:(v==null?void 0:v.error)||(M==null?void 0:M.error)||`Could not launch ${j.toUpperCase()} session`}}catch(I){return yh(I)?(t({machineId:f,kind:j,providerType:N,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:x}),{ok:!0}):{ok:!1,error:I instanceof Error?I.message:`Could not launch ${j.toUpperCase()} session`}}},[r,e,t]),d=o.useCallback(async(f,j)=>{if(!f||!j)return[];try{const N=await e(f,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),p=(N==null?void 0:N.result)??N;return Array.isArray(p==null?void 0:p.sessions)?p.sessions:[]}catch(N){return console.error("List saved sessions failed",N),[]}},[e]),h=o.useCallback(async f=>{await zc({conversation:n,mode:f,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:i})},[n,a,e,i]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineSavedSessions:d,setActiveCliViewMode:h}}function jh(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":return!0;case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function kh(e,t,r=Date.now()){return!e||!jh(t)?null:{tabKey:e,nonce:r}}function Sh({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,u]=o.useState(null),[m,d]=o.useState(null),h=o.useMemo(()=>{var x,y;if(!e){if(l){const g=t.find(C=>C.tabKey===l);if(g)return g}return r[0]}const p=n[a];if(p){const g=t.find(C=>C.tabKey===p);if(g)return g}return((x=i[a])==null?void 0:x[0])||((y=i[0])==null?void 0:y[0])},[t,l,a,n,i,e,r]),f=o.useCallback(p=>{u(p)},[]),j=o.useCallback(p=>{u(p.tabKey),c(x=>{const y=new URLSearchParams(x),g=ym(p);return g?y.set("activeTab",g):y.delete("activeTab"),y},{replace:!0})},[c]),N=o.useCallback((p,x)=>{const y=kh(p,x);y&&d(y)},[]);return{activeConv:h,openDesktopConversation:j,requestScrollToBottom:N,scrollToBottomRequest:m,setDesktopActiveTab:f}}function Nh(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 Ch(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&t&&t!==r),autoReadKey:i,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Th({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=o.useRef(null),i=o.useRef(null),c=o.useRef(null),l=o.useRef(null),u=o.useRef(null);o.useEffect(()=>{const m=()=>{c.current&&(clearTimeout(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null),i.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const d=Or(e,r),h=Ch({tabKey:e.tabKey,historySessionId:or(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Qt(e),liveState:d}),f=h.autoReadKey,j=Nh({autoReadKey:f,shouldMarkSeen:h.shouldMarkSeen,completedKey:a.current,pendingKey:i.current});if(!h.shouldMarkSeen){j.shouldCancelPending&&m(),a.current=f;return}if(!j.shouldSchedule)return;j.shouldCancelPending&&m();const N=()=>{if(document.visibilityState!=="visible"||a.current===f)return;a.current=f,i.current=null,c.current=null,l.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null);const x=h.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:x,completionMarker:h.completionMarker}).catch(()=>{})};if(i.current=j.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(N,1500);const x=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};u.current=x,document.addEventListener("visibilitychange",x);return}const p=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(N,800),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null))};u.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),o.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function Mh({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:u}){var T;const[m,d]=o.useState(!1),[h,f]=o.useState([]),[j,N]=o.useState(()=>ht()),[p,x]=o.useState(!1),[y,g]=o.useState(null),C=o.useRef(null),I=o.useMemo(()=>r||t||e,[e,r,t]),v=!!I&&Qe(I)&&!Ve(I),M=o.useMemo(()=>{if(!I||!v)return null;const A=I.daemonId||I.routeId||"",U=$t(I);return`${A}:${U}`},[I,v]),{isCreatingChat:S,isRefreshingHistory:k,handleSwitchSession:b,handleNewChat:B,handleRefreshHistory:L}=Xc({sendDaemonCommand:a,activeConv:I,chats:(T=n.find(A=>A.id===(I==null?void 0:I.routeId)))==null?void 0:T.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),_=o.useCallback(()=>{d(!0)},[]),H=o.useCallback(()=>{d(!1)},[]),F=o.useCallback(async()=>{if(!(!I||!v||p)){x(!0);try{const A=I.daemonId||I.routeId,U=$t(I),$=await a(A,"list_saved_sessions",{agentType:U,providerType:U,kind:"cli",limit:50}),E=($==null?void 0:$.result)??$;f(Array.isArray(E==null?void 0:E.sessions)?E.sessions:[])}catch(A){console.error("Refresh saved sessions failed",A),f([])}finally{x(!1)}}},[I,p,v,a]);o.useEffect(()=>{if(!m){C.current=null;return}if(!v){C.current=null,f([]),x(!1);return}!M||p||C.current!==M&&(C.current=M,F())},[F,m,p,v,M]);const O=o.useCallback(async A=>{if(!I||!v||!A.providerSessionId||!A.workspace)return;const U=I.daemonId||I.routeId,$=$t(I);try{g(A.providerSessionId);const E=await a(U,"launch_cli",{cliType:$,dir:A.workspace,resumeSessionId:A.providerSessionId,initialModel:Yi(A.summaryMetadata,"model",{preferShortValue:!0})||void 0}),z=(E==null?void 0:E.result)??E,Y=typeof(z==null?void 0:z.sessionId)=="string"?z.sessionId:typeof(z==null?void 0:z.id)=="string"?z.id:"";Y&&u(ve=>{const re=new URLSearchParams(ve);return re.set("activeTab",Y),re},{replace:!0}),H()}catch(E){console.error("Resume saved session failed",E)}finally{g(null)}},[H,I,v,a,u]);return{historyModalOpen:m,openHistoryModal:_,closeHistoryModal:H,historyTargetConv:I,isSavedSessionHistoryTarget:v,isHistoryCreatingChat:S,isHistoryRefreshingHistory:k,handleHistorySwitchSession:b,handleHistoryNewChat:B,handleHistoryRefresh:L,savedHistorySessions:h,savedHistoryFilters:j,setSavedHistoryFilters:N,isSavedHistoryLoading:p,resumingSavedHistorySessionId:y,handleRefreshSavedHistory:F,handleResumeSavedHistorySession:O}}function Ih({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,m]=o.useState(null),[d,h]=o.useState(null),f=o.useMemo(()=>{if(e||!n)return null;const y=l(n);return y&&!Qe(y)&&!Ve(y)?y:null},[e,n,l]),j=o.useMemo(()=>{const y=u==null?void 0:u.routeId;if(!y)return null;const g=u!=null&&u.tabKey?i.find(C=>C.tabKey===u.tabKey):a?i.find(C=>C.tabKey===a):null;return(g==null?void 0:g.routeId)===y?g:_t(i,y)},[i,u,a]),N=o.useMemo(()=>{if(j)return c.find(y=>y.id===j.routeId)},[c,j]);o.useEffect(()=>{f&&(m({routeId:f.routeId,tabKey:No(f)}),h(f),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,f]);const p=o.useCallback(y=>{y&&(m({routeId:y.routeId,tabKey:No(y)}),h(y))},[]),x=o.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:j,remoteDialogIdeEntry:N,remoteDialogActiveConv:d,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:x}}function Ah({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:u,sendDaemonCommand:m}){const{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:j,openRemoteDialog:N,closeRemoteDialog:p}=Ih({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[x,y]=o.useState(!1),[g,C]=o.useState(null),I=o.useCallback(async S=>{const k=S||u;!k||!Qe(k)&&!Ve(k)||(C(k),y(!0))},[u]),v=o.useCallback(()=>{y(!1),C(null)},[]),M=o.useCallback(async S=>{const k=g||u;if(!k||!Qe(k)&&!Ve(k)){v();return}y(!1);try{const b=$t(k),B=k.routeId||k.daemonId||"";await m(B,"stop_cli",{cliType:b,targetSessionId:k.sessionId,mode:S})}catch(b){console.error("Stop CLI failed:",b)}finally{C(null)}},[u,v,g,m]);return{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:j,openRemoteDialog:N,closeRemoteDialog:p,cliStopDialogOpen:x,cliStopTargetConv:g,requestCliStop:I,cancelCliStop:v,confirmCliStop:M}}function Qc(){return"select_session"}function Lh(){return"open_panel"}function Rh({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function _h(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function qo(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Yo(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ya(e){return e instanceof Error?e.message:String(e||"")}function Xo(e){const t=Ya(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Jo(e,t){const r=Ya(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function on({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[u,m]=o.useState(null),d=o.useRef(!1),h=o.useRef(null);o.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const f=o.useCallback(async x=>{if(!t)return!1;const y=x.trim(),g=_a(t);if(Rh({hasMessage:!!y,blockedMessage:g,sendInFlight:d.current}))return g&&m(g),!1;const C=Date.now(),I={tabKey:t.tabKey,message:y,timestamp:C};if(_h(h.current,I))return m(null),!0;d.current=!0,l(!0),m(null),h.current=I;try{const v=sr(t);if(!v)return h.current=qo(h.current,I),m("Unable to send message right now."),!1;const M=await e(v,"send_chat",{message:y,...ws(t)}),S=Yo(M);if(S!=null&&S.deduplicated)return m(null),!0;if((S==null?void 0:S.sent)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");if((S==null?void 0:S.success)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");return m(null),!0}catch(v){const M=Ya(v);return M.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",M):console.warn("Send blocked/failed",v),h.current=qo(h.current,I),m(Bm(v)),!1}finally{d.current=!1,l(!1)}},[t,e]),j=o.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(x){console.error("Relaunch failed",x)}},[t,e]),N=o.useCallback(async x=>{if(t)try{const g=(t.modalButtons||[]).indexOf(x),C=x.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),I=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(C),v=sr(t);if(!v)return;const M=await e(v,"resolve_action",{button:x,action:I?"approve":"reject",...g>=0&&{buttonIndex:g},...ws(t)}),S=Yo(M);S.success||r(k=>[...k,{routeId:t.tabKey,text:Jo(x,S==null?void 0:S.error),timestamp:Date.now()}])}catch(y){Xo(y)||console.error("[ModalButton] Error:",y),r(g=>[...g,{routeId:t.tabKey,text:Xo(y)?Jo(x,y):`❌ **${x}** error`,timestamp:Date.now()}])}},[t,e,r]),p=o.useCallback(async()=>{if(!(!t||a)){i(!0);try{await e(t.routeId,Lh(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(x){console.error("Focus agent failed",x)}finally{i(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:u,isFocusingAgent:a,handleSendChat:f,handleRelaunch:j,handleModalButton:N,handleFocusAgent:p}}function In(e,t=!0){return(e??!0)&&t}const Xa=o.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d=null,handleFocusAgent:h,isFocusingAgent:f,actionLogs:j,userName:N,scrollToBottomRequestNonce:p,isInputActive:x=!0,isVisible:y=!0}){const g=n,C=!n,I=In(y,g),v=In(y,C),M=In(y),S=Oc(t),k=S.status||S.modalMessage||S.modalButtons?{...t,...S.status?{status:S.status}:{},...S.modalMessage!==void 0?{modalMessage:S.modalMessage}:{},...S.modalButtons!==void 0?{modalButtons:S.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Ui,{activeConv:k,onModalButton:c}),k.transport!=="pty"&&k.transport!=="acp"&&k.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(Zs,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:l,children:"Relaunch with CDP"})]})}):null,k.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:g?"visible":"hidden",pointerEvents:g?"auto":"none"},children:s.jsx(gf,{activeConv:k,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,isVisible:I,isInputActive:x&&I})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(ca,{activeConv:k,ideEntry:a,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:f,actionLogs:j,userName:N,scrollToBottomRequestNonce:p,isInputActive:x&&v,isVisible:v})})]}):s.jsx(ca,{activeConv:k,ideEntry:a,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:f,actionLogs:j,userName:N,scrollToBottomRequestNonce:p,isInputActive:x&&M,isVisible:M})]})},(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 Ph({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:m,onOpenNativeConversation:d,onOpenMachine:h,onOpenHistory:f,onOpenRemote:j,onHideConversation:N,onStopCli:p,cliViewMode:x,onSetCliViewMode:y,handleSendChat:g,handleFocusAgent:C,handleModalButton:I,handleRelaunch:v}){const M=o.useRef(null),S=Qe(e)&&!t,k=S&&x==="terminal",b=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${b} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(va,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:at(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(dc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>h(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&x&&s.jsx(Ea,{mode:x,onChange:y,compact:!0}),S&&p&&s.jsx("button",{onClick:()=>{p(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(vt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(wa,{size:14})}),!t&&!S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>j(e),type:"button",children:s.jsx(St,{size:14})}),N&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>N(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(Xa,{activeConv:e,clearToken:0,isCliTerminal:k,ideEntry:n,terminalRef:M,handleModalButton:I,handleRelaunch:v,handleSendChat:g,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:C,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const An={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function Dh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Zc(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(Dh())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(An[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:An[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:An[c].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function el({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:St},{key:"chats",label:"Chats",icon:Wt}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:i})=>{const c=e===n;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(n),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(i,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function wr({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function ps({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function Os({icon:e,title:t,subtitle:r,children:n}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function jr({item:e,type:t,getAvatarText:r,onOpenConversation:n}){const a=t==="needs_attention"||t==="task_complete",i=t==="working",c=t==="earlier",l=t==="task_complete",{isReconnecting:u,isConnecting:m}=As(e.conversation),d=at(e.conversation),h=ls(e.conversation),f=gc(e.conversation,{requiresAction:t==="needs_attention"}),j=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",N=a?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",p=c?"text-text-secondary":"text-text-primary",x=c?"text-text-muted":"text-text-secondary",y=c?"text-text-secondary opacity-80":"text-text-muted",g=c?"text-text-muted opacity-80":"text-text-muted",C=!i&&!l,I="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] ${j}`,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 ${N}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(d)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${p}`,children:d}),C&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${g}`,children:Fi(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${x}`,children:[h,u?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${I} animate-pulse`,children:"Reconnecting…"})]}):m?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):f==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:I,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,children:e.preview})]}),a&&!l&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),i&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]},e.conversation.tabKey)}function Qo({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}})})}function Eh({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:m,onShowAllHidden:d,onOpenNewSession:h,onOpenMachine:f,onOpenSettings:j,onSectionChange:N,wsStatus:p="connected",isStandalone:x=!1}){const y=p==="disconnected"||p==="reconnecting"||p==="offline"||p==="auth_failed",g=c.length>0,C=t.length>0||r.length>0||n.length>0||a.length>0,I=e==="machines"?"Machines":"Chats",v=x?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",M=x?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${v}`,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:I}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Jr,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:j,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Xr,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${M}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:y?s.jsx(Os,{icon:s.jsx(Qo,{}),title:p==="offline"?"Network offline":p==="auth_failed"?"Session expired":"Reconnecting",subtitle:p==="offline"?"Waiting for network…":p==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(Os,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:x?"Waiting for your daemon":"Connect your machines",subtitle:x?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!x&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Zc,{})})}):s.jsx(ps,{children:c.map((S,k)=>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] ${k>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(S.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(S.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:S.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:S.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[S.unread," new"]}):S.total>0?`${S.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:S.subtitle}),S.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[S.total," chat",S.total!==1?"s":"",S.unread>0?` · ${S.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},S.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Needs attention",className:"mb-0"}),s.jsx(ps,{children:t.map((S,k)=>s.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:S,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},S.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(ps,{children:r.map((S,k)=>s.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:S,type:"task_complete",getAvatarText:l,onOpenConversation:u})},S.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(ps,{children:n.map((S,k)=>s.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:S,type:"working",getAvatarText:l,onOpenConversation:u})},S.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(wr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(ps,{children:a.map((S,k)=>s.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:s.jsx(jr,{item:S,type:"earlier",getAvatarText:l,onOpenConversation:u})},S.conversation.tabKey))}):C?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):y?s.jsx(Os,{icon:s.jsx(Qo,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):g?s.jsx(Os,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Wt,{size:20})}),title:"No conversations yet",subtitle:wc,children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":Dt,title:Dt,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:Dt})]})}):s.jsx(Os,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[s.jsx("span",{children:"Hidden"}),s.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:d,children:"Restore all"})]}),s.jsx(ps,{className:"bg-bg-secondary/25",children:i.map((S,k)=>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 ${k>0?"border-t border-border-subtle/70":""}`,onClick:()=>m(S),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(at(S))}),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:at(S)}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:ls(S)}),s.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},S.tabKey))})]})]}),e==="chats"&&h&&C&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":Dt,title:Dt,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),s.jsx(el,{section:e,onSectionChange:N})]})}function $h(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function tl(e){const t=[e.workspace||"Workspace unknown"],r=cs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=$h(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function cn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:m}){const[d,h]=o.useState(r);o.useEffect(()=>{h(r)},[r]);const f=xh(r),j=d.trim();return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!f||a||u(f)},disabled:!f||a,children:[s.jsx(va,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:N=>h(N.target.value),onKeyDown:N=>{N.key!=="Enter"||!j||a||(N.preventDefault(),u(j))},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:()=>{!j||a||u(j)},disabled:!j||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(N=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(N.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Ss,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:N.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:N.path})]})]},N.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(j||r),disabled:!j&&!r||a,children:c})]})]})})}function Ja({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:m,argsValue:d,onArgsChange:h,showModelInput:f,modelValue:j,onModelChange:N,historyProviderNode:p,onConfirm:x,onCancel:y}){const g=n==null?void 0:n.find(C=>C.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:y,"aria-label":"Close launch confirmation",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:C=>i(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(C=>s.jsx("option",{value:C.key,children:C.label},C.key))}),(g==null?void 0:g.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:g.description})]}),p,r.map(C=>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:C.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:C.value})]},`${C.label}:${C.value}`)),f&&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:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:j||"",onChange:C=>N(C.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),m&&h&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:d||"",onChange:C=>h(C.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,disabled:u,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:x,disabled:u,children:[s.jsx(ka,{size:14}),u?l:c]})]})]})})}function Zo(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ns(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${Zo(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:Zo(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(m=>m.key===u))return{options:i,selectedKey:u}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Bh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Kh(e){return[Bh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Oh(e){return e.lastLaunchedAt?Qr(e.lastLaunchedAt):""}function sl(e){return{metaText:Kh(e),updatedLabel:Oh(e)}}function Ln(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Wh({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var Ye,mt,pt,dt;const c=ir(),[l,u]=o.useState(!1),m=(((Ye=e.detectedIdes)==null?void 0:Ye.length)||0)>0,d=o.useMemo(()=>(e.workspaces||[]).map(Ce=>({id:Ce.id,path:Ce.path,label:Ce.label})),[e]),h=e.defaultWorkspaceId||null,[f,j]=o.useState(h||((mt=d[0])==null?void 0:mt.id)||""),[N,p]=o.useState(""),[x,y]=o.useState(""),[g,C]=o.useState([]),[I,v]=o.useState(!1),[M,S]=o.useState(""),[k,b]=o.useState(!1),[B,L]=o.useState(Ln(m,t.length,r.length)),_=o.useRef(null),[H,F]=o.useState(null),O=o.useRef("__home__"),[T,A]=o.useState("__home__"),[U,$]=o.useState(""),[E,z]=o.useState(""),[Y,ve]=o.useState(""),[re,ye]=o.useState([]),[le,be]=o.useState(()=>ht().textQuery),[ge,G]=o.useState(()=>ht().workspaceQuery),[ne,q]=o.useState(()=>ht().modelQuery),[ue,ce]=o.useState(()=>ht().resumableOnly),[je,ae]=o.useState(()=>ht().sortMode),[fe,oe]=o.useState(!1),[te,ee]=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 de=f==="__custom__"?N.trim():((pt=d.find(Ce=>Ce.id===f))==null?void 0:pt.path)||"",D=f==="__custom__"&&!!de&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ie=f!=="__custom__"&&((dt=d.find(Ce=>Ce.id===f))==null?void 0:dt.path)||"",Q=o.useMemo(()=>(e.recentLaunches||[]).map(Ce=>Ce.workspace),[e]),we=o.useCallback(async Ce=>{v(!0),S("");try{const He=await a(Ce);y(He.path),p(He.path),C(He.directories)}catch(He){S(He instanceof Error?He.message:"Could not load folder")}finally{v(!1)}},[a]),Ne=o.useCallback(()=>{var He;j("__custom__"),b(!0);const Ce=nn(e.platform,rn(N.trim(),ie,Q,e.defaultWorkspacePath,(He=d.find(Xe=>Xe.id===h))==null?void 0:He.path,d.map(Xe=>Xe.path)));we(Ce)},[N,h,we,Q,ie,e.platform,d]),Ae=o.useCallback(Ce=>{if(Ce!=null&&Ce.workspaceId){j(Ce.workspaceId),p("");return}if(Ce!=null&&Ce.workspacePath){j("__custom__"),p(Ce.workspacePath);return}j(""),p("")},[]),Me=o.useCallback(Ce=>{if(j(Ce),Ce==="__custom__"){Ne();return}p("")},[Ne]),Ue=o.useCallback(Ce=>{j("__custom__"),p(Ce)},[]),We=o.useCallback((Ce,He)=>{_.current=He,O.current=Ce.selectedWorkspaceKey||"__home__",A(Ce.selectedWorkspaceKey||"__home__"),$(Ce.initialArgs||""),z(Ce.initialModel||""),ve(""),ye([]);const Xe=Ce.providerType?`${e.id}:${Ce.providerType}`:null;if(Nf(J.current,Xe)){const ot=ht();be(ot.textQuery),G(ot.workspaceQuery),q(ot.modelQuery),ce(ot.resumableOnly),ae(ot.sortMode)}J.current=Xe,F(Ce),Ce.providerType&&i&&(oe(!0),i(Ce.providerType).then(ot=>ye(ot||[])).catch(ot=>console.warn("Failed to load saved sessions",ot)).finally(()=>oe(!1)))},[i,e.id]),Ke=o.useMemo(()=>jc(re,{textQuery:le,workspaceQuery:ge,modelQuery:ne,resumableOnly:ue,sortMode:je}),[ne,ue,re,je,le,ge]);o.useEffect(()=>{Y&&(Ke.some(Ce=>Ce.providerSessionId===Y)||ve(""))},[Ke,Y]);const Ge=o.useCallback(()=>{_.current&&(ee(!0),_.current().finally(()=>{_.current=null,ee(!1),F(null)}))},[]),Ze=o.useCallback(()=>{_.current=null,F(null)},[]),Je=o.useCallback(Ce=>{O.current=Ce,A(Ce)},[]);return o.useEffect(()=>{var Ce;X.current!==e.id&&(X.current=e.id,j(h||((Ce=d[0])==null?void 0:Ce.id)||"__custom__"),p(""),y(""),C([]),S(""),b(!1),be(ht().textQuery),G(ht().workspaceQuery),q(ht().modelQuery),ce(ht().resumableOnly),ae(ht().sortMode),J.current=null,L(Ln(m,t.length,r.length)))},[r.length,t.length,h,m,e.id,d]),o.useEffect(()=>{var Ce;f!=="__custom__"&&(f&&d.some(He=>He.id===f)||j(h||((Ce=d[0])==null?void 0:Ce.id)||"__custom__"))},[h,f,d]),o.useEffect(()=>{B==="ide"&&m||B==="cli"&&t.length>0||B==="acp"&&r.length>0||L(Ln(m,t.length,r.length))},[B,r.length,t.length,m]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:m,workspaceRows:d,defaultWorkspaceId:h,workspaceChoice:f,customWorkspacePath:N,browseCurrentPath:x,browseDirectories:g,browseBusy:I,browseError:M,browseDialogOpen:k,activeLauncherKind:B,launchConfirm:H,launchConfirmWorkspaceKeyRef:O,launchConfirmWorkspaceKey:T,launchConfirmArgs:U,launchConfirmModel:E,launchConfirmResumeId:Y,launchConfirmSavedSessions:re,launchConfirmTextFilter:le,launchConfirmWorkspaceFilter:ge,launchConfirmModelFilter:ne,launchConfirmResumableOnly:ue,launchConfirmSortMode:je,filteredLaunchConfirmSavedSessions:Ke,launchConfirmSessionsLoading:fe,launchConfirmBusy:te,resolvedWorkspacePath:de,canCreateMissingWorkspace:D,openBrowseDialog:Ne,loadBrowsePath:we,handleWorkspaceChoiceChange:Me,chooseCustomWorkspacePath:Ue,setCustomWorkspacePath:p,setBrowseDialogOpen:b,setActiveLauncherKind:L,openLaunchConfirm:We,handleConfirmLaunch:Ge,closeLaunchConfirm:Ze,setWorkspaceSelectionFromOption:Ae,setLaunchConfirmWorkspaceKeyAndSync:Je,setLaunchConfirmArgs:$,setLaunchConfirmModel:z,setLaunchConfirmResumeId:ve,setLaunchConfirmTextFilter:be,setLaunchConfirmWorkspaceFilter:G,setLaunchConfirmModelFilter:q,setLaunchConfirmResumableOnly:ce,setLaunchConfirmSortMode:ae}}function Hh({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:m,showBottomNav:d,onBack:h,onSectionChange:f,onOpenConversation:j,onOpenRecent:N,onOpenMachineDetails:p,onMachineUpgrade:x,onLaunchDetectedIde:y,onAddWorkspace:g,onBrowseDirectory:C,onLaunchWorkspaceProvider:I,onListSavedSessions:v}){const M=T=>T==="ide"?"IDE":T==="cli"?"CLI":"ACP",S=r.slice(0,4),k=t.slice(0,3),b=Wh({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:C,onListSavedSessions:v}),B=o.useMemo(()=>S.map(T=>{const{metaText:A,updatedLabel:U}=sl(T);return{key:`recent-launch:${T.id}`,primary:T.label,secondary:A,updatedLabel:U,onClick:()=>{const{options:$,selectedKey:E}=ns({machine:{workspaces:b.workspaceRows,defaultWorkspaceId:b.defaultWorkspaceId},currentWorkspacePath:T.workspace});b.openLaunchConfirm({title:T.kind==="ide"?es("restart-ide",T.label):T.providerSessionId?Ka(T.label):es("start-fresh",T.label),description:T.kind==="ide"?ts("restart-ide"):T.providerSessionId?Oa():ts("start-fresh"),confirmLabel:T.kind==="ide"?Cs("restart-ide"):T.providerSessionId?zr(!0):Cs("start-fresh"),busyLabel:T.kind==="ide"?Ts("restart-ide"):T.providerSessionId?$a(!0):Ts("start-fresh"),workspaceOptions:$,selectedWorkspaceKey:E,details:[{label:"Mode",value:M(T.kind)},...T.providerType?[{label:"Provider",value:T.providerType}]:[]]},async()=>{const z=$.find(Y=>Y.key===b.launchConfirmWorkspaceKeyRef.current);b.setWorkspaceSelectionFromOption(z),await N({...T,workspace:(z==null?void 0:z.workspacePath)??null})})}}}),[b,N,S]),L=o.useMemo(()=>k.map(T=>({key:`recent-chat:${T.conversation.tabKey}`,primary:at(T.conversation),secondary:pf(T.conversation,{timestampLabel:T.timestamp?Fi(T.timestamp):null}),unread:T.unread,onClick:()=>j(T.conversation)})),[j,k]),_=b.showAllRecent?B:B.slice(0,4),H=B.length>0,F=L.length>0,O=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${O} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:s.jsx(va,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Tt(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[F&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:L.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))})]}),H&&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:_.map(T=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:T.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:T.primary}),T.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:T.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:T.secondary})]},T.key))}),B.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>b.setShowAllRecent(T=>!T),children:b.showAllRecent?"Show fewer":`Show ${B.length-4} more`})})]}),(b.hasIdeOptions||n.length>0||a.length>0)&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:s.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),s.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),s.jsx("select",{value:b.workspaceChoice,onChange:T=>b.handleWorkspaceChoiceChange(T.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:b.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[b.workspaceRows.map(T=>s.jsxs("option",{value:T.id,children:[T.id===b.defaultWorkspaceId?"⭐ ":"",en(T.path,T.label)||T.path]},T.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),b.workspaceChoice==="__custom__"&&s.jsxs("div",{className:"flex flex-col gap-2.5",children:[s.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Ss,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),s.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:b.resolvedWorkspacePath||b.browseCurrentPath||"No folder selected yet."})]})]})}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:b.openBrowseDialog,children:"Select workspace…"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{b.resolvedWorkspacePath&&g(b.resolvedWorkspacePath)},disabled:!b.resolvedWorkspacePath||b.browseBusy,children:"Save as workspace"})]})]}),b.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:b.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[b.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${b.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>b.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${b.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>b.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${b.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>b.setActiveLauncherKind("acp"),children:"ACP"})]}),b.activeLauncherKind&&s.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[s.jsx("div",{className:"text-xs font-bold text-text-secondary",children:b.activeLauncherKind==="ide"?"Choose an IDE":b.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:b.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(T=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:A,selectedKey:U}=ns({machine:{workspaces:b.workspaceRows,defaultWorkspaceId:b.defaultWorkspaceId},currentWorkspaceId:b.workspaceChoice!=="__custom__"?b.workspaceChoice:null,currentWorkspacePath:b.resolvedWorkspacePath});b.openLaunchConfirm({title:`Launch ${T.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:A,selectedWorkspaceKey:U,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:T.name}]},async()=>{const $=A.find(E=>E.key===b.launchConfirmWorkspaceKeyRef.current);b.setWorkspaceSelectionFromOption($),y(T.type,{workspacePath:($==null?void 0:$.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:T.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:b.resolvedWorkspacePath||"Use selected workspace"})]},T.type)):(b.activeLauncherKind==="cli"?n:a).map(T=>s.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const A=b.activeLauncherKind==="cli"?"cli":"acp",{options:U,selectedKey:$}=ns({machine:{workspaces:b.workspaceRows,defaultWorkspaceId:b.defaultWorkspaceId},currentWorkspaceId:b.workspaceChoice!=="__custom__"?b.workspaceChoice:null,currentWorkspacePath:b.resolvedWorkspacePath});b.openLaunchConfirm({title:`Launch ${T.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${A.toUpperCase()}`,workspaceOptions:U,selectedWorkspaceKey:$,details:[{label:"Mode",value:A.toUpperCase()},{label:"Provider",value:T.displayName}],showArgsInput:!0,showModelInput:A==="acp",initialArgs:"",initialModel:"",providerType:T.type},async()=>{const E=U.find(z=>z.key===b.launchConfirmWorkspaceKeyRef.current);b.setWorkspaceSelectionFromOption(E),I(A,T.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.workspacePath)??null,args:b.launchConfirmArgs,model:b.launchConfirmModel,resumeSessionId:b.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[T.icon?`${T.icon} `:"",T.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:b.resolvedWorkspacePath||"Use selected workspace"})]},T.type))})]}),l.message&&s.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,b.canCreateMissingWorkspace&&s.jsx("div",{className:"mt-2",children:s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>g(b.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:x,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:p,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),b.browseDialogOpen&&s.jsx(cn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:b.browseCurrentPath,directories:b.browseDirectories,busy:b.browseBusy,error:b.browseError,confirmLabel:"Use this folder",onClose:()=>b.setBrowseDialogOpen(!1),onNavigate:T=>{b.loadBrowsePath(T)},onConfirm:T=>{b.chooseCustomWorkspacePath(T),b.setBrowseDialogOpen(!1)}}),b.launchConfirm&&s.jsx(Ja,{title:b.launchConfirm.title,description:b.launchConfirm.description,details:b.launchConfirm.details,workspaceOptions:b.launchConfirm.workspaceOptions,selectedWorkspaceKey:b.launchConfirmWorkspaceKey,onWorkspaceChange:b.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:b.launchConfirm.providerType?zr(!!b.launchConfirmResumeId):b.launchConfirm.confirmLabel,busyLabel:b.launchConfirm.providerType?void 0:b.launchConfirm.busyLabel,busy:b.launchConfirmBusy,showArgsInput:b.launchConfirm.showArgsInput,argsValue:b.launchConfirmArgs,onArgsChange:b.setLaunchConfirmArgs,showModelInput:b.launchConfirm.showModelInput,modelValue:b.launchConfirmModel,onModelChange:b.setLaunchConfirmModel,historyProviderNode:b.launchConfirm.providerType&&(b.launchConfirmSessionsLoading||b.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),b.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Ba()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:b.launchConfirmTextFilter,onChange:T=>b.setLaunchConfirmTextFilter(T.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:b.launchConfirmWorkspaceFilter,onChange:T=>b.setLaunchConfirmWorkspaceFilter(T.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:b.launchConfirmModelFilter,onChange:T=>b.setLaunchConfirmModelFilter(T.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),s.jsxs("select",{value:b.launchConfirmSortMode,onChange:T=>b.setLaunchConfirmSortMode(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:b.launchConfirmResumableOnly,onChange:T=>b.setLaunchConfirmResumableOnly(T.target.checked),disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:b.launchConfirmResumeId,onChange:T=>b.setLaunchConfirmResumeId(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Mf()}),b.filteredLaunchConfirmSavedSessions.map(T=>s.jsxs("option",{value:T.providerSessionId,disabled:!T.canResume,children:[T.title||T.providerSessionId," ",T.canResume?"":"(workspace missing)"]},T.providerSessionId))]}),!b.launchConfirmSessionsLoading&&b.launchConfirmSavedSessions.length>0&&b.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),b.launchConfirmResumeId&&(()=>{const T=b.filteredLaunchConfirmSavedSessions.find(U=>U.providerSessionId===b.launchConfirmResumeId);if(!T)return null;const A=tl(T);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:A.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:A.providerSessionId}),s.jsx("div",{className:"mt-1",children:A.metaLine}),A.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:A.updatedLabel}),A.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:A.preview})]})})()]}),onConfirm:b.handleConfirmLaunch,onCancel:b.closeLaunchConfirm}),d&&s.jsx(el,{section:m,onSectionChange:f})]})}function Rr(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Fh(e,t=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=t.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:Rr(e)}function Uh(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 zh(e,t){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:cs(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,m,d;const a=tr(n)?"cli":gs(n)?"acp":"ide",i=cs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(tr(n)?n.cliName||n.type:gs(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:gs(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((d=(m=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:m.call(u,-1))==null?void 0:d.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Vh(e,t){const r=new Map;for(const n of t){const a=ms(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((h,f)=>f.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=ta(n),u=a.filter(h=>h.unread||h.requiresAction).length,m=Uh(n),d=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Tt(n,{fallbackId:n.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?hf(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const i=n.latestTimestamp||n.fallbackActivityAt||0,c=a.latestTimestamp||a.fallbackActivityAt||0;return c!==i?c-i:n.label.localeCompare(a.label)})}function Gh(e){return e==="chat"}function kr(e,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 qh({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:j,setSelectedTabKey:N,setScreen:p,setSelectedMachineId:x,setSection:y,setMachineBackTarget:g,resetMachineAction:C}){const I=o.useRef(null),v=o.useCallback(M=>{if(!(M!=null&&M.sessionId))return;const S=Or(M,c),k=Math.max(Date.now(),Qt(M),S.lastUpdated||0);kr("mark_read:start",{tabKey:M.tabKey,sessionId:M.sessionId,displayPrimary:at(M),inboxBucket:S.inboxBucket,unread:S.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:Qt(M),readAt:k}),l(ms(M)||M.routeId,"mark_session_seen",{sessionId:M.sessionId,providerSessionId:M.providerSessionId,seenAt:k,completionMarker:S.completionMarker}).then(b=>{kr("mark_read:result",{tabKey:M.tabKey,sessionId:M.sessionId,result:b})}).catch(b=>{kr("mark_read:error",{tabKey:M.tabKey,sessionId:M.sessionId,error:b instanceof Error?b.message:String(b)})})},[c,l]);return o.useEffect(()=>{var S;if(!n){Gh(i)&&p("inbox"),N(((S=e[0])==null?void 0:S.tabKey)||null),I.current=null;return}if(i!=="chat"){I.current=null;return}const M=`${n.tabKey}:${n.sessionId||""}`;I.current!==M&&(I.current=M,v(n))},[e,v,i,n,p,N]),o.useEffect(()=>{if(!u)return;const M=e.find(S=>S.tabKey===u);M&&(N(M.tabKey),p("chat"),m==null||m())},[e,m,u,p,N]),o.useEffect(()=>{if(!d)return;const M=t.find(S=>S.id===d);M&&(x(M.id),C(),y("machines"),g("inbox"),p("machine"),h==null||h())},[t,h,d,C,g,p,y,x]),o.useEffect(()=>{f&&(y(f),p("inbox"),j==null||j())},[j,f,p,y]),o.useEffect(()=>{const M=r.filter(S=>S.inboxBucket==="task_complete"||S.unread);M.length!==0&&kr("inbox_state",{screen:i,selectedTabKey:a,items:M.map(S=>{const k=Or(S.conversation,c);return{liveState:k,tabKey:S.conversation.tabKey,sessionId:S.conversation.sessionId,displayPrimary:at(S.conversation),serverBucket:k.inboxBucket,computedBucket:S.inboxBucket,serverUnread:k.unread,computedUnread:S.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:Qt(S.conversation)}})})},[r,c,i,a]),{markConversationRead:v}}function Yh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ei(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Xh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Jh({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,m]=o.useState(null),d=o.useCallback(()=>{i("idle"),l(""),m(null)},[]),h=o.useCallback(async(g,C,I)=>{var v;try{i("loading"),l(`Launching ${C}…`);const M={ideType:C,enableCdp:!0};(v=I==null?void 0:I.workspacePath)!=null&&v.trim()&&(M.workspace=I.workspacePath.trim()),await e(g,"launch_ide",M),i("done"),l(`${C} launch requested`)}catch(M){i("error"),l(M instanceof Error?M.message:"Launch IDE failed"),console.error("Launch IDE failed",M)}},[e]),f=o.useCallback(async(g,C,I)=>{if(C.trim())try{i("loading"),l(I!=null&&I.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(g,"workspace_add",{path:C.trim(),createIfMissing:(I==null?void 0:I.createIfMissing)===!0});if(v!=null&&v.success){i("done"),l(I!=null&&I.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((v==null?void 0:v.error)||"Could not save workspace")}catch(v){i("error"),l(v instanceof Error?v.message:"Could not save workspace")}},[e]),j=o.useCallback(async g=>{var C,I,v,M,S,k;try{i("loading"),l("Starting daemon upgrade…");const b=await e(g,"daemon_upgrade",{});if((C=b==null?void 0:b.result)!=null&&C.alreadyLatest){i("done"),l(`Already on v${((I=b==null?void 0:b.result)==null?void 0:I.version)||"latest"}.`);return}if((v=b==null?void 0:b.result)!=null&&v.upgraded||(M=b==null?void 0:b.result)!=null&&M.success){i("done"),l(`Upgrade to v${((S=b==null?void 0:b.result)==null?void 0:S.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((k=b==null?void 0:b.result)==null?void 0:k.error)||"Upgrade failed")}catch(b){i("error"),l(b instanceof Error?b.message:"Upgrade failed")}},[e]),N=o.useCallback(async(g,C,I,v)=>{var k,b,B;const M=Date.now(),S={machineId:g,kind:C,providerType:I,workspaceId:(v==null?void 0:v.workspaceId)||null,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:M};try{i("loading"),l(`Launching ${I}…`),m(S);const L={cliType:I};(k=v==null?void 0:v.workspacePath)!=null&&k.trim()?L.dir=v.workspacePath.trim():v!=null&&v.workspaceId&&(L.workspaceId=v.workspaceId),v!=null&&v.resumeSessionId&&(L.resumeSessionId=v.resumeSessionId),(b=v==null?void 0:v.args)!=null&&b.trim()&&(L.cliArgs=v.args.trim().split(/\s+/).filter(Boolean)),(B=v==null?void 0:v.model)!=null&&B.trim()&&(L.initialModel=v.model.trim());const _=await e(g,"launch_cli",L),H=(_==null?void 0:_.result)||_,F=(H==null?void 0:H.sessionId)||(H==null?void 0:H.id);if(_!=null&&_.success&&F){m(null),i("done"),l(`${I} launched`),t(zt(F));return}if(_!=null&&_.success){i("loading"),l(`${I} launch requested — waiting for session…`);return}m(null),i("error"),l((_==null?void 0:_.error)||(H==null?void 0:H.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(L){if(Xh(L)){i("loading"),l(`${I} launch requested — waiting for session…`);return}m(null),i("error"),l(L instanceof Error?L.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),p=o.useCallback(async(g,C)=>{try{const I=await e(g,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),v=(I==null?void 0:I.result)??I;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(I){return console.error("Failed to list saved sessions on mobile:",I),[]}},[e]),x=o.useCallback(async(g,C)=>an(e,g,C),[e]);o.useEffect(()=>{if(!u)return;const g=ei(u.workspacePath),C=r.find(v=>{var L,_,H,F;if(!v||v.type==="adhdev-daemon"||Yh(v.daemonId||v.id)!==u.machineId||(v.transport==="acp"?"acp":v.transport==="pty"?"cli":null)!==u.kind||String(v.agentType||v.type||"")!==u.providerType)return!1;const b=String(v.providerSessionId||"");if(u.resumeSessionId&&b)return b===u.resumeSessionId;if(g){const O=ei(v.workspace||v.runtimeWorkspaceLabel);return O?O===g:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((F=(H=(_=(L=v.activeChat)==null?void 0:L.messages)==null?void 0:_.at)==null?void 0:H.call(_,-1))==null?void 0:F.timestamp)||0)>=u.startedAt-5e3});if(!C)return;const I=lc({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:n});I&&(m(null),i("done"),l(`${u.providerType} launched`),t(zt(I)))},[n,r,t,u]),o.useEffect(()=>{if(!u)return;const g=window.setTimeout(()=>{m(C=>!C||C.startedAt!==u.startedAt?C:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(g)},[u]);const y=o.useCallback(async(g,C)=>{if(C.kind==="ide"&&C.providerType){await h(g,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await N(g,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[h,N]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:h,handleAddWorkspace:f,handleMachineUpgrade:j,handleLaunchWorkspaceProvider:N,handleListSavedSessions:p,handleBrowseDirectory:x,handleOpenRecent:y}}function Qh({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:m}){const d=o.useCallback(y=>{i(y.tabKey),c("chat"),n(y)},[n,c,i]),h=o.useCallback(y=>{const g=e.find(C=>C.routeId===y.routeId&&C.streamSource==="native");g&&(i(g.tabKey),c("chat"),n(g))},[e,n,c,i]),f=o.useCallback(()=>{n(t),c("inbox")},[n,t,c]),j=o.useCallback((y,g="inbox")=>{l(y),a(),u("machines"),m(g),c("machine")},[a,m,c,u,l]),N=o.useCallback(y=>{const g=ms(y);g&&j(g,"chat")},[j]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),x=o.useCallback(y=>{u(y),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:h,backFromConversation:f,openMachine:j,openConversationMachine:N,backFromMachine:p,changeMachineSection:x}}function us(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function Zh(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function ex({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:j,onOpenHistory:N,onOpenRemote:p,onStopCli:x,wsStatus:y,isConnected:g,onShowHiddenConversation:C,onShowAllHiddenConversations:I,onHideConversation:v,onOpenNewSession:M,liveSessionInboxState:S,setCliViewModeOverrides:k}){const[b,B]=o.useState(()=>{var Q;return((Q=e[0])==null?void 0:Q.tabKey)||null}),[L,_]=o.useState(()=>e[0]?"chat":"inbox"),[H,F]=o.useState("chats"),[O,T]=o.useState(null),[A,U]=o.useState("inbox"),$=o.useRef([]),E=Is(),z="0.9.46",Y=o.useMemo(()=>e.find(Q=>Q.tabKey===b)||e[0]||null,[e,b]),ve=o.useMemo(()=>Y?r.find(Q=>Q.id===Y.routeId):void 0,[r,Y]),re=o.useMemo(()=>!Y||Ve(Y)||!Qe(Y)?null:Ls(Y),[Y]),ye=o.useMemo(()=>r.filter(Q=>Q.type==="adhdev-daemon").sort(Ca),[r]),le=o.useMemo(()=>ye.find(Q=>Q.id===O)||null,[ye,O]),be=on({sendDaemonCommand:a,activeConv:Y||void 0,setActionLogs:i,isStandalone:c}),ge=Jh({sendDaemonCommand:a,navigate:E,ides:r,conversations:e}),G=o.useMemo(()=>e.map(Q=>{const we=L==="chat"&&(Y==null?void 0:Y.tabKey)===Q.tabKey,Ne=Zr(Q,S,{hideOpenTaskCompleteUnread:!0,isOpenConversation:we}),Ae=Qt(Q),Me=bc(Q);return{conversation:Q,timestamp:Ae,preview:Me,unread:Ne.unread,requiresAction:Ne.requiresAction,isWorking:Ne.isWorking,inboxBucket:Ne.inboxBucket}}),[e,S,L,Y]),{markConversationRead:ne}=qh({conversations:e,machineEntries:ye,items:G,selectedConversation:Y,selectedTabKey:b,screen:L,liveSessionInboxState:S,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:j,setSelectedTabKey:B,setScreen:_,setSelectedMachineId:T,setSection:F,setMachineBackTarget:U,resetMachineAction:ge.resetMachineAction}),q=Qh({conversations:e,selectedConversation:Y,machineBackTarget:A,markConversationRead:ne,resetMachineAction:ge.resetMachineAction,setSelectedTabKey:B,setScreen:_,setSelectedMachineId:T,setSection:F,setMachineBackTarget:U}),ue=o.useMemo(()=>Rr(G.filter(Q=>Q.requiresAction)),[G]),ce=o.useMemo(()=>Rr(G.filter(Q=>Q.unread&&!Q.requiresAction)),[G]),je=o.useMemo(()=>Fh(G.filter(Q=>!Q.unread&&!Q.requiresAction&&Q.isWorking),$.current),[G]);o.useEffect(()=>{$.current=je.map(Q=>Q.conversation.tabKey)},[je]);const ae=o.useMemo(()=>Rr(G.filter(Q=>!Q.unread&&!Q.requiresAction&&!Q.isWorking)),[G]),fe=o.useMemo(()=>le?G.filter(Q=>ms(Q.conversation)===le.id):[],[G,le]),oe=o.useMemo(()=>zh(le,r),[r,le]),te=(le==null?void 0:le.version)||null,ee=!!le&&!!te&&!0&&te!==z,X=o.useMemo(()=>(le==null?void 0:le.availableProviders)||[],[le]),J=o.useMemo(()=>X.filter(Q=>us(Q,"cli")).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[X]),de=o.useMemo(()=>X.filter(Q=>us(Q,"acp")).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[X]),D=o.useMemo(()=>Vh(ye,G),[G,ye]),ie=o.useCallback(async Q=>{le&&await ge.handleOpenRecent(le.id,Q)},[ge,le]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:L==="chat"&&Y?s.jsx(Ph,{selectedConversation:Y,isAcp:Ve(Y),isStandalone:c,selectedIdeEntry:ve,actionLogs:n,userName:l,isSendingChat:be.isSendingChat,sendFeedbackMessage:be.sendFeedbackMessage,isFocusingAgent:be.isFocusingAgent,handleModalButton:be.handleModalButton,handleRelaunch:be.handleRelaunch,onBack:q.backFromConversation,onOpenNativeConversation:q.openNativeConversation,onOpenMachine:q.openConversationMachine,onHideConversation:v,onOpenHistory:N,onOpenRemote:p,onStopCli:x,cliViewMode:re,onSetCliViewMode:async Q=>{await zc({conversation:Y,mode:Q,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:k})},handleSendChat:be.handleSendChat,handleFocusAgent:be.handleFocusAgent}):L==="machine"&&le?s.jsx(Hh,{selectedMachineEntry:le,selectedMachineConversations:fe,selectedMachineRecentLaunches:oe,cliProviders:J,acpProviders:de,selectedMachineNeedsUpgrade:ee,appVersion:z,machineAction:ge.machineAction,isStandalone:c,section:H,showBottomNav:A==="inbox",onBack:q.backFromMachine,onSectionChange:q.changeMachineSection,onOpenConversation:q.openConversation,onOpenRecent:ie,onOpenMachineDetails:()=>E(`/machines/${le.id}`),onMachineUpgrade:()=>ge.handleMachineUpgrade(le.id),onLaunchDetectedIde:(Q,we)=>ge.handleLaunchDetectedIde(le.id,Q,we),onAddWorkspace:(Q,we)=>ge.handleAddWorkspace(le.id,Q,we),onBrowseDirectory:Q=>ge.handleBrowseDirectory(le.id,Q),onLaunchWorkspaceProvider:(Q,we,Ne)=>ge.handleLaunchWorkspaceProvider(le.id,Q,we,Ne),onListSavedSessions:Q=>ge.handleListSavedSessions(le.id,Q)}):s.jsx(Eh,{section:H,attentionItems:ue,unreadItems:ce,workingItems:je,completedItems:ae,hiddenConversations:t,machineCards:D,getAvatarText:Zh,onOpenConversation:q.openConversation,onShowConversation:C,onShowAllHidden:I,onOpenNewSession:M,onOpenMachine:q.openMachine,onOpenSettings:()=>E("/settings"),onSectionChange:F,wsStatus:y,isConnected:g,isStandalone:c})})}function Rn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function tx({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[m,d]=o.useState(null),h=o.useCallback(()=>{c.current=0,u(!1),d(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const f=o.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),j=o.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!Rn(t,r)){d("merge");return}const y=x.currentTarget.getBoundingClientRect(),g=x.clientX-y.left,C=y.width/3;g<C?d("split-left"):g>C*2?d("split-right"):d("merge")},[t,r]),N=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),d(null))},[]),p=o.useCallback(x=>{c.current=0,u(!1);const y=x.dataTransfer.getData("text/tab-key"),g=y?e.some(I=>I.tabKey===y):!1,C=m;if(d(null),i(),!!y){if(x.preventDefault(),C==="split-left"&&Rn(t,r)){r==null||r(y,"split-left");return}if(C==="split-right"&&Rn(t,r)){r==null||r(y,"split-right");return}if(g){a(y);return}n==null||n(y)}},[e,m,t,r,n,a,i]);return{dragOver:l,dropAction:m,resetDragState:h,handleDragEnter:f,handleDragOver:j,handleDragLeave:N,handleDrop:p}}function sx(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 rx({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(t??null),[l,u]=o.useState(r??[]),[m,d]=o.useState(null),h=o.useRef(null),f=o.useRef(null),j=o.useRef(n),N=o.useRef(a);o.useEffect(()=>{j.current=n},[n]),o.useEffect(()=>{N.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{u(S=>{const k=sx(S,e);return k.length===S.length&&k.every((b,B)=>b===S[B])?S:k})},[e]);const p=o.useMemo(()=>{const S=m??l;if(S.length===0)return e;const k=new Map(S.map((b,B)=>[b,B]));return[...e].sort((b,B)=>{const L=k.get(b.tabKey)??999,_=k.get(B.tabKey)??999;return L-_})},[e,m,l]);o.useEffect(()=>{var k,b;if(p.length===0){i!==null&&(c(null),(k=j.current)==null||k.call(j,null));return}if(i&&p.some(B=>B.tabKey===i))return;const S=p[0].tabKey;S!==i&&(c(S),(b=j.current)==null||b.call(j,S))},[p,i]);const x=o.useMemo(()=>p.find(S=>S.tabKey===i),[p,i]),y=o.useCallback(S=>{var k;c(S),(k=j.current)==null||k.call(j,S)},[]),g=o.useCallback((S,k,b)=>{u(B=>{var F;const L=B.filter(O=>O!==S),_=L.indexOf(k);if(_<0)return B;const H=b==="left"?_:_+1;return L.splice(H,0,S),(F=N.current)==null||F.call(N,L),L}),d(null)},[]),C=o.useCallback((S,k,b)=>{const L=(l.length>0?l:e.map(F=>F.tabKey)).filter(F=>F!==S),_=L.indexOf(k);if(_<0)return;const H=b==="left"?_:_+1;L.splice(H,0,S),h.current=L,d(L)},[l,e]),I=o.useCallback(()=>{var k;const S=h.current;S&&(u(S),(k=N.current)==null||k.call(N,S))},[]),v=o.useCallback(()=>{h.current=null,d(null)},[]),M=o.useCallback(S=>{u(k=>{var B;const b=k.filter(L=>L!==S);return b.push(S),(B=N.current)==null||B.call(N,b),b})},[]);return{activeTabId:i,activeConv:x,sortedConversations:p,previewOrderRef:h,draggingTabRef:f,selectTab:y,handleTabReorder:g,updatePreviewOrder:C,commitPreviewOrder:I,clearPreviewOrder:v,moveTabToEnd:M,setDraggingTabKey:S=>{f.current=S}}}function nx({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,u=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?wc:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:u}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),l&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:i,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Dt,"aria-label":Dt,children:[s.jsx(Ei,{size:14}),s.jsx("span",{children:Dt})]})}),c&&s.jsx(Zc,{}),c&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const rl="adhdev-tab-shortcuts";function nl(){try{return JSON.parse(localStorage.getItem(rl)||"{}")}catch{return{}}}function al({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>nl()),[l,u]=o.useState(null),m=o.useCallback(h=>{const f=[];return h.metaKey&&f.push(a?"⌘":"Meta"),h.ctrlKey&&f.push("Ctrl"),h.altKey&&f.push(a?"⌥":"Alt"),h.shiftKey&&f.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(f.push(h.key.length===1?h.key.toUpperCase():h.key),f.join("+"))},[a]),d=o.useCallback(h=>{c(h);try{localStorage.setItem(rl,JSON.stringify(h))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const h=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){u(null);return}const j=m(f);if(!j)return;const N={...i};for(const[p,x]of Object.entries(N))x===j&&delete N[p];N[l]=j,d(N),u(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,i,d,m]),o.useEffect(()=>{if(!e)return;const h=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[j,N]of Object.entries(i))if(t.includes(j)&&m(f)===N){f.preventDefault(),r(),n(j);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,i,t,r,n,m]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const _n=e=>{e.preventDefault()},ax=o.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:m,onConversationActivated:d,onPreviewReorder:h,onReorderTab:f,onCommitPreviewOrder:j,onClearPreviewOrder:N,onDragStateReset:p,onDragTabKeyChange:x,onReceiveTab:y,onOpenContextMenu:g,longPressTimer:C,isGroupActive:I}){const v=As(t),M=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",S=v.isReconnecting,k=o.useCallback(A=>{l.current=t.tabKey,x(t.tabKey),A.dataTransfer.setData("text/tab-key",t.tabKey),A.dataTransfer.effectAllowed="move"},[t.tabKey,l,x]),b=o.useCallback(()=>{l.current=null,x(null),j(),N(),p()},[l,x,j,N,p]),B=o.useCallback(A=>{const U=l.current;if(!(!U||U===t.tabKey)&&A.dataTransfer.types.includes("text/tab-key")){A.preventDefault(),A.stopPropagation();const $=A.currentTarget.getBoundingClientRect(),E=A.clientX<$.left+$.width/2?"left":"right";h(U,t.tabKey,E)}},[t.tabKey,l,h]),L=o.useCallback(A=>{A.preventDefault(),A.stopPropagation();const U=A.dataTransfer.getData("text/tab-key");if(U&&U!==t.tabKey){const $=A.currentTarget.getBoundingClientRect(),E=A.clientX<$.left+$.width/2?"left":"right";c.includes(U)?f(U,t.tabKey,E):y&&y(U)}N()},[t.tabKey,c,f,y,N]),_=o.useCallback(A=>{A.stopPropagation(),u(),m(t.tabKey),d(t)},[t,d,u,m]),H=o.useCallback(A=>{A.preventDefault(),g(A.clientX,A.clientY,t.tabKey)},[t.tabKey,g]),F=o.useCallback(A=>{const U=A.touches[0];C.current=setTimeout(()=>{g(U.clientX,U.clientY,t.tabKey)},600)},[t.tabKey,C,g]),O=o.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),T=["adhdev-dockview-tab",M,r&&"is-active",I&&"is-group-active",S&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:T,draggable:!0,onDragStart:k,onDragEnd:b,onDragOver:B,onDrop:L,onClick:_,onContextMenu:H,onTouchStart:F,onTouchEnd:O,onTouchMove:O,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:v.isGenerating?s.jsx("div",{className:"tab-spinner"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):S?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.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:at(t),children:at(t)}),s.jsx("span",{className:"adhdev-dockview-tab-meta",children:S?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Zt(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[Zt(t),s.jsx("span",{className:"connecting-dots"})]}):Zt(t)})]}),i&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function ox({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:j,onReceiveTab:N,onHideTab:p,isGroupActive:x,allowTabShortcuts:y=!0}){const[g,C]=o.useState(null),I=o.useRef(null),v=o.useRef(null),M=o.useMemo(()=>e.map(H=>H.tabKey),[e]);ar("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(g==null?void 0:g.tabKey)||null});const{isMac:S,tabShortcuts:k,shortcutListening:b,setShortcutListening:B,saveShortcuts:L}=al({enabled:y,sortedTabKeys:e.map(H=>H.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!g)return;const H=F=>{const O=document.querySelector("[data-pane-context-menu]");O&&O.contains(F.target)||C(null)};return window.addEventListener("mousedown",H,!0),()=>window.removeEventListener("mousedown",H,!0)},[g]),o.useEffect(()=>{const H=v.current;if(!H)return;const F=O=>{Math.abs(O.deltaY)<=Math.abs(O.deltaX)||(O.preventDefault(),H.scrollLeft+=O.deltaY)};return H.addEventListener("wheel",F,{passive:!1}),()=>H.removeEventListener("wheel",F)},[]);const _=o.useCallback((H,F,O)=>{C({x:H,y:F,tabKey:O})},[]);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:v,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(H=>s.jsx(ax,{conv:H,isActive:t===H.tabKey,isDraggedTab:a.current===H.tabKey,isTaskCompleteUnread:n.has(H.tabKey),shortcut:y?k[H.tabKey]:void 0,conversationKeys:M,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:j,onReceiveTab:N,onOpenContextMenu:_,longPressTimer:I,isGroupActive:x},H.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),g&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:g.x,top:g.y},children:[y&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:_n,onClick:H=>{H.stopPropagation(),B(g.tabKey),C(null)},children:["⌨ ",k[g.tabKey]?`Change shortcut (${k[g.tabKey]})`:"Set shortcut"]}),k[g.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:_n,onClick:()=>{const H={...k};delete H[g.tabKey],L(H),C(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[y&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:_n,onClick:()=>{p(g.tabKey),C(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&b&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>B(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:H=>H.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. ",S?"⌘+1":"Ctrl+1",", ",S?"⌥+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 ix({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:u,groupIndex:m,onFocus:d,isSplitMode:h,numGroups:f,onMoveTab:j,onReceiveTab:N,style:p,onActiveTabChange:x,initialActiveTabId:y,initialTabOrder:g,onTabOrderChange:C,onHideTab:I,isFocused:v,allowTabShortcuts:M=!0,onOpenNewSession:S,liveSessionInboxState:k}){const{sendCommand:b}=wt(),B=o.useRef(null),{activeTabId:L,activeConv:_,sortedConversations:H,draggingTabRef:F,selectTab:O,handleTabReorder:T,updatePreviewOrder:A,commitPreviewOrder:U,clearPreviewOrder:$,moveTabToEnd:E,setDraggingTabKey:z}=rx({conversations:e,initialActiveTabId:y,initialTabOrder:g,onActiveTabChange:x,onTabOrderChange:C}),Y=on({sendDaemonCommand:a,activeConv:_,setActionLogs:i,isStandalone:c}),{dragOver:ve,dropAction:re,resetDragState:ye,handleDragEnter:le,handleDragOver:be,handleDragLeave:ge,handleDrop:G}=tx({conversations:e,numGroups:f,onMoveTab:j,onReceiveTab:N,onOwnTabDrop:E,onClearPreviewOrder:$}),ne=_&&!Ve(_)&&Ls(_)==="terminal",q=o.useMemo(()=>_?t.find(ae=>ae.id===_.routeId):void 0,[t,_]),ue=o.useMemo(()=>_?n.filter(ae=>ae.routeId===_.tabKey):[],[n,_]),ce=o.useMemo(()=>new Set(H.filter(ae=>Nu(ae,k,{isOpenConversation:ae.tabKey===L})).map(ae=>ae.tabKey)),[L,k,H]);ar("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:L,dragOver:ve});const je=o.useCallback(ae=>{ae.streamSource==="agent-stream"&&ae.agentType&&b(ae.routeId,Qc(),{agentType:ae.agentType,...ae.sessionId&&{targetSessionId:ae.sessionId}}).catch(()=>{})},[b]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...p,outline:ve?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(ox,{conversations:H,activeTabId:L,groupIndex:m,numGroups:f,unreadTabKeys:ce,draggingTabRef:F,onFocus:d,onSelectTab:O,onConversationActivated:je,onPreviewReorder:A,onReorderTab:T,onCommitPreviewOrder:U,onClearPreviewOrder:$,onDragStateReset:ye,onDragTabKeyChange:z,onMoveTab:j,onReceiveTab:N,onHideTab:I,isGroupActive:v??!1,allowTabShortcuts:M}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:le,onDragOver:be,onDragLeave:ge,onDrop:G,children:[ve&&s.jsx(nx,{dropAction:re,canSplit:!!(f<4&&j)}),_?s.jsx(Xa,{activeConv:_,clearToken:r[_.tabKey]||0,isCliTerminal:!!ne,ideEntry:q,terminalRef:B,handleModalButton:Y.handleModalButton,handleRelaunch:Y.handleRelaunch,handleSendChat:Y.handleSendChat,isSendingChat:Y.isSendingChat,sendFeedbackMessage:Y.sendFeedbackMessage,handleFocusAgent:Y.handleFocusAgent,isFocusingAgent:Y.isFocusingAgent,actionLogs:ue,userName:u,isInputActive:!h||!!v}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Qa,{conversationsCount:e.length,isSplitMode:h,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:S})})]})]})}function cx({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:m,isStandalone:d,hasRegisteredMachines:h,userName:f,focusedGroup:j,focusGroup:N,moveTabToGroup:p,splitTabRelative:x,closeGroup:y,handleResizeStart:g,groupActiveTabIds:C,setGroupActiveTab:I,groupTabOrders:v,setGroupTabOrder:M,toggleHiddenTab:S,onOpenNewSession:k,allowTabShortcuts:b=!0,liveSessionInboxState:B}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((L,_)=>{const H=t&&n.length===r?`${n[_]}%`:void 0;return s.jsxs(jt.Fragment,{children:[t&&_>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:F=>g(_-1,F),onDoubleClick:()=>y(_),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(ix,{style:t?{flexBasis:H??`${100/r}%`,flexGrow:H?0:1,flexShrink:H?0:1}:void 0,conversations:L,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:m,isStandalone:d,hasRegisteredMachines:h,userName:f,groupIndex:_,isFocused:t&&j===_,onFocus:()=>N(_),isSplitMode:t,numGroups:r,onMoveTab:(F,O)=>{O==="left"&&_>0?p(F,_-1):O==="right"&&_<r-1?p(F,_+1):O==="split-left"&&r<4?x(F,_,"left"):O==="split-right"&&r<4&&x(F,_,"right")},onReceiveTab:F=>p(F,_),onActiveTabChange:F=>I(_,F),initialActiveTabId:C[_],initialTabOrder:v[_],onTabOrderChange:F=>M(_,F),onHideTab:S,onOpenNewSession:k,allowTabShortcuts:b,liveSessionInboxState:B})]},_)})})}function ol({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?lt.onScreenshot("ide-page",(d,h)=>{if(d!==e)return;const f=new FileReader;f.onload=()=>i(f.result),f.readAsDataURL(h)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var d;return e?((d=lt.onStatus)==null?void 0:d.call(lt,(h,f)=>{h===e&&f!=null&&f.screenshotUsage&&l(f.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,t]),o.useEffect(()=>{const m=e?lt.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&t?m.startScreenshots(t):m.stopScreenshots(t),()=>{m.stopScreenshots(t)}},[n,r,t,e]);const u=o.useCallback(async(m,d)=>{const h=e?lt.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(m,d,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const il="adhdev-dashboard-action-shortcuts",lx=1200,dx={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function ux(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function st(e,t){switch(e){case"openShortcutHelp":return"?";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return t?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return t?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return t?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return t?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return t?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return t?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return t?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return t?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return t?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return t?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function cl(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:st("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:st("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:st("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:st("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:st("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:st("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:st("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:st("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:st("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:st("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:st("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:st("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:st("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:st("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:st("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:st("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:st("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:st("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:st("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:st("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:st("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:st("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:st("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:st("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:st("toggleCliView",e)}]}function fa(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function qr(e){const t=Object.fromEntries(cl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(il)||"{}"),n={...t,...r};for(const[a,i]of Object.entries(dx))n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function ll(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function mx({enabled:e=!0,onTrigger:t}){const r=ux(),[n,a]=o.useState(()=>qr(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),m=o.useRef({parts:[],timer:null}),d=o.useCallback(p=>{const x=[];return p.metaKey&&x.push(r?"⌘":"Meta"),p.ctrlKey&&x.push("Ctrl"),p.altKey&&x.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&x.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(x.push(ll(p.key)),x.join("+"))},[r]),h=o.useCallback(p=>{a(p);try{localStorage.setItem(il,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=qr(r),x=Object.entries(n),y=Object.entries(p);x.length===y.length&&x.every(([g,C])=>p[g]===C)||h(p)},[n,r,h]);const f=o.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),j=o.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},lx))},[]);o.useEffect(()=>{if(!i)return;const p=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){c(null),u([]);return}const y=d(x);if(!y)return;const C=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(y);if(l.length===0&&C){u([y]);return}const v=[...l,y].slice(0,2).join(" "),M={...n};for(const[S,k]of Object.entries(M))k===v&&delete M[S];M[i]=v,h(M),c(null),u([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,d,h,i,l]),o.useEffect(()=>{if(!e||i)return;const p=x=>{if(x.defaultPrevented)return;const y=d(x);if(!y)return;const g=x.metaKey||x.ctrlKey||x.altKey;if(fa(x.target)&&!g)return;const C=m.current.parts,I=g?[y]:[...C.slice(-1),y].slice(-2),v=I.join(" "),M=I[I.length-1],S=Object.entries(n).filter(([,_])=>!!_),k=S.find(([,_])=>_===v);if(k){x.preventDefault(),f(),t(k[0]);return}if(S.some(([,_])=>_.startsWith(`${v} `))){x.preventDefault(),m.current.parts=I,j();return}const B=S.find(([,_])=>_===M);if(B){x.preventDefault(),f(),t(B[0]);return}if(S.some(([,_])=>_.startsWith(`${M} `))){x.preventDefault(),m.current.parts=[M],j();return}f()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,j,e,d,t,f,i]),o.useEffect(()=>()=>f(),[f]);const N=o.useMemo(()=>cl(r),[r]);return{isMac:r,actionDefinitions:N,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:h}}function fx({isTabInPopout:e,isTabFloating:t,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}function dl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function ti({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!dl(n):!0}function px({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:dl(r)}const ul=500;function hx({detachDelayMs:e=ul,onDetach:t,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:n=globalThis.clearTimeout.bind(globalThis)}){let a=null,i=null,c=null,l=!1;const u=()=>{c!=null&&(n(c),c=null)},m=()=>{u(),a=null,i=null,l=!1},d=()=>{!a||!i||l||c!=null||(c=r(()=>{c=null,!(!a||!i||l)&&(l=!0,t({panelId:a,clientX:i.clientX,clientY:i.clientY}))},e))};return{startDrag:h=>{u(),a=h.panelId,i={clientX:h.clientX,clientY:h.clientY},l=!1},markNoDropTarget:h=>{!a||l||(i={clientX:h.clientX,clientY:h.clientY},d())},markDockTarget:h=>{!a||l||(h&&(i={clientX:h.clientX,clientY:h.clientY}),u())},endDrag:m,isDragging:()=>a!=null,hasDetached:()=>l,dispose:m}}function xx(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}const ml=o.createContext(null);function ln(){const e=o.useContext(ml);if(!e)throw new Error("DashboardDockviewContext missing");return e}function _r(e){return at(e)||e.tabKey}function bx(e){return`remote:${e}`}function At(e){return e.startsWith("remote:")}function si(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function gx(e){e.preventDefault()}function Pn(e){var n;const t=e==null?void 0:e.defaultView;if(!t)return;const r=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),r(e==null?void 0:e.body),r(e==null?void 0:e.documentElement),(n=t.requestAnimationFrame)==null||n.call(t,()=>{try{t.focus(),r(e==null?void 0:e.body)}catch{}})}catch{}}function Dn(e,t){e.classList.remove(qn.className,Yn.className),e.classList.add(t==="light"?qn.className:Yn.className)}function ri(e){return e?Array.from(new Set(e.groups.map(t=>{var r,n;return(n=(r=t.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(t=>!!t&&t!==window))):[]}function yx(e){const[,t]=o.useState(0);o.useEffect(()=>{const r=()=>t(a=>a+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const a of n)a.dispose()}},[e.api,e.containerApi])}function vx(e,t,r){var c;const n=[t];let a;for(const l of n){let u;for(const m of l){const d=e.addPanel({id:m.tabKey,component:"conversation",title:_r(m),params:{kind:"conversation",tabKey:m.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return r??((c=t[0])==null?void 0:c.tabKey)??null}function ni(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])At(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==_r(n)&&a.api.setTitle(_r(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:_r(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function ai(e,t,r){var u,m;const n=r?bx(r):null;for(const d of[...e.panels])At(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=_t(t,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=vc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((m=e.panels.find(d=>!At(d.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function wx({params:e,api:t}){var h;const r=ln(),n=o.useRef(null),[a,i]=o.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=on({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(t.isActive);const f=[t.onDidActiveChange(j=>i(j.isActive)),t.onDidActiveGroupChange(j=>{if(!t.isActive&&!j.isActive){i(!1);return}i(t.isActive)})];return()=>{for(const j of f)j.dispose()}},[t]);const u=o.useMemo(()=>c?r.ides.find(f=>f.id===c.routeId):void 0,[r.ides,c]),m=o.useMemo(()=>c?r.actionLogs.filter(f=>f.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(Qa,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const d=!Ve(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(Xa,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:d,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:m,userName:r.userName,scrollToBottomRequestNonce:((h=r.scrollToBottomRequest)==null?void 0:h.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:a})})}function jx({params:e}){var u;const t=ln(),r=o.useMemo(()=>_t([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=ol({doId:a,targetSessionId:r?ac(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Hi,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:l})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function kx(){const e=ln();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Qa,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Sx(e){var j,N;yx(e);const t=ln(),r=o.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=_t([...t.conversationsByTabKey.values()],e.params.routeId),x=((j=e.api.group.activePanel)==null?void 0:j.id)===e.api.id,y=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${x?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((N=e.api.group.activePanel)==null?void 0:N.id)===e.api.id,i=e.api.isGroupActive,c=Zr(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,u=c.isConnecting,m=c.isGenerating,d=c.isWaiting,h=c.unread,f=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:at(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var x;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((x=p.target)==null?void 0:x.ownerDocument)??document})},children:[h&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?s.jsx("div",{className:"tab-spinner"}):d?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):u?s.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:at(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Zt(n)}):u?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Zt(n)}):s.jsx("span",{children:Zt(n)})})]}),f&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:f,children:f})]})}function Nx({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:u,userName:m,toggleHiddenTab:d,actionShortcuts:h,registerActionHandlers:f,onActiveTabChange:j,onOpenNewSession:N,onRequestScrollToBottom:p,requestedActiveTabKey:x,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:g,scrollToBottomRequest:C,liveSessionInboxState:I,layoutProfile:v}){var Xe,ot,ft;const{theme:M}=Fa(),{sendCommand:S}=wt(),k=o.useRef(null),b=o.useRef(null),B=o.useRef(null),L=o.useRef(!1),_=o.useRef(!1),H=o.useRef(!1),F=o.useRef(null),O=o.useRef([]),[T,A]=o.useState(null),[U,$]=o.useState(0),E=o.useRef(typeof window>"u"?{}:qp(v)),z=o.useMemo(()=>new Map(e.map(W=>[W.tabKey,W])),[e]),Y=o.useMemo(()=>{const W=k.current;return W?W.groups.some(w=>{try{const R=w.model.location.type;return R!=="floating"&&R!=="popout"?!1:w.panels.some(P=>z.has(P.id))}catch{return!1}}):!1},[z,U,e]),ve=o.useCallback(()=>{var W;(W=k.current)==null||W.focus()},[]),re=o.useCallback((W,w)=>{p==null||p(W,w)},[p]),ye=o.useCallback(W=>{const w=document,R=W.document;for(const he of w.querySelectorAll('link[rel="stylesheet"]')){const Se=R.createElement("link");Se.rel="stylesheet",Se.href=he.href,he.crossOrigin&&(Se.crossOrigin=he.crossOrigin),R.head.appendChild(Se)}for(const he of w.querySelectorAll("style")){const Se=R.createElement("style");Se.textContent=he.textContent,R.head.appendChild(Se)}const P=[];for(const he of w.styleSheets)try{for(const Se of he.cssRules)Se instanceof CSSStyleRule&&(Se.selectorText===":root"||Se.selectorText==="html")&&P.push(Se.cssText)}catch{}if(P.length>0){const he=R.createElement("style");he.textContent=P.join(`
|
|
43
|
+
`),R.head.appendChild(he)}const V=w.documentElement.getAttribute("data-theme");V&&R.documentElement.setAttribute("data-theme",V),R.documentElement.style.colorScheme=V==="light"?"light":"dark",R.body.className=w.body.className;const Z=w.documentElement.getAttribute("style");Z&&R.documentElement.setAttribute("style",Z);const me=R.getElementById("dv-popout-window");me instanceof HTMLElement&&(me.classList.add("adhdev-dockview"),Dn(me,M))},[M]),le=o.useCallback(()=>{var w;const W=k.current;if(W)for(const R of W.groups)try{const P=(w=R.element)==null?void 0:w.ownerDocument;if(!P||P===document)continue;const V=P.getElementById("dv-popout-window");V instanceof HTMLElement&&(V.classList.add("adhdev-dockview"),Dn(V,M));const Z=document.documentElement.getAttribute("data-theme");Z&&P.documentElement.setAttribute("data-theme",Z),P.documentElement.style.colorScheme=Z==="light"?"light":"dark",P.body.className=document.body.className;const me=document.documentElement.getAttribute("style");me?P.documentElement.setAttribute("style",me):P.documentElement.removeAttribute("style")}catch{}},[M]),be=o.useCallback(W=>{const w=k.current;if(!w)return;const R=w.getPanel(W);R&&w.addPopoutGroup(R,{popoutUrl:"/popout.html",onDidOpen:({window:P})=>{ye(P),fe();const V=z.get(W);P.document.title=V?`${at(V)} — ADHDev`:"ADHDev — Popout"}})},[z,ye]),ge=o.useCallback(W=>{const w=k.current,R=w==null?void 0:w.getPanel(W);if(!w||!R)return;const P=w.groups.filter(V=>{var Z;try{return((Z=V.element)==null?void 0:Z.ownerDocument)===document}catch{return!0}});P.length>0?R.api.moveTo({group:P[0],position:"center"}):R.api.moveTo({position:"center"}),R.api.setActive()},[]),G=o.useCallback(W=>{var P;const w=k.current;if(!w)return!1;const R=w.getPanel(W);if(!R)return!1;try{return((P=R.group.element)==null?void 0:P.ownerDocument)!==document}catch{return!1}},[]),ne=o.useCallback(W=>{G(W)&&ge(W),d(W)},[G,ge,d]),q=o.useCallback(W=>{const w=k.current,R=w==null?void 0:w.getPanel(W);!w||!R||w.addFloatingGroup(R,{width:600,height:500})},[]),ue=o.useCallback(W=>{var R;const w=(R=k.current)==null?void 0:R.getPanel(W);if(!w)return!1;try{return w.group.model.location.type==="floating"}catch{return!1}},[]),ce=o.useCallback(()=>{var w,R;const W=(R=(w=k.current)==null?void 0:w.activePanel)==null?void 0:R.id;return!W||At(W)?null:z.has(W)?W:null},[z]),je=o.useCallback(W=>{const w=k.current,R=w==null?void 0:w.getPanel(W);if(!w||!R)return;const P=w.groups.filter(V=>{try{return V.model.location.type==="grid"}catch{return!0}});P.length>0?R.api.moveTo({group:P[0],position:"center"}):R.api.moveTo({position:"center"}),R.api.setActive()},[]),ae=o.useCallback(()=>{var Z;const W=k.current;if(!W)return;const R=W.groups.filter(me=>{var he;try{return((he=me.element)==null?void 0:he.ownerDocument)===document&&me.model.location.type==="grid"}catch{return!1}})[0]||null,P=[...W.panels];for(const me of P){const he=(Z=me.group.element)==null?void 0:Z.ownerDocument,Se=me.group.model.location.type;he===document&&Se==="grid"||(R&&R.id!==me.group.id?me.api.moveTo({group:R,position:"center"}):me.api.moveTo({position:"center"}))}const V=W.activePanel;V&&(V.group.model.openPanel(V),V.api.setActive()),Pn(document)},[]),fe=o.useCallback(()=>{var w,R;const W=k.current;if(W)for(const P of W.groups){const V=(w=P.element)==null?void 0:w.ownerDocument;if(!V||V===document)continue;const Z=V.getElementById("dv-popout-window");if(!(Z instanceof HTMLElement))continue;let me=null,he=V.title||"ADHDev",Se="Popout workspace";const Re=P.activePanel;if(Re)if(me=Re.id,At(Re.id)){const Ie=((R=Re.params)==null?void 0:R.routeId)||Re.id.slice(7),qe=_t([...z.values()],Ie);he=vc(qe),Se=qe!=null&&qe.machineName?`Remote view · ${qe.machineName}`:"Remote view"}else{const Ie=z.get(Re.id);he=Ie?at(Ie):Re.title||Re.id,Se=Ie?Zt(Ie):"Dockview panel"}V.title=`${he} — ADHDev`;const ke=Array.from(V.querySelectorAll("#adhdev-popout-header"));for(const Ie of ke)Ie.remove();const Ee=V.createElement("div");Ee.id="adhdev-popout-header",V.body.appendChild(Ee),Ee.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),Ee.innerHTML=`
|
|
44
44
|
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
45
45
|
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
46
|
-
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${
|
|
47
|
-
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${
|
|
46
|
+
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${si(he)}</div>
|
|
47
|
+
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${si(Se)}</div>
|
|
48
48
|
</div>
|
|
49
49
|
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
50
50
|
<button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
|
|
51
51
|
<button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
|
|
52
52
|
</div>
|
|
53
|
-
`,Z.style.top="52px",Z.style.height="calc(100% - 52px)";const $e=Ee.querySelector("[data-adhdev-popout-focus]");$e&&($e.onclick=()=>{window.focus()});const Be=Ee.querySelector("[data-adhdev-popout-dock]");Be&&(Be.disabled=!me,Be.style.opacity=me?"1":"0.5",Be.style.cursor=me?"pointer":"default",Be.onclick=()=>{var Ie;me&&ge(me),(Ie=V.defaultView)==null||Ie.focus()})}},[z,ge]),oe=o.useCallback(W=>{var P;const w=k.current,R=w==null?void 0:w.getPanel(W);if(!(!w||!R)){R.group.model.openPanel(R),R.api.setActive(),re(W,"dockview-shortcut");try{const V=R.group.model.location;V.type==="popout"?V.getWindow().focus():Pn((P=R.group.element)==null?void 0:P.ownerDocument)}catch{}}},[re]),te=o.useCallback(W=>{const w=k.current,R=w==null?void 0:w.activePanel,P=(w==null?void 0:w.activeGroup)||(R==null?void 0:R.group);if(!w||!R||!P)return;const V=P.panels||[];if(V.length<=1)return;const Z=V.findIndex(Se=>Se.id===R.id);if(Z<0)return;const me=(Z+W+V.length)%V.length,he=V[me];he&&(he.group.model.openPanel(he),he.api.setActive(),At(he.id)||re(he.id,"dockview-shortcut"))},[re]),ee=o.useCallback(W=>{var $e;const w=k.current,R=(w==null?void 0:w.activeGroup)||(($e=w==null?void 0:w.activePanel)==null?void 0:$e.group);if(!w||!R)return;const P=w.groups||[],V=P.find(Be=>Be.id===R.id);if(!V)return;const Z=V.element.getBoundingClientRect(),me=Z.left+Z.width/2,he=Z.top+Z.height/2,Se=(Be,Ie,qe,ct)=>Math.max(0,Math.min(Ie,ct)-Math.max(Be,qe)),Re=Be=>{const Ie=Be.element.getBoundingClientRect(),qe=Ie.left+Ie.width/2,ct=Ie.top+Ie.height/2;let pe=0,Le=0,et=0,nt=!1;if(W==="left"?(nt=qe<me,pe=Math.max(0,Z.left-Ie.right),Le=Math.abs(ct-he),et=Se(Z.top,Z.bottom,Ie.top,Ie.bottom)):W==="right"?(nt=qe>me,pe=Math.max(0,Ie.left-Z.right),Le=Math.abs(ct-he),et=Se(Z.top,Z.bottom,Ie.top,Ie.bottom)):W==="above"?(nt=ct<he,pe=Math.max(0,Z.top-Ie.bottom),Le=Math.abs(qe-me),et=Se(Z.left,Z.right,Ie.left,Ie.right)):(nt=ct>he,pe=Math.max(0,Ie.top-Z.bottom),Le=Math.abs(qe-me),et=Se(Z.left,Z.right,Ie.left,Ie.right)),!nt)return Number.POSITIVE_INFINITY;const Oe=et>0?0:120;return pe*3+Le+Oe};let ke=null,Ee=Number.POSITIVE_INFINITY;for(const Be of P){if(Be.id===V.id)continue;const Ie=Re(Be);Number.isFinite(Ie)&&(Ie>=Ee||(Ee=Ie,ke=Be))}return ke||void 0},[]),X=o.useCallback(W=>{var P;const w=ee(W);if(!w)return;const R=w.activePanel||w.panels[0];R&&(w.model.openPanel(R),R.api.setActive(),At(R.id)||re(R.id,"dockview-focus"),Pn((P=w.element)==null?void 0:P.ownerDocument))},[ee,re]),J=o.useCallback((W,w)=>{const R=k.current,P=R==null?void 0:R.activePanel,V=(R==null?void 0:R.activeGroup)||(P==null?void 0:P.group);if(!R||!P||!V)return;let Z=ee(W);!Z&&(w!=null&&w.createGroupIfMissing)&&(Z=R.addGroup({referenceGroup:V,direction:W})),Z&&(P.api.moveTo({group:Z,position:"center"}),P.group.model.openPanel(P),P.api.setActive(),At(P.id)||re(P.id,w!=null&&w.createGroupIfMissing?"dockview-split":"dockview-move"))},[ee,re]),{isMac:de,tabShortcuts:D,shortcutListening:ie,setShortcutListening:Q,saveShortcuts:we}=ol({sortedTabKeys:e.map(W=>W.tabKey),onFocus:ve,onSelectTab:oe}),Ne=o.useCallback(()=>{var R;const W=k.current;if(!W)return;const w=W.activePanel;if(w){if(At(w.id)){const P=((R=w.params)==null?void 0:R.routeId)||w.id.slice(7),V=_t(e,P);V!=null&&V.tabKey&&Q(V.tabKey);return}z.has(w.id)&&Q(w.id)}},[z,oe,Q,e]),Ae=o.useCallback(W=>{const w=[];return W.metaKey&&w.push(de?"⌘":"Meta"),W.ctrlKey&&w.push("Ctrl"),W.altKey&&w.push(de?"⌥":"Alt"),W.shiftKey&&W.key.length!==1&&w.push(de?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(W.key)?null:(w.push(dl(W.key)),w.join("+"))},[de]),Te=o.useCallback(W=>{var w,R;switch(W){case"splitActiveTabRight":J("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":J("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const P=ce();P&&q(P);return}case"popoutActiveTab":{const P=ce();P&&be(P);return}case"dockActiveTab":{const P=ce();if(!P)return;G(P)?ge(P):ue(P)&&je(P);return}case"focusLeftPane":X("left");return;case"focusRightPane":X("right");return;case"focusUpPane":X("above");return;case"focusDownPane":X("below");return;case"moveActiveTabToLeftPane":J("left");return;case"moveActiveTabToRightPane":J("right");return;case"moveActiveTabToUpPane":J("above");return;case"moveActiveTabToDownPane":J("below");return;case"selectPreviousGroupTab":te(-1);return;case"selectNextGroupTab":te(1);return;case"setActiveTabShortcut":Ne();return;case"hideCurrentTab":{const P=(R=(w=k.current)==null?void 0:w.activePanel)==null?void 0:R.id;P&&!At(P)&&ne(P);return}default:return}},[te,je,X,q,ce,ne,ue,G,ge,J,be,Ne]);o.useEffect(()=>{if(!M)return;const W=M.sourceDocument,w=W.defaultView??window,R=P=>{const V=W.querySelector("[data-dockview-tab-context-menu]");V&&V.contains(P.target)||A(null)};return w.addEventListener("mousedown",R,!0),w!==window&&window.addEventListener("mousedown",()=>A(null),!0),()=>{w.removeEventListener("mousedown",R,!0),w!==window&&window.removeEventListener("mousedown",()=>A(null),!0)}},[M]);const Ue=o.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:z,hasDetachedConversationPanels:Y,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:N,liveSessionInboxState:I,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:ne,userName:m,scrollToBottomRequest:C,tabShortcuts:D,openTabContextMenu:({x:W,y:w,tabKey:R,sourceDocument:P})=>A({x:W,y:w,tabKey:R,sourceDocument:P??document}),popoutTab:be,moveTabBackToMain:ge,isTabInPopout:G,floatTab:q,isTabFloating:ue}),[n,t,z,Y,r,c,l,N,I,a,i,ne,m,C,D,be,ge,G,q,ue]),We=M?hx({isTabInPopout:G(M.tabKey),isTabFloating:ue(M.tabKey),tabShortcut:D[M.tabKey],actionShortcuts:h}):[],Ke=o.useCallback(W=>{var P;const w=k.current;if((((P=w==null?void 0:w.activePanel)==null?void 0:P.id)??null)===W.id){W.group.model.openPanel(W);return}W.group.model.openPanel(W),W.api.setActive()},[]),Ge=o.useCallback((W,w="requested-tab")=>{if(!W)return!1;const R=k.current;if(!R)return!1;const P=R.getPanel(W);return P?(Ke(P),re(W,w),g==null||g(),!0):!1},[Ke,g,re]),Ze=o.useCallback(()=>{if(H.current)return!1;const W=Ge(F.current,"stored-layout-restore");return W&&(H.current=!0),W},[Ge]),Je=o.useCallback(()=>{var w;const W=k.current;W&&Yp(v,{activeTabId:((w=W.activePanel)==null?void 0:w.id)??null,layout:W.toJSON()})},[v]),Ye=o.useCallback(()=>{Jp(v,E.current)},[v]),mt=o.useCallback(W=>{var P,V,Z,me;const w=k.current;if(!w)return{kind:"grid"};const R=w.toJSON();for(const he of R.floatingGroups||[])if((V=(P=he.data)==null?void 0:P.views)!=null&&V.includes(W)&&he.position)return{kind:"floating",position:he.position};for(const he of R.popoutGroups||[])if((me=(Z=he.data)==null?void 0:Z.views)!=null&&me.includes(W))return{kind:"popout",position:he.position,popoutUrl:he.url};return{kind:"grid"}},[]),pt=o.useCallback(W=>{const w=k.current;if(!w)return;const R=w.getPanel(W),P=E.current[W];if(!R||!P||P.kind==="grid")return;if(R.group.model.location.type===P.kind){delete E.current[W],Ye();return}if(P.kind==="floating"){w.addFloatingGroup(R,{x:P.position.left??24,y:P.position.top??24,width:P.position.width,height:P.position.height}),delete E.current[W],Ye();return}delete E.current[W],Ye()},[Ye]);o.useEffect(()=>(f==null||f({setShortcutForActiveTab:Ne,restoreHiddenTabToSavedLocation:pt,activateConversationTab:oe,resetAllPanelsToMain:ae,activatePreviousTabInGroup:()=>te(-1),activateNextTabInGroup:()=>te(1),floatActiveTab:()=>{const W=ce();W&&q(W)},popoutActiveTab:()=>{const W=ce();W&&be(W)},dockActiveTab:()=>{const W=ce();W&&(G(W)?ge(W):ue(W)&&je(W))},splitActiveTabRight:()=>J("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>J("below",{createGroupIfMissing:!0}),focusLeftPane:()=>X("left"),focusRightPane:()=>X("right"),focusUpPane:()=>X("above"),focusDownPane:()=>X("below"),moveActiveTabToLeftPane:()=>J("left"),moveActiveTabToRightPane:()=>J("right"),moveActiveTabToUpPane:()=>J("above"),moveActiveTabToDownPane:()=>J("below")}),()=>f==null?void 0:f(null)),[te,je,q,X,ce,ue,G,J,ge,be,f,ae,pt,oe,Ne]),o.useEffect(()=>()=>{var W;(W=B.current)==null||W.call(B),B.current=null},[]);const dt=o.useCallback(W=>{var R,P;k.current=W.api,(R=B.current)==null||R.call(B),B.current=null;const w=qp(v);if(F.current=(w==null?void 0:w.activeTabId)??null,w!=null&&w.layout&&W.api.fromJSON(w.layout,{reuseExistingPanels:!1}),_.current=si({hasStoredLayout:!!(w!=null&&w.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:r}),_.current||(ai(W.api,e),oi(W.api,e,y)),W.api.totalPanels===0&&e.length>0){const V=jx(W.api,e,x);if(V){const Z=W.api.getPanel(V);Z&&Ke(Z)}}else!_.current&&!Ge(x)&&Ze();if(L.current=!0,W.api.onDidActivePanelChange(V=>{var me;if(F.current=(V==null?void 0:V.id)??null,H.current=!0,fe(),V&&At(V.id)){const he=((me=V.params)==null?void 0:me.routeId)||V.id.slice(7),Se=_t(e,he);j((Se==null?void 0:Se.tabKey)??null),Je();return}if(j((V==null?void 0:V.id)??null),Je(),!V)return;const Z=z.get(V.id);(Z==null?void 0:Z.streamSource)==="agent-stream"&&Z.agentType&&S(Z.routeId,Zc(),{agentType:Z.agentType,...Z.sessionId&&{targetSessionId:Z.sessionId}}).catch(()=>{})}),W.api.onDidLayoutChange(()=>{Je(),fe(),$(V=>V+1)}),gx()){const V=ke=>({clientX:ke.clientX,clientY:ke.clientY}),Z=ke=>{var $e;const Ee=($e=b.current)==null?void 0:$e.getBoundingClientRect();return Ee?ke.clientX<Ee.left||ke.clientX>Ee.right||ke.clientY<Ee.top||ke.clientY>Ee.bottom:!1},me=bx({detachDelayMs:ml,onDetach:({panelId:ke,clientX:Ee,clientY:$e})=>{var Le,et;const Be=W.api.getPanel(ke);if(!Be)return;try{if(Be.group.model.location.type!=="grid")return}catch{return}const Ie=(Le=b.current)==null?void 0:Le.getBoundingClientRect(),qe=(et=Be.group.element)==null?void 0:et.getBoundingClientRect(),ct=Math.round(Math.min(Math.max((qe==null?void 0:qe.width)??600,360),720)),pe=Math.round(Math.min(Math.max((qe==null?void 0:qe.height)??500,260),640));W.api.addFloatingGroup(Be,{x:Ie?Math.max(0,Ee-Ie.left-32):void 0,y:Ie?Math.max(0,$e-Ie.top-18):void 0,width:ct,height:pe}),Be.api.setActive(),Je(),fe(),$(nt=>nt+1)}}),he=[W.api.onWillDragPanel(ke=>{if(!(ke.nativeEvent.defaultPrevented||ke.nativeEvent.shiftKey)){try{if(ke.panel.group.model.location.type!=="grid")return}catch{return}me.startDrag({panelId:ke.panel.id,...V(ke.nativeEvent)})}}),W.api.onWillShowOverlay(ke=>{if(me.hasDetached()){ke.preventDefault();return}me.markDockTarget(V(ke.nativeEvent))}),W.api.onWillDrop(ke=>{if(me.hasDetached()){ke.preventDefault(),me.endDrag();return}me.markDockTarget(V(ke.nativeEvent))}),W.api.onDidDrop(()=>me.endDrag()),W.api.onUnhandledDragOverEvent(ke=>{me.isDragging()&&me.markNoDropTarget(V(ke.nativeEvent))})],Se=ke=>{if(!me.isDragging())return;const Ee=V(ke);Z(Ee)&&me.markNoDropTarget(Ee)},Re=()=>me.endDrag();window.addEventListener("dragover",Se,!0),window.addEventListener("drop",Re,!0),window.addEventListener("dragend",Re,!0),B.current=()=>{me.dispose();for(const ke of he)ke.dispose();window.removeEventListener("dragover",Se,!0),window.removeEventListener("drop",Re,!0),window.removeEventListener("dragend",Re,!0)}}W.api.onDidAddGroup(V=>{requestAnimationFrame(()=>{var Z,me;try{const he=(Z=V.element)==null?void 0:Z.ownerDocument;if(!he||he===document)return;(me=he.getElementById("dv-popout-window"))==null||me.classList.add("adhdev-dockview");const Se=document.documentElement.getAttribute("data-theme");Se&&he.documentElement.setAttribute("data-theme",Se),he.body.className=document.body.className;const Re=document.documentElement.getAttribute("style");Re&&he.documentElement.setAttribute("style",Re)}catch{}fe(),$(he=>he+1)})}),j(((P=W.api.activePanel)==null?void 0:P.id)??null)},[Ke,Ge,z,r,u,v,j,Je,x,y,S,fe,e]);o.useLayoutEffect(()=>{const W=k.current;if(!W||!L.current||_.current&&si({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:r}))return;_.current&&(_.current=!1);const w=O.current,R=new Set(w),P=e.map(ke=>ke.tabKey),V=new Set(P),Z=xx({previousVisibleConversationCount:w.length,visibleConversationCount:e.length,ides:r});let me=!1;for(const ke of w)V.has(ke)||Z||(E.current[ke]=mt(ke),me=!0);me&&Ye(),Z||(ai(W,e),oi(W,e,y));const he=P.filter(ke=>!R.has(ke));let Se=!1;for(const ke of he){const Ee=W.getPanel(ke),$e=E.current[ke];if(!Ee||!$e||$e.kind==="grid")continue;if(Ee.group.model.location.type===$e.kind){delete E.current[ke],Se=!0;continue}if($e.kind==="floating"){W.addFloatingGroup(Ee,{x:$e.position.left??24,y:$e.position.top??24,width:$e.position.width,height:$e.position.height}),delete E.current[ke],Se=!0;continue}}if(Se&&Ye(),O.current=P,x&&Ge(x))return;!W.activePanel&&W.panels[0]&&Ke(W.panels[0]),!!(W.activePanel&&W.getPanel(W.activePanel.id))||Ze()},[Ke,Ge,Ze,r,u,Ye,mt,x,y,e]),o.useEffect(()=>{L.current&&Ge(x)},[Ge,x]),o.useEffect(()=>{const W=R=>{const P=R.target;if(!P)return;const V=P.querySelector("[data-tab-key]")||P.closest("[data-tab-key]");if(V){const Z=V.getAttribute("data-tab-key");if(Z&&R.dataTransfer){const me=P.closest(".dv-tab")||V.closest(".dv-tab")||V;R.dataTransfer.effectAllowed="move",R.dataTransfer.setData("text/tab-key",Z),me instanceof HTMLElement&&R.dataTransfer.setDragImage(me,Math.max(12,Math.round(me.clientWidth/2)),Math.max(10,Math.round(me.clientHeight/2)))}}};window.addEventListener("dragstart",W);const w=ni(k.current);for(const R of w)R.addEventListener("dragstart",W);return()=>{window.removeEventListener("dragstart",W);for(const R of w)R.removeEventListener("dragstart",W)}},[U]),o.useEffect(()=>{var w;const W=(w=b.current)==null?void 0:w.querySelector(".adhdev-dockview");W instanceof HTMLElement&&Dn(W,T),le(),fe()},[fe,le,T]),o.useEffect(()=>{fe()},[fe]),o.useEffect(()=>{const W=w=>{if(w.defaultPrevented||ie)return;const R=Ae(w);if(!R)return;const P=w.metaKey||w.ctrlKey||w.altKey;fa(w.target)&&!P||qr(de).setActiveTabShortcut!==R||(w.preventDefault(),w.stopPropagation(),Ne())};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[Ae,de,ie,Ne]),o.useEffect(()=>{const W=b.current;if(!W)return;const w=R=>{var he,Se;if(!R.isTrusted)return;const P=(Se=(he=R.target)==null?void 0:he.closest)==null?void 0:Se.call(he,".dv-scrollable");if(!P)return;R.preventDefault(),R.stopPropagation();const V=Math.abs(R.deltaX),Z=Math.abs(R.deltaY),me=V>Z?R.deltaX:R.deltaY;P.dispatchEvent(new WheelEvent("wheel",{deltaY:me,deltaMode:R.deltaMode,bubbles:!1,cancelable:!0}))};return W.addEventListener("wheel",w,{passive:!1,capture:!0}),()=>W.removeEventListener("wheel",w,{capture:!0})},[]),o.useEffect(()=>{const W=ni(k.current);if(W.length===0)return;const w=W.map(R=>{let P=[],V=null;const Z=()=>{V!=null&&R.clearTimeout(V),V=null,P=[]},me=()=>{V!=null&&R.clearTimeout(V),V=R.setTimeout(()=>{V=null,P=[]},1200)},he=Re=>{if(!Re.ctrlKey&&!Re.metaKey&&!Re.altKey)return;const ke=Ae(Re);if(!ke)return;const Ee=al();for(const[$e,Be]of Object.entries(Ee))if(e.some(Ie=>Ie.tabKey===$e)&&Be===ke){Re.preventDefault(),oe($e);return}},Se=Re=>{if(Re.defaultPrevented||ie)return;const ke=Ae(Re);if(!ke)return;const Ee=Re.metaKey||Re.ctrlKey||Re.altKey;if(fa(Re.target)&&!Ee)return;const $e=qr(de),Be=Object.entries($e).filter(([Oe,Tt])=>!!Tt&&(Oe==="splitActiveTabRight"||Oe==="splitActiveTabDown"||Oe==="floatActiveTab"||Oe==="popoutActiveTab"||Oe==="dockActiveTab"||Oe==="focusLeftPane"||Oe==="focusRightPane"||Oe==="focusUpPane"||Oe==="focusDownPane"||Oe==="moveActiveTabToLeftPane"||Oe==="moveActiveTabToRightPane"||Oe==="moveActiveTabToUpPane"||Oe==="moveActiveTabToDownPane"||Oe==="selectPreviousGroupTab"||Oe==="selectNextGroupTab"||Oe==="setActiveTabShortcut"||Oe==="hideCurrentTab")),Ie=Ee?[ke]:[...P.slice(-1),ke].slice(-2),qe=Ie.join(" "),ct=Ie[Ie.length-1],pe=Be.find(([,Oe])=>Oe===qe);if(pe){Re.preventDefault(),Z(),Te(pe[0]);return}if(Be.some(([,Oe])=>Oe.startsWith(`${qe} `))){Re.preventDefault(),P=Ie,me();return}const et=Be.find(([,Oe])=>Oe===ct);if(et){Re.preventDefault(),Z(),Te(et[0]);return}if(Be.some(([,Oe])=>Oe.startsWith(`${ct} `))){Re.preventDefault(),P=[ct],me();return}Z()};return R.addEventListener("keydown",he),R.addEventListener("keydown",Se),()=>{Z(),R.removeEventListener("keydown",he),R.removeEventListener("keydown",Se)}});return()=>{for(const R of w)R()}},[Ae,de,U,oe,ie,Te,e]);const Ce=T==="light"?qn:Yn,He=((ft=(ot=(Xe=k.current)==null?void 0:Xe.activePanel)==null?void 0:ot.group.element)==null?void 0:ft.ownerDocument)??document;return s.jsxs(fl.Provider,{value:Ue,children:[s.jsx("div",{ref:b,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(nd,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:kx,remote:Sx},defaultTabComponent:Cx,watermarkComponent:Nx,onReady:dt,singleTabMode:"default",tabAnimation:"smooth",theme:Ce,popoutUrl:"/popout.html"})}),M&&Js.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:M.x,top:M.y},children:We.map(W=>{if(W.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},W.id);let w=s.jsx(Qd,{size:13,className:"shrink-0 opacity-70"}),R=()=>{};switch(W.id){case"dockInWindow":case"dockBackToGrid":w=s.jsx(eu,{size:13,className:"shrink-0 opacity-70"}),R=()=>{je(M.tabKey),A(null)};break;case"moveBackToMain":w=s.jsx(Jd,{size:13,className:"shrink-0 opacity-70"}),R=()=>{ge(M.tabKey),A(null)};break;case"floatAsPanel":w=s.jsx(Zd,{size:13,className:"shrink-0 opacity-70"}),R=()=>{q(M.tabKey),A(null)};break;case"openInNewWindow":w=s.jsx(Xd,{size:13,className:"shrink-0 opacity-70"}),R=()=>{be(M.tabKey),A(null)};break;case"setShortcut":R=P=>{P.stopPropagation(),Q(M.tabKey),A(null)};break;case"removeShortcut":w=s.jsx(vt,{size:13,className:"shrink-0 opacity-70"}),R=()=>{const P={...D};delete P[M.tabKey],we(P),A(null)};break;case"hideTab":w=s.jsx(Di,{size:13,className:"shrink-0 opacity-70"}),R=()=>{ne(M.tabKey),A(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${W.tone==="muted"?"text-text-muted":""}`,onMouseDown:vx,onClick:R,children:[w,s.jsx("span",{className:"flex-1 min-w-0",children:W.label}),W.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:W.shortcut}):null]},W.id)})}),M.sourceDocument.body),ie&&Js.createPortal(s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>Q(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:W=>W.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. ",de?"⌘+1":"Ctrl+1",", ",de?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),He.body)]})}const pl="adhdev-recent-launch-args-v1",Tx=8;function Ix(e){return String(e||"").trim().replace(/\s+/g," ")}function hl(e,t){return`${e.trim()}::${t.trim()}`}function xl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(pl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Ax(e){if(!(typeof window>"u"))try{window.localStorage.setItem(pl,JSON.stringify(e))}catch{}}function bl(e,t){var i;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((i=xl().byKey[hl(r,n)])==null?void 0:i.items)||[]}function gl(e,t,r){var d;const n=String(e||"").trim(),a=String(t||"").trim(),i=Ix(r);if(!n||!a||!i)return;const c=xl(),l=hl(n,a),u=((d=c.byKey[l])==null?void 0:d.items)||[],m=[i,...u.filter(h=>h!==i)].slice(0,Tx);c.byKey[l]={items:m},Ax(c)}function yl(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Pr({title:e,description:t,action:r,children:n,className:a="",contentClassName:i=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),r?s.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?s.jsx("div",{className:t||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function vl({busy:e,savedSessionsLoading:t,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?sl(n):null;return s.jsxs(Pr,{title:"Saved history",description:Ba(),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:Rf()})]}),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 En(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>us(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>us(a,"acp"))?"acp":null}function Sr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Lx({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:c,onListSavedSessions:l}){var ft,W;const u=ir(),m=o.useMemo(()=>[...e].sort(Ca),[e]),[d,h]=o.useState(((ft=m[0])==null?void 0:ft.id)||""),f=o.useMemo(()=>m.find(w=>w.id===d)||m[0],[d,m]),j=o.useMemo(()=>((f==null?void 0:f.workspaces)||[]).map(w=>({id:w.id,path:w.path,label:w.label})),[f]),N=(f==null?void 0:f.defaultWorkspaceId)||null,[p,x]=o.useState(""),[y,g]=o.useState(""),[C,I]=o.useState(En(m[0])),[v,T]=o.useState(""),[S,k]=o.useState(""),[b,B]=o.useState([]),[L,_]=o.useState(""),[H,F]=o.useState([]),[O,M]=o.useState(!1),[A,U]=o.useState(!1),[$,E]=o.useState(""),[z,Y]=o.useState(!1),[ve,re]=o.useState(()=>ht()),[ye,le]=o.useState(null),[be,ge]=o.useState(!1),[G,ne]=o.useState(""),[q,ue]=o.useState(!1),[ce,je]=o.useState(""),[ae,fe]=o.useState([]),[oe,te]=o.useState(!1),[ee,X]=o.useState(""),[J,de]=o.useState(!1),D=o.useRef(null),ie=o.useRef(0);o.useEffect(()=>{var w;!d&&((w=m[0])!=null&&w.id)&&h(m[0].id)},[d,m]),o.useEffect(()=>{!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||u(f.id,{minFreshMs:3e4}).catch(()=>{})},[u,f]);const Q=o.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(w=>us(w,"cli")),[f]),we=o.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(w=>us(w,"acp")),[f]),Ne=o.useMemo(()=>((f==null?void 0:f.detectedIdes)||[]).map(w=>({id:w.type,label:w.name||w.type,meta:w.running?"Detected locally":"Available to open"})),[f]),Ae=o.useMemo(()=>C==="cli"?Q.map(w=>({id:w.type,label:w.displayName||w.type,meta:"CLI provider"})):C==="acp"?we.map(w=>({id:w.type,label:w.displayName||w.type,meta:"ACP provider"})):Ne,[we,C,Q,Ne]);o.useEffect(()=>{var R;if(!f)return;if(D.current!==f.id){D.current=f.id,x(N||((R=j[0])==null?void 0:R.id)||"__home__"),g(""),I(En(f)),T(""),k(""),_(""),F([]),U(!1),E(""),re(ht()),ne("");return}x(P=>{var V;return P==="__custom__"||P==="__home__"||j.some(Z=>Z.id===P)?P:N||((V=j[0])==null?void 0:V.id)||"__home__"}),I(P=>P==="ide"&&Ne.length>0||P==="cli"&&Q.length>0||P==="acp"&&we.length>0?P:En(f))},[we.length,Q.length,N,Ne.length,f,j]),o.useEffect(()=>{var w;C&&(Ae.some(R=>R.id===v)||T(((w=Ae[0])==null?void 0:w.id)||""))},[C,Ae,v]);const Te=o.useCallback(async(w,R)=>{const P=ie.current+1;return ie.current=P,M(!0),E(""),l(w,R).then(V=>{ie.current===P&&F(V)}).catch(V=>{ie.current===P&&(F([]),E(V instanceof Error?V.message:"Could not load saved sessions"))}).finally(()=>{ie.current===P&&(M(!1),U(!0))})},[l]),Ue=o.useCallback((w,R)=>{B(bl(w,R))},[]);o.useEffect(()=>{ie.current+=1,_(""),re(ht()),!f||!v||C==="ide"?B([]):Ue(f.id,v),U(!1),F([]),E(""),M(!1)},[C,Ue,Te,f,v]),o.useEffect(()=>{if(!L)return;const w=H.find(R=>R.providerSessionId===L);w!=null&&w.canResume||_("")},[H,L]);const We=p==="__custom__"?y.trim():p==="__home__"?"":((W=j.find(w=>w.id===p))==null?void 0:W.path)||"",Ke=o.useMemo(()=>f?t.filter(w=>w.id!==f.id&&w.daemonId===f.id).map(w=>w.workspace):[],[t,f]),Ge=o.useMemo(()=>((f==null?void 0:f.recentLaunches)||[]).map(w=>w.workspace),[f]),Ze=o.useCallback(w=>{const R=String(w.workspace||"").trim();if(!R)return;const P=j.find(V=>Sr(V.path)===Sr(R));if(P){x(P.id),g("");return}x("__custom__"),g(R)},[j]),Je=o.useCallback(w=>{const R=String(w.workspace||"").trim();if(!R)return{workspaceId:null,workspacePath:null};const P=j.find(V=>Sr(V.path)===Sr(R));return P?{workspaceId:P.id,workspacePath:null}:{workspaceId:null,workspacePath:R}},[j]),Ye=o.useMemo(()=>H.find(w=>w.providerSessionId===L)||null,[H,L]),mt=o.useMemo(()=>{var R;if(C!=="cli"||!f||!v)return null;const w=((R=Q.find(P=>P.type===v))==null?void 0:R.displayName)||v;return{routeId:f.id,daemonId:f.id,providerSessionId:L||void 0,transport:"pty",mode:"chat",agentName:w,agentType:v,status:"idle",title:w,messages:[],ideType:v,workspaceName:We,displayPrimary:w,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${f.id}:${v}`,machineName:Mt(f,{fallbackId:f.id})}},[C,Q,We,f,L,v]),pt=o.useCallback(()=>{var R;if(!f)return;x("__custom__"),ue(!0),X("");const w=nn(f.platform,rn(y.trim(),We,Ke,Ge,f.defaultWorkspacePath,(R=j.find(P=>P.id===N))==null?void 0:R.path,j.map(P=>P.path)));te(!0),n(f.id,w).then(P=>{je(P.path),g(P.path),fe(P.directories)}).catch(P=>{X(P instanceof Error?P.message:"Could not load folder")}).finally(()=>te(!1))},[y,N,Ge,Ke,n,We,f,j]),dt=o.useCallback(w=>{f&&(te(!0),X(""),n(f.id,w).then(R=>{je(R.path),g(R.path),fe(R.directories)}).catch(R=>{X(R instanceof Error?R.message:"Could not load folder")}).finally(()=>te(!1)))},[n,f]),Ce=o.useCallback(async()=>{if(!f||!We)return;de(!0),ne("");const w=await a(f.id,We);if(de(!1),!w.ok){ne(w.error||"Could not save workspace");return}ne("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,We,f]),He=o.useCallback(async()=>{if(!f||!C||!v)return;ge(!0),ne("");const w=S.trim()?S.trim().split(/\s+/).filter(Boolean):[],R=C==="ide"?await i(f.id,v,{workspacePath:We||null}):await c(f.id,C,v,{workspaceId:p!=="__home__"&&p!=="__custom__"?p:null,workspacePath:p==="__custom__"&&We||null,resumeSessionId:C==="cli"&&L?L:null,cliArgs:w});if(ge(!1),!R.ok){ne(R.error||"Could not start session");return}C!=="ide"&&S.trim()&&(gl(f.id,v,S),Ue(f.id,v)),r()},[C,S,Ue,r,i,c,We,f,L,v,p]),Xe=C?Sc(C,C==="cli"&&!!L):"Start",ot=C?Nc(C,C==="cli"&&!!L):"Starting…";return f?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[s.jsx(Pr,{title:"Machine",children:s.jsx("select",{value:f.id,onChange:w=>h(w.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:be,children:m.map(w=>s.jsx("option",{value:w.id,children:Mt(w,{fallbackId:w.id})},w.id))})}),s.jsxs(Pr,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:pt,disabled:be,children:"Browse…"}),children:[s.jsxs("select",{value:p,onChange:w=>{const R=w.target.value;x(R),R==="__custom__"?pt():ne("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:be,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),j.map(w=>s.jsxs("option",{value:w.id,children:[w.id===N?"⭐ ":"",en(w.path,w.label)||w.path]},w.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:p==="__home__"?"Launch without a workspace.":We||"Select a workspace folder."}),p==="__custom__"&&We&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:pt,disabled:be,children:[s.jsx(Ss,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ce,disabled:be||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:Q.length>0},{id:"ide",label:"IDE",enabled:Ne.length>0},{id:"acp",label:"ACP",enabled:we.length>0}].map(w=>s.jsx("button",{type:"button",className:`btn btn-sm ${C===w.id?"btn-primary":"btn-secondary"}`,onClick:()=>I(w.id),disabled:!w.enabled||be,children:w.label},w.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:C==="ide"?"Choose IDE":C==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Ae.map(w=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===w.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>T(w.id),disabled:be,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:w.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:w.meta})]},w.id)),Ae.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),C!=="ide"&&s.jsxs(Pr,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:S,onChange:w=>k(w.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:be}),b.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:b.map(w=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>k(w),disabled:be,title:w,children:w},w))})]}),C==="cli"&&s.jsx(vl,{busy:be,savedSessionsLoading:O,savedSessionsError:$,selectedSession:Ye,onRefresh:()=>{!f||!v||Te(f.id,v)},onOpenHistory:()=>{!f||!v||(Y(!0),yl({hasLoadedInitialResults:A,isLoading:O})&&Te(f.id,v))},onClearSelection:()=>_("")}),G&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${G.includes("saved")||G.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:G})]}),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:be,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:He,disabled:be||!C||!v||p==="__custom__"&&!We,children:[s.jsx(ka,{size:14}),be?ot:Xe]})]})]})}),q&&s.jsx(cn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:ce,directories:ae,busy:oe,error:ee,onClose:()=>ue(!1),onNavigate:dt,onConfirm:w=>{g(w),je(w),x("__custom__"),ue(!1)}}),z&&mt&&s.jsx(Wa,{activeConv:mt,ides:[],isCreatingChat:!1,isRefreshingHistory:O,savedSessions:H,isSavedSessionsLoading:O,isResumingSavedSessionId:ye,savedHistoryFilters:ve,onSavedHistoryFiltersChange:re,onClose:()=>Y(!1),onNewChat:()=>{_(""),Y(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!f||!v||Te(f.id,v)},onResumeSavedSession:w=>{if(!f||!v||ye||!w.canResume)return;const R=Je(w);_(w.providerSessionId),Ze(w),le(w.providerSessionId),Y(!1),ge(!0),ne(""),c(f.id,"cli",v,{workspaceId:R.workspaceId,workspacePath:R.workspacePath,resumeSessionId:w.providerSessionId}).then(P=>{if(!P.ok){ne(P.error||"Could not resume session");return}r()}).finally(()=>{ge(!1),le(P=>P===w.providerSessionId?null:P)})}})]}):null}function Rx({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=o.useState(!1),[i,c]=o.useState(!1),[l,u]=o.useState(!1),[m,d]=o.useState(!1),[h,f]=o.useState(!1),[j,N]=o.useState("quickstart"),[p,x]=o.useState("workspace"),y=o.useMemo(()=>!t&&!e,[t,e]),g=o.useCallback(k=>{a(k),k&&c(!1)},[]),C=o.useCallback(k=>{c(k),k&&a(!1)},[]),I=o.useCallback(()=>{N(r===0?"quickstart":"shortcuts"),x("workspace"),u(!0),a(!1),c(!1)},[r]),v=o.useCallback(()=>{u(!1)},[]),T=o.useCallback(()=>{d(!0)},[]),S=o.useCallback(()=>{d(!1)},[]);return o.useEffect(()=>{if(!y){f(!1);return}f(!0);const k=window.setTimeout(()=>{f(!1)},1e4);return()=>window.clearTimeout(k)},[y]),{inboxOpen:n,hiddenOpen:i,shortcutHelpOpen:l,newSessionOpen:m,guideNudgeVisible:h,guideTab:j,shortcutSection:p,isDesktopDashboard:y,setGuideTab:N,setShortcutSection:x,handleInboxOpenChange:g,handleHiddenOpenChange:C,handleOpenShortcutHelp:I,closeShortcutHelp:v,openNewSession:T,closeNewSession:S}}function _x(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 Px(e){return e instanceof Error?e.message:String(e||"")}function Dx(e){const t=Px(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Ex({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetActiveCliViewMode:m,mobileChatConversations:d,hiddenConversations:h,ides:f,actionLogs:j,sendDaemonCommand:N,setActionLogs:p,setCliViewModeOverrides:x,isStandalone:y,initialDataLoaded:g,userName:C,requestedMobileTabKey:I,onRequestedMobileTabConsumed:v,requestedMachineId:T,onRequestedMachineConsumed:S,requestedMobileSection:k,onRequestedMobileSectionConsumed:b,containerRef:B,isSplitMode:L,numGroups:_,groupSizes:H,groupedConvs:F,clearedTabs:O,focusedGroup:M,focusGroup:A,moveTabToGroup:U,splitTabRelative:$,closeGroup:E,handleResizeStart:z,groupActiveTabIds:Y,setGroupActiveTab:ve,groupTabOrders:re,setGroupTabOrder:ye,toggleHiddenTab:le,visibleConversations:be,requestedDesktopTabKey:ge,onRequestedDesktopTabConsumed:G,onDesktopActiveTabChange:ne,onRequestScrollToBottom:q,onHideConversation:ue,onShowHiddenConversation:ce,onShowAllHiddenConversations:je,scrollToBottomRequest:ae,machineEntries:fe,layoutProfile:oe,onBrowseMachineDirectory:te,onSaveMachineWorkspace:ee,onLaunchMachineIde:X,onLaunchMachineProvider:J,onListMachineSavedSessions:de,notifications:D,notificationUnreadCount:ie,liveSessionInboxState:Q,onMarkNotificationRead:we,onMarkNotificationUnread:Ne,onDeleteNotification:Ae}){const Te=jt.useRef(null),{inboxOpen:Ue,hiddenOpen:We,shortcutHelpOpen:Ke,newSessionOpen:Ge,guideNudgeVisible:Ze,guideTab:Je,shortcutSection:Ye,isDesktopDashboard:mt,setGuideTab:pt,setShortcutSection:dt,handleInboxOpenChange:Ce,handleHiddenOpenChange:He,handleOpenShortcutHelp:Xe,closeShortcutHelp:ot,openNewSession:ft,closeNewSession:W}=Rx({isMobile:t,showMobileChatMode:e,visibleConversationCount:be.length}),w=jt.useCallback(pe=>{var Le;Js.flushSync(()=>{ce(pe)}),(Le=Te.current)==null||Le.restoreHiddenTabToSavedLocation(pe.tabKey)},[ce]),R=jt.useCallback(pe=>{var et;const Le=d.find(nt=>ra(nt,pe))||h.find(nt=>ra(nt,pe));Le&&(h.some(nt=>nt.tabKey===Le.tabKey)&&w(Le),ne(Le.tabKey),(et=Te.current)==null||et.activateConversationTab(Le.tabKey),q(Le.tabKey,"notification-open")),we(pe.id),Ce(!1)},[w,h,d,ne,we,q]),P=jt.useCallback(()=>{var Le;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Le=Te.current)==null||Le.resetAllPanelsToMain(),He(!1))},[He]),V=jt.useCallback(async pe=>{var Tt;if(!r)return;const Le=(Tt=r.modalButtons)==null?void 0:Tt[pe];if(!Le)return;const et=sr(r);if(!et)return;const nt=Le.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Oe=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(nt);try{await N(et,"resolve_action",{button:Le,action:Oe?"approve":"reject",buttonIndex:pe,...ws(r)})}catch(K){Dx(K)||console.error("[Shortcut approval] Failed:",K)}},[r,N]),{isMac:Z,actionDefinitions:me,actionShortcuts:he,shortcutListening:Se,shortcutListeningDraft:Re,setShortcutListening:ke,setShortcutListeningDraft:Ee,saveShortcuts:$e}=px({enabled:mt&&!Ke,onTrigger:pe=>{var Le,et,nt,Oe,Tt,K,se,xe,Pe,Me,_e,tt,yt,ut,Ht,lr;if(pe==="openShortcutHelp"){Xe();return}if(pe==="hideCurrentTab"){r&&ue(r);return}if(pe==="toggleHiddenTabs"){He(!We);return}if(pe==="openHistoryForActiveTab"){r&&!Ve(r)&&i(r);return}if(pe==="openRemoteForActiveTab"){r&&!Qe(r)&&!Ve(r)&&c(r);return}if(pe==="splitActiveTabRight"){(Le=Te.current)==null||Le.splitActiveTabRight();return}if(pe==="splitActiveTabDown"){(et=Te.current)==null||et.splitActiveTabDown();return}if(pe==="floatActiveTab"){(nt=Te.current)==null||nt.floatActiveTab();return}if(pe==="popoutActiveTab"){(Oe=Te.current)==null||Oe.popoutActiveTab();return}if(pe==="dockActiveTab"){(Tt=Te.current)==null||Tt.dockActiveTab();return}if(pe==="focusLeftPane"){(K=Te.current)==null||K.focusLeftPane();return}if(pe==="focusRightPane"){(se=Te.current)==null||se.focusRightPane();return}if(pe==="focusUpPane"){(xe=Te.current)==null||xe.focusUpPane();return}if(pe==="focusDownPane"){(Pe=Te.current)==null||Pe.focusDownPane();return}if(pe==="moveActiveTabToLeftPane"){(Me=Te.current)==null||Me.moveActiveTabToLeftPane();return}if(pe==="moveActiveTabToRightPane"){(_e=Te.current)==null||_e.moveActiveTabToRightPane();return}if(pe==="moveActiveTabToUpPane"){(tt=Te.current)==null||tt.moveActiveTabToUpPane();return}if(pe==="moveActiveTabToDownPane"){(yt=Te.current)==null||yt.moveActiveTabToDownPane();return}if(pe==="triggerPrimaryApprovalAction"){V(0);return}if(pe==="triggerSecondaryApprovalAction"){V(1);return}if(pe==="triggerTertiaryApprovalAction"){V(2);return}if(pe==="setActiveTabShortcut"){(ut=Te.current)==null||ut.setShortcutForActiveTab();return}if(pe==="selectPreviousGroupTab"){(Ht=Te.current)==null||Ht.activatePreviousTabInGroup();return}if(pe==="selectNextGroupTab"){(lr=Te.current)==null||lr.activateNextTabInGroup();return}!r||!Qe(r)||Ve(r)||pe==="toggleCliView"&&m(u==="chat"?"terminal":"chat")}}),Be=jt.useCallback(()=>{ot(),ke(null),Ee([])},[ot,ke,Ee]),Ie=jt.useMemo(()=>Ye==="all"?me:me.filter(pe=>_x(pe)===Ye),[me,Ye]),qe=jt.useCallback(()=>{const pe=Object.fromEntries(me.map(Le=>[Le.id,""]));$e(pe)},[me,$e]),ct=jt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const pe=Object.fromEntries(me.map(Le=>[Le.id,Le.defaultShortcut]));$e(pe)},[me,$e]);return jt.useEffect(()=>{const pe=Le=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Le.metaKey&&Le.key.toLowerCase()==="w":Le.ctrlKey&&Le.key.toLowerCase()==="w")&&(Le.preventDefault(),r&&ue&&ue(r))};return window.addEventListener("keydown",pe),()=>window.removeEventListener("keydown",pe)},[r,ue]),jt.useEffect(()=>{if(!Ke||Se)return;const pe=Le=>{Le.key==="Escape"&&(Le.preventDefault(),Be())};return window.addEventListener("keydown",pe,!0),()=>window.removeEventListener("keydown",pe,!0)},[Be,Ke,Se]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Cf,{activeConv:r,wsStatus:n,isConnected:a,conversations:be,hiddenConversations:h,onOpenHistory:i,onHideConversation:ue,onShowConversation:w,onShowAllHidden:je,onResetPanelsToMain:P,notifications:D,notificationUnreadCount:ie,onOpenNotification:R,onMarkNotificationRead:we,onMarkNotificationUnread:Ne,onDeleteNotification:Ae,inboxOpen:Ue,onInboxOpenChange:Ce,hiddenOpen:We,onHiddenOpenChange:He,onOpenNewSession:t?void 0:ft,onOpenDashboardGuide:Xe,guideNudgeVisible:Ze,actionShortcuts:he,onOpenRemote:()=>{!r||Qe(r)||Ve(r)||c(r)},onStopCli:l,activeCliViewMode:u,onSetCliViewMode:m}),e?s.jsx(sx,{conversations:d,hiddenConversations:h,ides:f,actionLogs:j,sendDaemonCommand:N,setActionLogs:p,setCliViewModeOverrides:x,isStandalone:y,userName:C,requestedActiveTabKey:I,onRequestedActiveTabConsumed:v,requestedMachineId:T,onRequestedMachineConsumed:S,requestedMobileSection:k,onRequestedMobileSectionConsumed:b,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowHiddenConversation:w,onShowAllHiddenConversations:je,onOpenNewSession:ft,liveSessionInboxState:Q}):t?s.jsx(dx,{containerRef:B,isSplitMode:L,numGroups:_,groupSizes:H,groupedConvs:F,clearedTabs:O,ides:f,actionLogs:j,sendDaemonCommand:N,setActionLogs:p,isStandalone:y,hasRegisteredMachines:fe.length>0,userName:C,focusedGroup:M,focusGroup:A,moveTabToGroup:U,splitTabRelative:$,closeGroup:E,handleResizeStart:z,groupActiveTabIds:Y,setGroupActiveTab:ve,groupTabOrders:re,setGroupTabOrder:ye,toggleHiddenTab:le,onOpenNewSession:ft,allowTabShortcuts:!1,liveSessionInboxState:Q}):s.jsx(Mx,{visibleConversations:be,clearedTabs:O,ides:f,actionLogs:j,sendDaemonCommand:N,setActionLogs:p,isStandalone:y,hasRegisteredMachines:fe.length>0,initialDataLoaded:g,userName:C,toggleHiddenTab:le,actionShortcuts:he,registerActionHandlers:pe=>{Te.current=pe},onActiveTabChange:ne,requestedActiveTabKey:ge,onRequestedActiveTabConsumed:G,onRequestScrollToBottom:q,scrollToBottomRequest:ae,onOpenNewSession:ft,liveSessionInboxState:Q,layoutProfile:oe}),Ge&&s.jsx(Lx,{machines:fe,ides:f,onClose:W,onBrowseDirectory:te,onSaveWorkspace:ee,onLaunchIde:X,onLaunchProvider:J,onListSavedSessions:de}),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:Be,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:pe=>pe.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:Be,"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(pe=>s.jsx("button",{type:"button",className:`btn btn-sm ${Je===pe.id?"btn-primary":"btn-secondary"}`,onClick:()=>pt(pe.id),children:pe.label},pe.id))}),Je==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Z?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Je==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),Je==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(pe=>s.jsx("button",{type:"button",className:`btn btn-sm ${Ye===pe.id?"btn-primary":"btn-secondary"}`,onClick:()=>dt(pe.id),children:pe.label},pe.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:qe,children:"Disable all"}),s.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:ct,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Ie.map(pe=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Se===pe.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:pe.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:pe.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:pe.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:Se===pe.id?Re.length>0?`${Re.join(" ")} ...`:"Listening...":he[pe.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{ke(pe.id),Ee([])},children:Se===pe.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Le={...he};Le[pe.id]="",$e(Le)},children:"Disable"})]})]})},pe.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Z?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})})]})}const $n=[{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 $x({onClose:e}){const[t,r]=o.useState(0),n=$n[t],a=t===$n.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:$n.map((i,c)=>s.jsx("div",{style:{width:c===t?24:8,height:8,borderRadius:4,background:c===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:n.icon})," ",n.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
|
|
53
|
+
`,Z.style.top="52px",Z.style.height="calc(100% - 52px)";const $e=Ee.querySelector("[data-adhdev-popout-focus]");$e&&($e.onclick=()=>{window.focus()});const Be=Ee.querySelector("[data-adhdev-popout-dock]");Be&&(Be.disabled=!me,Be.style.opacity=me?"1":"0.5",Be.style.cursor=me?"pointer":"default",Be.onclick=()=>{var Ie;me&&ge(me),(Ie=V.defaultView)==null||Ie.focus()})}},[z,ge]),oe=o.useCallback(W=>{var P;const w=k.current,R=w==null?void 0:w.getPanel(W);if(!(!w||!R)){R.group.model.openPanel(R),R.api.setActive(),re(W,"dockview-shortcut");try{const V=R.group.model.location;V.type==="popout"?V.getWindow().focus():Pn((P=R.group.element)==null?void 0:P.ownerDocument)}catch{}}},[re]),te=o.useCallback(W=>{const w=k.current,R=w==null?void 0:w.activePanel,P=(w==null?void 0:w.activeGroup)||(R==null?void 0:R.group);if(!w||!R||!P)return;const V=P.panels||[];if(V.length<=1)return;const Z=V.findIndex(Se=>Se.id===R.id);if(Z<0)return;const me=(Z+W+V.length)%V.length,he=V[me];he&&(he.group.model.openPanel(he),he.api.setActive(),At(he.id)||re(he.id,"dockview-shortcut"))},[re]),ee=o.useCallback(W=>{var $e;const w=k.current,R=(w==null?void 0:w.activeGroup)||(($e=w==null?void 0:w.activePanel)==null?void 0:$e.group);if(!w||!R)return;const P=w.groups||[],V=P.find(Be=>Be.id===R.id);if(!V)return;const Z=V.element.getBoundingClientRect(),me=Z.left+Z.width/2,he=Z.top+Z.height/2,Se=(Be,Ie,qe,ct)=>Math.max(0,Math.min(Ie,ct)-Math.max(Be,qe)),Re=Be=>{const Ie=Be.element.getBoundingClientRect(),qe=Ie.left+Ie.width/2,ct=Ie.top+Ie.height/2;let pe=0,Le=0,et=0,nt=!1;if(W==="left"?(nt=qe<me,pe=Math.max(0,Z.left-Ie.right),Le=Math.abs(ct-he),et=Se(Z.top,Z.bottom,Ie.top,Ie.bottom)):W==="right"?(nt=qe>me,pe=Math.max(0,Ie.left-Z.right),Le=Math.abs(ct-he),et=Se(Z.top,Z.bottom,Ie.top,Ie.bottom)):W==="above"?(nt=ct<he,pe=Math.max(0,Z.top-Ie.bottom),Le=Math.abs(qe-me),et=Se(Z.left,Z.right,Ie.left,Ie.right)):(nt=ct>he,pe=Math.max(0,Ie.top-Z.bottom),Le=Math.abs(qe-me),et=Se(Z.left,Z.right,Ie.left,Ie.right)),!nt)return Number.POSITIVE_INFINITY;const Oe=et>0?0:120;return pe*3+Le+Oe};let ke=null,Ee=Number.POSITIVE_INFINITY;for(const Be of P){if(Be.id===V.id)continue;const Ie=Re(Be);Number.isFinite(Ie)&&(Ie>=Ee||(Ee=Ie,ke=Be))}return ke||void 0},[]),X=o.useCallback(W=>{var P;const w=ee(W);if(!w)return;const R=w.activePanel||w.panels[0];R&&(w.model.openPanel(R),R.api.setActive(),At(R.id)||re(R.id,"dockview-focus"),Pn((P=w.element)==null?void 0:P.ownerDocument))},[ee,re]),J=o.useCallback((W,w)=>{const R=k.current,P=R==null?void 0:R.activePanel,V=(R==null?void 0:R.activeGroup)||(P==null?void 0:P.group);if(!R||!P||!V)return;let Z=ee(W);!Z&&(w!=null&&w.createGroupIfMissing)&&(Z=R.addGroup({referenceGroup:V,direction:W})),Z&&(P.api.moveTo({group:Z,position:"center"}),P.group.model.openPanel(P),P.api.setActive(),At(P.id)||re(P.id,w!=null&&w.createGroupIfMissing?"dockview-split":"dockview-move"))},[ee,re]),{isMac:de,tabShortcuts:D,shortcutListening:ie,setShortcutListening:Q,saveShortcuts:we}=al({sortedTabKeys:e.map(W=>W.tabKey),onFocus:ve,onSelectTab:oe}),Ne=o.useCallback(()=>{var R;const W=k.current;if(!W)return;const w=W.activePanel;if(w){if(At(w.id)){const P=((R=w.params)==null?void 0:R.routeId)||w.id.slice(7),V=_t(e,P);V!=null&&V.tabKey&&Q(V.tabKey);return}z.has(w.id)&&Q(w.id)}},[z,oe,Q,e]),Ae=o.useCallback(W=>{const w=[];return W.metaKey&&w.push(de?"⌘":"Meta"),W.ctrlKey&&w.push("Ctrl"),W.altKey&&w.push(de?"⌥":"Alt"),W.shiftKey&&W.key.length!==1&&w.push(de?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(W.key)?null:(w.push(ll(W.key)),w.join("+"))},[de]),Me=o.useCallback(W=>{var w,R;switch(W){case"splitActiveTabRight":J("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":J("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const P=ce();P&&q(P);return}case"popoutActiveTab":{const P=ce();P&&be(P);return}case"dockActiveTab":{const P=ce();if(!P)return;G(P)?ge(P):ue(P)&&je(P);return}case"focusLeftPane":X("left");return;case"focusRightPane":X("right");return;case"focusUpPane":X("above");return;case"focusDownPane":X("below");return;case"moveActiveTabToLeftPane":J("left");return;case"moveActiveTabToRightPane":J("right");return;case"moveActiveTabToUpPane":J("above");return;case"moveActiveTabToDownPane":J("below");return;case"selectPreviousGroupTab":te(-1);return;case"selectNextGroupTab":te(1);return;case"setActiveTabShortcut":Ne();return;case"hideCurrentTab":{const P=(R=(w=k.current)==null?void 0:w.activePanel)==null?void 0:R.id;P&&!At(P)&&ne(P);return}default:return}},[te,je,X,q,ce,ne,ue,G,ge,J,be,Ne]);o.useEffect(()=>{if(!T)return;const W=T.sourceDocument,w=W.defaultView??window,R=P=>{const V=W.querySelector("[data-dockview-tab-context-menu]");V&&V.contains(P.target)||A(null)};return w.addEventListener("mousedown",R,!0),w!==window&&window.addEventListener("mousedown",()=>A(null),!0),()=>{w.removeEventListener("mousedown",R,!0),w!==window&&window.removeEventListener("mousedown",()=>A(null),!0)}},[T]);const Ue=o.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:z,hasDetachedConversationPanels:Y,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:N,liveSessionInboxState:I,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:ne,userName:m,scrollToBottomRequest:C,tabShortcuts:D,openTabContextMenu:({x:W,y:w,tabKey:R,sourceDocument:P})=>A({x:W,y:w,tabKey:R,sourceDocument:P??document}),popoutTab:be,moveTabBackToMain:ge,isTabInPopout:G,floatTab:q,isTabFloating:ue}),[n,t,z,Y,r,c,l,N,I,a,i,ne,m,C,D,be,ge,G,q,ue]),We=T?fx({isTabInPopout:G(T.tabKey),isTabFloating:ue(T.tabKey),tabShortcut:D[T.tabKey],actionShortcuts:h}):[],Ke=o.useCallback(W=>{var P;const w=k.current;if((((P=w==null?void 0:w.activePanel)==null?void 0:P.id)??null)===W.id){W.group.model.openPanel(W);return}W.group.model.openPanel(W),W.api.setActive()},[]),Ge=o.useCallback((W,w="requested-tab")=>{if(!W)return!1;const R=k.current;if(!R)return!1;const P=R.getPanel(W);return P?(Ke(P),re(W,w),g==null||g(),!0):!1},[Ke,g,re]),Ze=o.useCallback(()=>{if(H.current)return!1;const W=Ge(F.current,"stored-layout-restore");return W&&(H.current=!0),W},[Ge]),Je=o.useCallback(()=>{var w;const W=k.current;W&&Gp(v,{activeTabId:((w=W.activePanel)==null?void 0:w.id)??null,layout:W.toJSON()})},[v]),Ye=o.useCallback(()=>{Yp(v,E.current)},[v]),mt=o.useCallback(W=>{var P,V,Z,me;const w=k.current;if(!w)return{kind:"grid"};const R=w.toJSON();for(const he of R.floatingGroups||[])if((V=(P=he.data)==null?void 0:P.views)!=null&&V.includes(W)&&he.position)return{kind:"floating",position:he.position};for(const he of R.popoutGroups||[])if((me=(Z=he.data)==null?void 0:Z.views)!=null&&me.includes(W))return{kind:"popout",position:he.position,popoutUrl:he.url};return{kind:"grid"}},[]),pt=o.useCallback(W=>{const w=k.current;if(!w)return;const R=w.getPanel(W),P=E.current[W];if(!R||!P||P.kind==="grid")return;if(R.group.model.location.type===P.kind){delete E.current[W],Ye();return}if(P.kind==="floating"){w.addFloatingGroup(R,{x:P.position.left??24,y:P.position.top??24,width:P.position.width,height:P.position.height}),delete E.current[W],Ye();return}delete E.current[W],Ye()},[Ye]);o.useEffect(()=>(f==null||f({setShortcutForActiveTab:Ne,restoreHiddenTabToSavedLocation:pt,activateConversationTab:oe,resetAllPanelsToMain:ae,activatePreviousTabInGroup:()=>te(-1),activateNextTabInGroup:()=>te(1),floatActiveTab:()=>{const W=ce();W&&q(W)},popoutActiveTab:()=>{const W=ce();W&&be(W)},dockActiveTab:()=>{const W=ce();W&&(G(W)?ge(W):ue(W)&&je(W))},splitActiveTabRight:()=>J("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>J("below",{createGroupIfMissing:!0}),focusLeftPane:()=>X("left"),focusRightPane:()=>X("right"),focusUpPane:()=>X("above"),focusDownPane:()=>X("below"),moveActiveTabToLeftPane:()=>J("left"),moveActiveTabToRightPane:()=>J("right"),moveActiveTabToUpPane:()=>J("above"),moveActiveTabToDownPane:()=>J("below")}),()=>f==null?void 0:f(null)),[te,je,q,X,ce,ue,G,J,ge,be,f,ae,pt,oe,Ne]),o.useEffect(()=>()=>{var W;(W=B.current)==null||W.call(B),B.current=null},[]);const dt=o.useCallback(W=>{var R,P;k.current=W.api,(R=B.current)==null||R.call(B),B.current=null;const w=Vp(v);if(F.current=(w==null?void 0:w.activeTabId)??null,w!=null&&w.layout&&W.api.fromJSON(w.layout,{reuseExistingPanels:!1}),_.current=ti({hasStoredLayout:!!(w!=null&&w.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:r}),_.current||(ni(W.api,e),ai(W.api,e,y)),W.api.totalPanels===0&&e.length>0){const V=vx(W.api,e,x);if(V){const Z=W.api.getPanel(V);Z&&Ke(Z)}}else!_.current&&!Ge(x)&&Ze();if(L.current=!0,W.api.onDidActivePanelChange(V=>{var me;if(F.current=(V==null?void 0:V.id)??null,H.current=!0,fe(),V&&At(V.id)){const he=((me=V.params)==null?void 0:me.routeId)||V.id.slice(7),Se=_t(e,he);j((Se==null?void 0:Se.tabKey)??null),Je();return}if(j((V==null?void 0:V.id)??null),Je(),!V)return;const Z=z.get(V.id);(Z==null?void 0:Z.streamSource)==="agent-stream"&&Z.agentType&&S(Z.routeId,Qc(),{agentType:Z.agentType,...Z.sessionId&&{targetSessionId:Z.sessionId}}).catch(()=>{})}),W.api.onDidLayoutChange(()=>{Je(),fe(),$(V=>V+1)}),xx()){const V=ke=>({clientX:ke.clientX,clientY:ke.clientY}),Z=ke=>{var $e;const Ee=($e=b.current)==null?void 0:$e.getBoundingClientRect();return Ee?ke.clientX<Ee.left||ke.clientX>Ee.right||ke.clientY<Ee.top||ke.clientY>Ee.bottom:!1},me=hx({detachDelayMs:ul,onDetach:({panelId:ke,clientX:Ee,clientY:$e})=>{var Le,et;const Be=W.api.getPanel(ke);if(!Be)return;try{if(Be.group.model.location.type!=="grid")return}catch{return}const Ie=(Le=b.current)==null?void 0:Le.getBoundingClientRect(),qe=(et=Be.group.element)==null?void 0:et.getBoundingClientRect(),ct=Math.round(Math.min(Math.max((qe==null?void 0:qe.width)??600,360),720)),pe=Math.round(Math.min(Math.max((qe==null?void 0:qe.height)??500,260),640));W.api.addFloatingGroup(Be,{x:Ie?Math.max(0,Ee-Ie.left-32):void 0,y:Ie?Math.max(0,$e-Ie.top-18):void 0,width:ct,height:pe}),Be.api.setActive(),Je(),fe(),$(nt=>nt+1)}}),he=[W.api.onWillDragPanel(ke=>{if(!(ke.nativeEvent.defaultPrevented||ke.nativeEvent.shiftKey)){try{if(ke.panel.group.model.location.type!=="grid")return}catch{return}me.startDrag({panelId:ke.panel.id,...V(ke.nativeEvent)})}}),W.api.onWillShowOverlay(ke=>{if(me.hasDetached()){ke.preventDefault();return}me.markDockTarget(V(ke.nativeEvent))}),W.api.onWillDrop(ke=>{if(me.hasDetached()){ke.preventDefault(),me.endDrag();return}me.markDockTarget(V(ke.nativeEvent))}),W.api.onDidDrop(()=>me.endDrag()),W.api.onUnhandledDragOverEvent(ke=>{me.isDragging()&&me.markNoDropTarget(V(ke.nativeEvent))})],Se=ke=>{if(!me.isDragging())return;const Ee=V(ke);Z(Ee)&&me.markNoDropTarget(Ee)},Re=()=>me.endDrag();window.addEventListener("dragover",Se,!0),window.addEventListener("drop",Re,!0),window.addEventListener("dragend",Re,!0),B.current=()=>{me.dispose();for(const ke of he)ke.dispose();window.removeEventListener("dragover",Se,!0),window.removeEventListener("drop",Re,!0),window.removeEventListener("dragend",Re,!0)}}W.api.onDidAddGroup(V=>{requestAnimationFrame(()=>{var Z,me;try{const he=(Z=V.element)==null?void 0:Z.ownerDocument;if(!he||he===document)return;(me=he.getElementById("dv-popout-window"))==null||me.classList.add("adhdev-dockview");const Se=document.documentElement.getAttribute("data-theme");Se&&he.documentElement.setAttribute("data-theme",Se),he.body.className=document.body.className;const Re=document.documentElement.getAttribute("style");Re&&he.documentElement.setAttribute("style",Re)}catch{}fe(),$(he=>he+1)})}),j(((P=W.api.activePanel)==null?void 0:P.id)??null)},[Ke,Ge,z,r,u,v,j,Je,x,y,S,fe,e]);o.useLayoutEffect(()=>{const W=k.current;if(!W||!L.current||_.current&&ti({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:r}))return;_.current&&(_.current=!1);const w=O.current,R=new Set(w),P=e.map(ke=>ke.tabKey),V=new Set(P),Z=px({previousVisibleConversationCount:w.length,visibleConversationCount:e.length,ides:r});let me=!1;for(const ke of w)V.has(ke)||Z||(E.current[ke]=mt(ke),me=!0);me&&Ye(),Z||(ni(W,e),ai(W,e,y));const he=P.filter(ke=>!R.has(ke));let Se=!1;for(const ke of he){const Ee=W.getPanel(ke),$e=E.current[ke];if(!Ee||!$e||$e.kind==="grid")continue;if(Ee.group.model.location.type===$e.kind){delete E.current[ke],Se=!0;continue}if($e.kind==="floating"){W.addFloatingGroup(Ee,{x:$e.position.left??24,y:$e.position.top??24,width:$e.position.width,height:$e.position.height}),delete E.current[ke],Se=!0;continue}}if(Se&&Ye(),O.current=P,x&&Ge(x))return;!W.activePanel&&W.panels[0]&&Ke(W.panels[0]),!!(W.activePanel&&W.getPanel(W.activePanel.id))||Ze()},[Ke,Ge,Ze,r,u,Ye,mt,x,y,e]),o.useEffect(()=>{L.current&&Ge(x)},[Ge,x]),o.useEffect(()=>{const W=R=>{const P=R.target;if(!P)return;const V=P.querySelector("[data-tab-key]")||P.closest("[data-tab-key]");if(V){const Z=V.getAttribute("data-tab-key");if(Z&&R.dataTransfer){const me=P.closest(".dv-tab")||V.closest(".dv-tab")||V;R.dataTransfer.effectAllowed="move",R.dataTransfer.setData("text/tab-key",Z),me instanceof HTMLElement&&R.dataTransfer.setDragImage(me,Math.max(12,Math.round(me.clientWidth/2)),Math.max(10,Math.round(me.clientHeight/2)))}}};window.addEventListener("dragstart",W);const w=ri(k.current);for(const R of w)R.addEventListener("dragstart",W);return()=>{window.removeEventListener("dragstart",W);for(const R of w)R.removeEventListener("dragstart",W)}},[U]),o.useEffect(()=>{var w;const W=(w=b.current)==null?void 0:w.querySelector(".adhdev-dockview");W instanceof HTMLElement&&Dn(W,M),le(),fe()},[fe,le,M]),o.useEffect(()=>{fe()},[fe]),o.useEffect(()=>{const W=w=>{if(w.defaultPrevented||ie)return;const R=Ae(w);if(!R)return;const P=w.metaKey||w.ctrlKey||w.altKey;fa(w.target)&&!P||qr(de).setActiveTabShortcut!==R||(w.preventDefault(),w.stopPropagation(),Ne())};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[Ae,de,ie,Ne]),o.useEffect(()=>{const W=b.current;if(!W)return;const w=R=>{var he,Se;if(!R.isTrusted)return;const P=(Se=(he=R.target)==null?void 0:he.closest)==null?void 0:Se.call(he,".dv-scrollable");if(!P)return;R.preventDefault(),R.stopPropagation();const V=Math.abs(R.deltaX),Z=Math.abs(R.deltaY),me=V>Z?R.deltaX:R.deltaY;P.dispatchEvent(new WheelEvent("wheel",{deltaY:me,deltaMode:R.deltaMode,bubbles:!1,cancelable:!0}))};return W.addEventListener("wheel",w,{passive:!1,capture:!0}),()=>W.removeEventListener("wheel",w,{capture:!0})},[]),o.useEffect(()=>{const W=ri(k.current);if(W.length===0)return;const w=W.map(R=>{let P=[],V=null;const Z=()=>{V!=null&&R.clearTimeout(V),V=null,P=[]},me=()=>{V!=null&&R.clearTimeout(V),V=R.setTimeout(()=>{V=null,P=[]},1200)},he=Re=>{if(!Re.ctrlKey&&!Re.metaKey&&!Re.altKey)return;const ke=Ae(Re);if(!ke)return;const Ee=nl();for(const[$e,Be]of Object.entries(Ee))if(e.some(Ie=>Ie.tabKey===$e)&&Be===ke){Re.preventDefault(),oe($e);return}},Se=Re=>{if(Re.defaultPrevented||ie)return;const ke=Ae(Re);if(!ke)return;const Ee=Re.metaKey||Re.ctrlKey||Re.altKey;if(fa(Re.target)&&!Ee)return;const $e=qr(de),Be=Object.entries($e).filter(([Oe,Mt])=>!!Mt&&(Oe==="splitActiveTabRight"||Oe==="splitActiveTabDown"||Oe==="floatActiveTab"||Oe==="popoutActiveTab"||Oe==="dockActiveTab"||Oe==="focusLeftPane"||Oe==="focusRightPane"||Oe==="focusUpPane"||Oe==="focusDownPane"||Oe==="moveActiveTabToLeftPane"||Oe==="moveActiveTabToRightPane"||Oe==="moveActiveTabToUpPane"||Oe==="moveActiveTabToDownPane"||Oe==="selectPreviousGroupTab"||Oe==="selectNextGroupTab"||Oe==="setActiveTabShortcut"||Oe==="hideCurrentTab")),Ie=Ee?[ke]:[...P.slice(-1),ke].slice(-2),qe=Ie.join(" "),ct=Ie[Ie.length-1],pe=Be.find(([,Oe])=>Oe===qe);if(pe){Re.preventDefault(),Z(),Me(pe[0]);return}if(Be.some(([,Oe])=>Oe.startsWith(`${qe} `))){Re.preventDefault(),P=Ie,me();return}const et=Be.find(([,Oe])=>Oe===ct);if(et){Re.preventDefault(),Z(),Me(et[0]);return}if(Be.some(([,Oe])=>Oe.startsWith(`${ct} `))){Re.preventDefault(),P=[ct],me();return}Z()};return R.addEventListener("keydown",he),R.addEventListener("keydown",Se),()=>{Z(),R.removeEventListener("keydown",he),R.removeEventListener("keydown",Se)}});return()=>{for(const R of w)R()}},[Ae,de,U,oe,ie,Me,e]);const Ce=M==="light"?qn:Yn,He=((ft=(ot=(Xe=k.current)==null?void 0:Xe.activePanel)==null?void 0:ot.group.element)==null?void 0:ft.ownerDocument)??document;return s.jsxs(ml.Provider,{value:Ue,children:[s.jsx("div",{ref:b,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(rd,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:wx,remote:jx},defaultTabComponent:Sx,watermarkComponent:kx,onReady:dt,singleTabMode:"default",tabAnimation:"smooth",theme:Ce,popoutUrl:"/popout.html"})}),T&&Js.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:T.x,top:T.y},children:We.map(W=>{if(W.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},W.id);let w=s.jsx(Jd,{size:13,className:"shrink-0 opacity-70"}),R=()=>{};switch(W.id){case"dockInWindow":case"dockBackToGrid":w=s.jsx(Zd,{size:13,className:"shrink-0 opacity-70"}),R=()=>{je(T.tabKey),A(null)};break;case"moveBackToMain":w=s.jsx(Xd,{size:13,className:"shrink-0 opacity-70"}),R=()=>{ge(T.tabKey),A(null)};break;case"floatAsPanel":w=s.jsx(Qd,{size:13,className:"shrink-0 opacity-70"}),R=()=>{q(T.tabKey),A(null)};break;case"openInNewWindow":w=s.jsx(Yd,{size:13,className:"shrink-0 opacity-70"}),R=()=>{be(T.tabKey),A(null)};break;case"setShortcut":R=P=>{P.stopPropagation(),Q(T.tabKey),A(null)};break;case"removeShortcut":w=s.jsx(vt,{size:13,className:"shrink-0 opacity-70"}),R=()=>{const P={...D};delete P[T.tabKey],we(P),A(null)};break;case"hideTab":w=s.jsx(Pi,{size:13,className:"shrink-0 opacity-70"}),R=()=>{ne(T.tabKey),A(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${W.tone==="muted"?"text-text-muted":""}`,onMouseDown:gx,onClick:R,children:[w,s.jsx("span",{className:"flex-1 min-w-0",children:W.label}),W.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:W.shortcut}):null]},W.id)})}),T.sourceDocument.body),ie&&Js.createPortal(s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>Q(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:W=>W.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. ",de?"⌘+1":"Ctrl+1",", ",de?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),He.body)]})}const fl="adhdev-recent-launch-args-v1",Cx=8;function Tx(e){return String(e||"").trim().replace(/\s+/g," ")}function pl(e,t){return`${e.trim()}::${t.trim()}`}function hl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(fl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Mx(e){if(!(typeof window>"u"))try{window.localStorage.setItem(fl,JSON.stringify(e))}catch{}}function xl(e,t){var i;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((i=hl().byKey[pl(r,n)])==null?void 0:i.items)||[]}function bl(e,t,r){var d;const n=String(e||"").trim(),a=String(t||"").trim(),i=Tx(r);if(!n||!a||!i)return;const c=hl(),l=pl(n,a),u=((d=c.byKey[l])==null?void 0:d.items)||[],m=[i,...u.filter(h=>h!==i)].slice(0,Cx);c.byKey[l]={items:m},Mx(c)}function gl(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Pr({title:e,description:t,action:r,children:n,className:a="",contentClassName:i=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),r?s.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?s.jsx("div",{className:t||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function yl({busy:e,savedSessionsLoading:t,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?tl(n):null;return s.jsxs(Pr,{title:"Saved history",description:Ba(),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:Af()})]}),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 En(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>us(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>us(a,"acp"))?"acp":null}function Sr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ix({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:c,onListSavedSessions:l}){var ft,W;const u=ir(),m=o.useMemo(()=>[...e].sort(Ca),[e]),[d,h]=o.useState(((ft=m[0])==null?void 0:ft.id)||""),f=o.useMemo(()=>m.find(w=>w.id===d)||m[0],[d,m]),j=o.useMemo(()=>((f==null?void 0:f.workspaces)||[]).map(w=>({id:w.id,path:w.path,label:w.label})),[f]),N=(f==null?void 0:f.defaultWorkspaceId)||null,[p,x]=o.useState(""),[y,g]=o.useState(""),[C,I]=o.useState(En(m[0])),[v,M]=o.useState(""),[S,k]=o.useState(""),[b,B]=o.useState([]),[L,_]=o.useState(""),[H,F]=o.useState([]),[O,T]=o.useState(!1),[A,U]=o.useState(!1),[$,E]=o.useState(""),[z,Y]=o.useState(!1),[ve,re]=o.useState(()=>ht()),[ye,le]=o.useState(null),[be,ge]=o.useState(!1),[G,ne]=o.useState(""),[q,ue]=o.useState(!1),[ce,je]=o.useState(""),[ae,fe]=o.useState([]),[oe,te]=o.useState(!1),[ee,X]=o.useState(""),[J,de]=o.useState(!1),D=o.useRef(null),ie=o.useRef(0);o.useEffect(()=>{var w;!d&&((w=m[0])!=null&&w.id)&&h(m[0].id)},[d,m]),o.useEffect(()=>{!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||u(f.id,{minFreshMs:3e4}).catch(()=>{})},[u,f]);const Q=o.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(w=>us(w,"cli")),[f]),we=o.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(w=>us(w,"acp")),[f]),Ne=o.useMemo(()=>((f==null?void 0:f.detectedIdes)||[]).map(w=>({id:w.type,label:w.name||w.type,meta:w.running?"Detected locally":"Available to open"})),[f]),Ae=o.useMemo(()=>C==="cli"?Q.map(w=>({id:w.type,label:w.displayName||w.type,meta:"CLI provider"})):C==="acp"?we.map(w=>({id:w.type,label:w.displayName||w.type,meta:"ACP provider"})):Ne,[we,C,Q,Ne]);o.useEffect(()=>{var R;if(!f)return;if(D.current!==f.id){D.current=f.id,x(N||((R=j[0])==null?void 0:R.id)||"__home__"),g(""),I(En(f)),M(""),k(""),_(""),F([]),U(!1),E(""),re(ht()),ne("");return}x(P=>{var V;return P==="__custom__"||P==="__home__"||j.some(Z=>Z.id===P)?P:N||((V=j[0])==null?void 0:V.id)||"__home__"}),I(P=>P==="ide"&&Ne.length>0||P==="cli"&&Q.length>0||P==="acp"&&we.length>0?P:En(f))},[we.length,Q.length,N,Ne.length,f,j]),o.useEffect(()=>{var w;C&&(Ae.some(R=>R.id===v)||M(((w=Ae[0])==null?void 0:w.id)||""))},[C,Ae,v]);const Me=o.useCallback(async(w,R)=>{const P=ie.current+1;return ie.current=P,T(!0),E(""),l(w,R).then(V=>{ie.current===P&&F(V)}).catch(V=>{ie.current===P&&(F([]),E(V instanceof Error?V.message:"Could not load saved sessions"))}).finally(()=>{ie.current===P&&(T(!1),U(!0))})},[l]),Ue=o.useCallback((w,R)=>{B(xl(w,R))},[]);o.useEffect(()=>{ie.current+=1,_(""),re(ht()),!f||!v||C==="ide"?B([]):Ue(f.id,v),U(!1),F([]),E(""),T(!1)},[C,Ue,Me,f,v]),o.useEffect(()=>{if(!L)return;const w=H.find(R=>R.providerSessionId===L);w!=null&&w.canResume||_("")},[H,L]);const We=p==="__custom__"?y.trim():p==="__home__"?"":((W=j.find(w=>w.id===p))==null?void 0:W.path)||"",Ke=o.useMemo(()=>f?t.filter(w=>w.id!==f.id&&w.daemonId===f.id).map(w=>w.workspace):[],[t,f]),Ge=o.useMemo(()=>((f==null?void 0:f.recentLaunches)||[]).map(w=>w.workspace),[f]),Ze=o.useCallback(w=>{const R=String(w.workspace||"").trim();if(!R)return;const P=j.find(V=>Sr(V.path)===Sr(R));if(P){x(P.id),g("");return}x("__custom__"),g(R)},[j]),Je=o.useCallback(w=>{const R=String(w.workspace||"").trim();if(!R)return{workspaceId:null,workspacePath:null};const P=j.find(V=>Sr(V.path)===Sr(R));return P?{workspaceId:P.id,workspacePath:null}:{workspaceId:null,workspacePath:R}},[j]),Ye=o.useMemo(()=>H.find(w=>w.providerSessionId===L)||null,[H,L]),mt=o.useMemo(()=>{var R;if(C!=="cli"||!f||!v)return null;const w=((R=Q.find(P=>P.type===v))==null?void 0:R.displayName)||v;return{routeId:f.id,daemonId:f.id,providerSessionId:L||void 0,transport:"pty",mode:"chat",agentName:w,agentType:v,status:"idle",title:w,messages:[],ideType:v,workspaceName:We,displayPrimary:w,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${f.id}:${v}`,machineName:Tt(f,{fallbackId:f.id})}},[C,Q,We,f,L,v]),pt=o.useCallback(()=>{var R;if(!f)return;x("__custom__"),ue(!0),X("");const w=nn(f.platform,rn(y.trim(),We,Ke,Ge,f.defaultWorkspacePath,(R=j.find(P=>P.id===N))==null?void 0:R.path,j.map(P=>P.path)));te(!0),n(f.id,w).then(P=>{je(P.path),g(P.path),fe(P.directories)}).catch(P=>{X(P instanceof Error?P.message:"Could not load folder")}).finally(()=>te(!1))},[y,N,Ge,Ke,n,We,f,j]),dt=o.useCallback(w=>{f&&(te(!0),X(""),n(f.id,w).then(R=>{je(R.path),g(R.path),fe(R.directories)}).catch(R=>{X(R instanceof Error?R.message:"Could not load folder")}).finally(()=>te(!1)))},[n,f]),Ce=o.useCallback(async()=>{if(!f||!We)return;de(!0),ne("");const w=await a(f.id,We);if(de(!1),!w.ok){ne(w.error||"Could not save workspace");return}ne("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,We,f]),He=o.useCallback(async()=>{if(!f||!C||!v)return;ge(!0),ne("");const w=S.trim()?S.trim().split(/\s+/).filter(Boolean):[],R=C==="ide"?await i(f.id,v,{workspacePath:We||null}):await c(f.id,C,v,{workspaceId:p!=="__home__"&&p!=="__custom__"?p:null,workspacePath:p==="__custom__"&&We||null,resumeSessionId:C==="cli"&&L?L:null,cliArgs:w});if(ge(!1),!R.ok){ne(R.error||"Could not start session");return}C!=="ide"&&S.trim()&&(bl(f.id,v,S),Ue(f.id,v)),r()},[C,S,Ue,r,i,c,We,f,L,v,p]),Xe=C?kc(C,C==="cli"&&!!L):"Start",ot=C?Sc(C,C==="cli"&&!!L):"Starting…";return f?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[s.jsx(Pr,{title:"Machine",children:s.jsx("select",{value:f.id,onChange:w=>h(w.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:be,children:m.map(w=>s.jsx("option",{value:w.id,children:Tt(w,{fallbackId:w.id})},w.id))})}),s.jsxs(Pr,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:pt,disabled:be,children:"Browse…"}),children:[s.jsxs("select",{value:p,onChange:w=>{const R=w.target.value;x(R),R==="__custom__"?pt():ne("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:be,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),j.map(w=>s.jsxs("option",{value:w.id,children:[w.id===N?"⭐ ":"",en(w.path,w.label)||w.path]},w.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:p==="__home__"?"Launch without a workspace.":We||"Select a workspace folder."}),p==="__custom__"&&We&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:pt,disabled:be,children:[s.jsx(Ss,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ce,disabled:be||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:Q.length>0},{id:"ide",label:"IDE",enabled:Ne.length>0},{id:"acp",label:"ACP",enabled:we.length>0}].map(w=>s.jsx("button",{type:"button",className:`btn btn-sm ${C===w.id?"btn-primary":"btn-secondary"}`,onClick:()=>I(w.id),disabled:!w.enabled||be,children:w.label},w.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:C==="ide"?"Choose IDE":C==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Ae.map(w=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===w.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>M(w.id),disabled:be,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:w.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:w.meta})]},w.id)),Ae.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),C!=="ide"&&s.jsxs(Pr,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:S,onChange:w=>k(w.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:be}),b.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:b.map(w=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>k(w),disabled:be,title:w,children:w},w))})]}),C==="cli"&&s.jsx(yl,{busy:be,savedSessionsLoading:O,savedSessionsError:$,selectedSession:Ye,onRefresh:()=>{!f||!v||Me(f.id,v)},onOpenHistory:()=>{!f||!v||(Y(!0),gl({hasLoadedInitialResults:A,isLoading:O})&&Me(f.id,v))},onClearSelection:()=>_("")}),G&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${G.includes("saved")||G.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:G})]}),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:be,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:He,disabled:be||!C||!v||p==="__custom__"&&!We,children:[s.jsx(ka,{size:14}),be?ot:Xe]})]})]})}),q&&s.jsx(cn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:ce,directories:ae,busy:oe,error:ee,onClose:()=>ue(!1),onNavigate:dt,onConfirm:w=>{g(w),je(w),x("__custom__"),ue(!1)}}),z&&mt&&s.jsx(Wa,{activeConv:mt,ides:[],isCreatingChat:!1,isRefreshingHistory:O,savedSessions:H,isSavedSessionsLoading:O,isResumingSavedSessionId:ye,savedHistoryFilters:ve,onSavedHistoryFiltersChange:re,onClose:()=>Y(!1),onNewChat:()=>{_(""),Y(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!f||!v||Me(f.id,v)},onResumeSavedSession:w=>{if(!f||!v||ye||!w.canResume)return;const R=Je(w);_(w.providerSessionId),Ze(w),le(w.providerSessionId),Y(!1),ge(!0),ne(""),c(f.id,"cli",v,{workspaceId:R.workspaceId,workspacePath:R.workspacePath,resumeSessionId:w.providerSessionId}).then(P=>{if(!P.ok){ne(P.error||"Could not resume session");return}r()}).finally(()=>{ge(!1),le(P=>P===w.providerSessionId?null:P)})}})]}):null}function Ax({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=o.useState(!1),[i,c]=o.useState(!1),[l,u]=o.useState(!1),[m,d]=o.useState(!1),[h,f]=o.useState(!1),[j,N]=o.useState("quickstart"),[p,x]=o.useState("workspace"),y=o.useMemo(()=>!t&&!e,[t,e]),g=o.useCallback(k=>{a(k),k&&c(!1)},[]),C=o.useCallback(k=>{c(k),k&&a(!1)},[]),I=o.useCallback(()=>{N(r===0?"quickstart":"shortcuts"),x("workspace"),u(!0),a(!1),c(!1)},[r]),v=o.useCallback(()=>{u(!1)},[]),M=o.useCallback(()=>{d(!0)},[]),S=o.useCallback(()=>{d(!1)},[]);return o.useEffect(()=>{if(!y){f(!1);return}f(!0);const k=window.setTimeout(()=>{f(!1)},1e4);return()=>window.clearTimeout(k)},[y]),{inboxOpen:n,hiddenOpen:i,shortcutHelpOpen:l,newSessionOpen:m,guideNudgeVisible:h,guideTab:j,shortcutSection:p,isDesktopDashboard:y,setGuideTab:N,setShortcutSection:x,handleInboxOpenChange:g,handleHiddenOpenChange:C,handleOpenShortcutHelp:I,closeShortcutHelp:v,openNewSession:M,closeNewSession:S}}function Lx(e){switch(e.id){case"triggerPrimaryApprovalAction":case"triggerSecondaryApprovalAction":case"triggerTertiaryApprovalAction":return"approvals";case"splitActiveTabRight":case"splitActiveTabDown":case"focusLeftPane":case"focusRightPane":case"focusUpPane":case"focusDownPane":case"moveActiveTabToLeftPane":case"moveActiveTabToRightPane":case"moveActiveTabToUpPane":case"moveActiveTabToDownPane":return"panes";default:return"workspace"}}function Rx(e){return e instanceof Error?e.message:String(e||"")}function _x(e){const t=Rx(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Px({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetActiveCliViewMode:m,mobileChatConversations:d,hiddenConversations:h,ides:f,actionLogs:j,sendDaemonCommand:N,setActionLogs:p,setCliViewModeOverrides:x,isStandalone:y,initialDataLoaded:g,userName:C,requestedMobileTabKey:I,onRequestedMobileTabConsumed:v,requestedMachineId:M,onRequestedMachineConsumed:S,requestedMobileSection:k,onRequestedMobileSectionConsumed:b,containerRef:B,isSplitMode:L,numGroups:_,groupSizes:H,groupedConvs:F,clearedTabs:O,focusedGroup:T,focusGroup:A,moveTabToGroup:U,splitTabRelative:$,closeGroup:E,handleResizeStart:z,groupActiveTabIds:Y,setGroupActiveTab:ve,groupTabOrders:re,setGroupTabOrder:ye,toggleHiddenTab:le,visibleConversations:be,requestedDesktopTabKey:ge,onRequestedDesktopTabConsumed:G,onDesktopActiveTabChange:ne,onRequestScrollToBottom:q,onHideConversation:ue,onShowHiddenConversation:ce,onShowAllHiddenConversations:je,scrollToBottomRequest:ae,machineEntries:fe,layoutProfile:oe,onBrowseMachineDirectory:te,onSaveMachineWorkspace:ee,onLaunchMachineIde:X,onLaunchMachineProvider:J,onListMachineSavedSessions:de,notifications:D,notificationUnreadCount:ie,liveSessionInboxState:Q,onMarkNotificationRead:we,onMarkNotificationUnread:Ne,onDeleteNotification:Ae}){const Me=jt.useRef(null),{inboxOpen:Ue,hiddenOpen:We,shortcutHelpOpen:Ke,newSessionOpen:Ge,guideNudgeVisible:Ze,guideTab:Je,shortcutSection:Ye,isDesktopDashboard:mt,setGuideTab:pt,setShortcutSection:dt,handleInboxOpenChange:Ce,handleHiddenOpenChange:He,handleOpenShortcutHelp:Xe,closeShortcutHelp:ot,openNewSession:ft,closeNewSession:W}=Ax({isMobile:t,showMobileChatMode:e,visibleConversationCount:be.length}),w=jt.useCallback(pe=>{var Le;Js.flushSync(()=>{ce(pe)}),(Le=Me.current)==null||Le.restoreHiddenTabToSavedLocation(pe.tabKey)},[ce]),R=jt.useCallback(pe=>{var et;const Le=d.find(nt=>ra(nt,pe))||h.find(nt=>ra(nt,pe));Le&&(h.some(nt=>nt.tabKey===Le.tabKey)&&w(Le),ne(Le.tabKey),(et=Me.current)==null||et.activateConversationTab(Le.tabKey),q(Le.tabKey,"notification-open")),we(pe.id),Ce(!1)},[w,h,d,ne,we,q]),P=jt.useCallback(()=>{var Le;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Le=Me.current)==null||Le.resetAllPanelsToMain(),He(!1))},[He]),V=jt.useCallback(async pe=>{var Mt;if(!r)return;const Le=(Mt=r.modalButtons)==null?void 0:Mt[pe];if(!Le)return;const et=sr(r);if(!et)return;const nt=Le.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Oe=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(nt);try{await N(et,"resolve_action",{button:Le,action:Oe?"approve":"reject",buttonIndex:pe,...ws(r)})}catch(K){_x(K)||console.error("[Shortcut approval] Failed:",K)}},[r,N]),{isMac:Z,actionDefinitions:me,actionShortcuts:he,shortcutListening:Se,shortcutListeningDraft:Re,setShortcutListening:ke,setShortcutListeningDraft:Ee,saveShortcuts:$e}=mx({enabled:mt&&!Ke,onTrigger:pe=>{var Le,et,nt,Oe,Mt,K,se,xe,Pe,Te,_e,tt,yt,ut,Ht,lr;if(pe==="openShortcutHelp"){Xe();return}if(pe==="hideCurrentTab"){r&&ue(r);return}if(pe==="toggleHiddenTabs"){He(!We);return}if(pe==="openHistoryForActiveTab"){r&&!Ve(r)&&i(r);return}if(pe==="openRemoteForActiveTab"){r&&!Qe(r)&&!Ve(r)&&c(r);return}if(pe==="splitActiveTabRight"){(Le=Me.current)==null||Le.splitActiveTabRight();return}if(pe==="splitActiveTabDown"){(et=Me.current)==null||et.splitActiveTabDown();return}if(pe==="floatActiveTab"){(nt=Me.current)==null||nt.floatActiveTab();return}if(pe==="popoutActiveTab"){(Oe=Me.current)==null||Oe.popoutActiveTab();return}if(pe==="dockActiveTab"){(Mt=Me.current)==null||Mt.dockActiveTab();return}if(pe==="focusLeftPane"){(K=Me.current)==null||K.focusLeftPane();return}if(pe==="focusRightPane"){(se=Me.current)==null||se.focusRightPane();return}if(pe==="focusUpPane"){(xe=Me.current)==null||xe.focusUpPane();return}if(pe==="focusDownPane"){(Pe=Me.current)==null||Pe.focusDownPane();return}if(pe==="moveActiveTabToLeftPane"){(Te=Me.current)==null||Te.moveActiveTabToLeftPane();return}if(pe==="moveActiveTabToRightPane"){(_e=Me.current)==null||_e.moveActiveTabToRightPane();return}if(pe==="moveActiveTabToUpPane"){(tt=Me.current)==null||tt.moveActiveTabToUpPane();return}if(pe==="moveActiveTabToDownPane"){(yt=Me.current)==null||yt.moveActiveTabToDownPane();return}if(pe==="triggerPrimaryApprovalAction"){V(0);return}if(pe==="triggerSecondaryApprovalAction"){V(1);return}if(pe==="triggerTertiaryApprovalAction"){V(2);return}if(pe==="setActiveTabShortcut"){(ut=Me.current)==null||ut.setShortcutForActiveTab();return}if(pe==="selectPreviousGroupTab"){(Ht=Me.current)==null||Ht.activatePreviousTabInGroup();return}if(pe==="selectNextGroupTab"){(lr=Me.current)==null||lr.activateNextTabInGroup();return}!r||!Qe(r)||Ve(r)||pe==="toggleCliView"&&m(u==="chat"?"terminal":"chat")}}),Be=jt.useCallback(()=>{ot(),ke(null),Ee([])},[ot,ke,Ee]),Ie=jt.useMemo(()=>Ye==="all"?me:me.filter(pe=>Lx(pe)===Ye),[me,Ye]),qe=jt.useCallback(()=>{const pe=Object.fromEntries(me.map(Le=>[Le.id,""]));$e(pe)},[me,$e]),ct=jt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const pe=Object.fromEntries(me.map(Le=>[Le.id,Le.defaultShortcut]));$e(pe)},[me,$e]);return jt.useEffect(()=>{const pe=Le=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Le.metaKey&&Le.key.toLowerCase()==="w":Le.ctrlKey&&Le.key.toLowerCase()==="w")&&(Le.preventDefault(),r&&ue&&ue(r))};return window.addEventListener("keydown",pe),()=>window.removeEventListener("keydown",pe)},[r,ue]),jt.useEffect(()=>{if(!Ke||Se)return;const pe=Le=>{Le.key==="Escape"&&(Le.preventDefault(),Be())};return window.addEventListener("keydown",pe,!0),()=>window.removeEventListener("keydown",pe,!0)},[Be,Ke,Se]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Sf,{activeConv:r,wsStatus:n,isConnected:a,conversations:be,hiddenConversations:h,onOpenHistory:i,onHideConversation:ue,onShowConversation:w,onShowAllHidden:je,onResetPanelsToMain:P,notifications:D,notificationUnreadCount:ie,onOpenNotification:R,onMarkNotificationRead:we,onMarkNotificationUnread:Ne,onDeleteNotification:Ae,inboxOpen:Ue,onInboxOpenChange:Ce,hiddenOpen:We,onHiddenOpenChange:He,onOpenNewSession:t?void 0:ft,onOpenDashboardGuide:Xe,guideNudgeVisible:Ze,actionShortcuts:he,onOpenRemote:()=>{!r||Qe(r)||Ve(r)||c(r)},onStopCli:l,activeCliViewMode:u,onSetCliViewMode:m}),e?s.jsx(ex,{conversations:d,hiddenConversations:h,ides:f,actionLogs:j,sendDaemonCommand:N,setActionLogs:p,setCliViewModeOverrides:x,isStandalone:y,userName:C,requestedActiveTabKey:I,onRequestedActiveTabConsumed:v,requestedMachineId:M,onRequestedMachineConsumed:S,requestedMobileSection:k,onRequestedMobileSectionConsumed:b,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowHiddenConversation:w,onShowAllHiddenConversations:je,onOpenNewSession:ft,liveSessionInboxState:Q}):t?s.jsx(cx,{containerRef:B,isSplitMode:L,numGroups:_,groupSizes:H,groupedConvs:F,clearedTabs:O,ides:f,actionLogs:j,sendDaemonCommand:N,setActionLogs:p,isStandalone:y,hasRegisteredMachines:fe.length>0,userName:C,focusedGroup:T,focusGroup:A,moveTabToGroup:U,splitTabRelative:$,closeGroup:E,handleResizeStart:z,groupActiveTabIds:Y,setGroupActiveTab:ve,groupTabOrders:re,setGroupTabOrder:ye,toggleHiddenTab:le,onOpenNewSession:ft,allowTabShortcuts:!1,liveSessionInboxState:Q}):s.jsx(Nx,{visibleConversations:be,clearedTabs:O,ides:f,actionLogs:j,sendDaemonCommand:N,setActionLogs:p,isStandalone:y,hasRegisteredMachines:fe.length>0,initialDataLoaded:g,userName:C,toggleHiddenTab:le,actionShortcuts:he,registerActionHandlers:pe=>{Me.current=pe},onActiveTabChange:ne,requestedActiveTabKey:ge,onRequestedActiveTabConsumed:G,onRequestScrollToBottom:q,scrollToBottomRequest:ae,onOpenNewSession:ft,liveSessionInboxState:Q,layoutProfile:oe}),Ge&&s.jsx(Ix,{machines:fe,ides:f,onClose:W,onBrowseDirectory:te,onSaveWorkspace:ee,onLaunchIde:X,onLaunchProvider:J,onListSavedSessions:de}),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:Be,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:pe=>pe.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:Be,"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(pe=>s.jsx("button",{type:"button",className:`btn btn-sm ${Je===pe.id?"btn-primary":"btn-secondary"}`,onClick:()=>pt(pe.id),children:pe.label},pe.id))}),Je==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Z?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Je==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),Je==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(pe=>s.jsx("button",{type:"button",className:`btn btn-sm ${Ye===pe.id?"btn-primary":"btn-secondary"}`,onClick:()=>dt(pe.id),children:pe.label},pe.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:qe,children:"Disable all"}),s.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:ct,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Ie.map(pe=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Se===pe.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:pe.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:pe.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:pe.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:Se===pe.id?Re.length>0?`${Re.join(" ")} ...`:"Listening...":he[pe.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{ke(pe.id),Ee([])},children:Se===pe.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Le={...he};Le[pe.id]="",$e(Le)},children:"Disable"})]})]})},pe.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Z?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})})]})}const $n=[{icon:"🦦",title:"Welcome to ADHDev",desc:"Monitor and control your AI coding agents from anywhere — web, mobile, or CLI.",visual:"🎉"},{icon:"💬",title:"Real-time chat",desc:"See what your AI agent is doing in real-time. Send messages, approve or reject actions — all from your browser or phone.",visual:"📱"},{icon:"🖥️",title:"Remote desktop",desc:"View and control your IDE screen via P2P connection. Click, type, scroll — just like being there.",visual:"🖱️"},{icon:"🚀",title:"Get started",desc:"Install the daemon and link it to your dashboard. It connects automatically.",code:"npm install -g @adhdev/daemon-standalone && adhdev-standalone"}];function Dx({onClose:e}){const[t,r]=o.useState(0),n=$n[t],a=t===$n.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:$n.map((i,c)=>s.jsx("div",{style:{width:c===t?24:8,height:8,borderRadius:4,background:c===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:n.icon})," ",n.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
|
|
54
54
|
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
55
55
|
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
56
|
-
`})]})}function Bx({hasExtensions:e,ideName:t,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:t}),n.map(i=>{const c=r===i.tabKey,l=i.status==="waiting_approval",u=i.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${c?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(i.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"0 0 6px var(--accent-primary)":"none"}}),i.title,l&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},i.tabKey)})]}):null}function Kx({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,c]=o.useState(()=>a||"native"),l=o.useMemo(()=>Mc(t),[t]),u=o.useMemo(()=>e?Ha(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),m=o.useMemo(()=>u.find(p=>p.streamSource==="native"),[u]),d=o.useMemo(()=>u.filter(p=>p.streamSource==="agent-stream"),[u]),h=o.useMemo(()=>e?_t(u,e.id):null,[u,e]);o.useEffect(()=>{a&&c(a)},[a]),o.useEffect(()=>{if(a||!h)return;const p=h.streamSource==="native"?"native":h.tabKey;!p||i===p||i==="native"&&c(p)},[i,h,a]),o.useEffect(()=>{var p;i!=="native"&&(d.some(x=>x.tabKey===i)||c(((p=d[0])==null?void 0:p.tabKey)||"native"))},[i,d]),o.useEffect(()=>{i==="native"&&(m||d[0]&&c(d[0].tabKey))},[i,m,d]);const f=o.useMemo(()=>i==="native"&&m?m:d.find(p=>p.tabKey===i)||h||m||d[0],[i,m,h,d]),j=o.useMemo(()=>d.map(p=>({tabKey:p.tabKey,title:vc(p)||n,status:p.status})),[d,n]),N=o.useCallback(p=>{if(p)return u.find(x=>ra(x,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[u]);return{activeChatTab:i,setActiveChatTab:c,activeConv:f,conversations:u,extensionTabs:j,hasExtensions:j.length>0,resolveConversationByTarget:N}}function Ox({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:i,setActionLogs:c,isStandalone:l,userName:u,onOpenHistory:m,onConversationChange:d,onClose:h}){const[f,j]=o.useState("split"),[N,p]=o.useState(()=>Ut(e)?"native":e.tabKey),x=o.useRef(null),y=o.useMemo(()=>t||r.find(A=>A.id===e.routeId),[e.routeId,t,r]),g=o.useMemo(()=>rt((y==null?void 0:y.type)||""),[y==null?void 0:y.type]),{conversations:C,extensionTabs:I,hasExtensions:v}=Kx({ideData:y,allIdes:r,connectionStates:n,ideName:g||"IDE",preferredTabKey:Ut(e)?void 0:e.tabKey}),T=o.useMemo(()=>y?_t(C,y.id):null,[y,C]);o.useEffect(()=>{const A=x.current,U={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(x.current=U,!(A&&A.routeId===U.routeId&&A.tabKey===U.tabKey&&A.streamSource===U.streamSource)){if(Ut(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(N==="native"){if(C.some(A=>A.streamSource==="native"))return;(T==null?void 0:T.streamSource)==="agent-stream"&&p(T.tabKey);return}if(!C.some(A=>A.tabKey===N)){if((T==null?void 0:T.streamSource)==="agent-stream"){p(T.tabKey);return}p("native")}},[C,N,T]);const S=o.useMemo(()=>N==="native"?C.find(A=>A.streamSource==="native")||e:C.find(A=>A.tabKey===N)||e,[e,C,N]),k=Wc(S),b=o.useMemo(()=>k.status||k.modalMessage||k.modalButtons?{...S,...k.status?{status:k.status}:{},...k.modalMessage!==void 0?{modalMessage:k.modalMessage}:{},...k.modalButtons!==void 0?{modalButtons:k.modalButtons}:{}}:S,[S,k]),B=Rs(b),L=on({sendDaemonCommand:i,activeConv:b,setActionLogs:c,isStandalone:l}),{connScreenshot:_,screenshotUsage:H,handleRemoteAction:F}=il({doId:B,targetSessionId:oc(b),connState:b.connectionState||"new",viewMode:f}),O=o.useMemo(()=>a.filter(A=>A.routeId===b.tabKey),[a,b.tabKey]);o.useEffect(()=>{d==null||d(b)},[b,d]),o.useEffect(()=>{const A=U=>{U.key==="Escape"&&h()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[h]);const M=o.useCallback(A=>{A.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:h,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:M,children:[s.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(St,{size:16})}),s.jsx("span",{className:"truncate",children:Ia(S)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(A=>{const U=f===A;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${U?"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:()=>j(A),title:A==="split"?"Split view":"Remote only",children:A==="split"?s.jsx(Bd,{size:15}):s.jsx(St,{size:15})},A)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>m(S),title:"Chat History",children:[s.jsx(wa,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${f==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[f!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(Bx,{hasExtensions:v,ideName:g||"IDE",activeChatTab:N,extensionTabs:I,onSelectTab:p}),s.jsx(zi,{activeConv:b,onModalButton:L.handleModalButton}),s.jsx(ca,{activeConv:b,ideEntry:y,showMetaChips:!1,handleSendChat:L.handleSendChat,isSendingChat:L.isSendingChat,sendFeedbackMessage:L.sendFeedbackMessage,handleFocusAgent:L.handleFocusAgent,isFocusingAgent:L.isFocusingAgent,actionLogs:O,userName:u})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${f==="split"?"order-1 md:order-2":""}`,children:s.jsx(Fi,{addLog:()=>{},connState:b.connectionState||"new",connScreenshot:_,screenshotUsage:H,transportType:b.transport,onAction:F})})]})]})})}function Wx({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=yf(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 Hx({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(kf,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(Wa,{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(Ox,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),r.open&&r.targetConv&&(Qe(r.targetConv)||Ve(r.targetConv))&&s.jsx(Wx,{activeConv:r.targetConv,canSaveAndStop:Qe(r.targetConv)&&!Ve(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(Cc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&s.jsx($x,{onClose:i.onClose})]})}function Fx({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:i}){return e.length===0?null:s.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(nr,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[r?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(c=>{const l=Mt(c,{fallbackId:c.id}),u=n[c.id],m=c.version||c.daemonVersion||"unknown",d=c.versionUpdateRequired===!0;return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:l}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),d&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:d?"Update now":"Upgrade"})]},c.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:s.jsx(vt,{size:16})})]})}function Ux(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function zx(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 Vx(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>zx(t)).map(t=>t.id)}}function Gx(){var ao,oo,io,co;const{sendCommand:e}=wt(),t=ir(),r=Oc(),n=ga(),a=Is(),[i,c]=ad(),l=i.get("activeTab"),u=((ao=n.state)==null?void 0:ao.openRemoteForTabKey)||null,m=((oo=n.state)==null?void 0:oo.openMachineId)||null,d=((io=n.state)==null?void 0:io.mobileSection)||null,h=xc(),f=h.ides||[],j=h.initialLoaded??!0,{updateRouteChats:N,setToasts:p}=h,[x,y]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),g=h.toasts||[],C=h.wsStatus||"connected",I=h.isConnected??!0,v=h.connectionStates||{},T=h.showReconnected||!1,{layoutProfile:S,groupAssignments:k,updateGroupAssignments:b,focusedGroup:B,updateFocusedGroup:L,focusGroup:_,groupActiveTabIds:H,updateGroupActiveTabIds:F,setGroupActiveTab:O,groupTabOrders:M,updateGroupTabOrders:A,setGroupTabOrder:U,groupSizes:$,updateGroupSizes:E,isMobile:z,hasHydratedStoredLayout:Y,hydrateStoredLayout:ve,focusConversationTab:re}=eh(),[ye,le]=o.useState(()=>Va());o.useEffect(()=>gp(le),[]);const be=o.useMemo(()=>Ux({isMobile:z,mobileViewMode:ye}),[z,ye]),[ge,G]=o.useState([]),[ne,q]=o.useState({}),[ue,ce]=o.useState({});ar("Dashboard",{ideCount:f.length,toastCount:g.length,focusedGroup:B,groupCount:Object.keys(k).length,actionLogCount:ge.length});const je=o.useMemo(()=>f.filter(Fe=>Fe.type==="adhdev-daemon").sort(Ca),[f]),ae=je[0],fe=!!ae;o.useEffect(()=>{const{metadataDaemonIds:Fe,runtimeDaemonIds:It}=Vx(je);for(const _s of Fe)t(_s,{minFreshMs:3e4}).catch(()=>{});for(const _s of It)r(_s,{minFreshMs:3e4}).catch(()=>{})},[t,r,je]);const oe=(ae==null?void 0:ae.terminalBackend)||null,te=ae?Mt(ae,{fallbackId:ae.id}):null,ee=(ae==null?void 0:ae.id)||null,X=o.useMemo(()=>Ip(f,ne),[f,ne]),{hiddenTabs:J,hideTarget:de,toggleTarget:D,showTarget:ie,showAllTabs:Q}=Tp(),{conversations:we,visibleConversations:Ne,visibleTabKeys:Ae,resolveConversationBySessionId:Te,resolveConversationByTarget:Ue}=Kp({ides:X,connectionStates:v,clearedTabs:ue,hiddenTabs:J}),We=o.useMemo(()=>new Map(we.map(Fe=>[Fe.tabKey,Fe])),[we]),Ke=tf(Ne,be),Ge=o.useMemo(()=>_o(we,Ke),[we,Ke]),Ze=o.useMemo(()=>_o(Ne,Ke),[Ne,Ke]);o.useEffect(()=>{Object.keys(ne).length!==0&&q(Fe=>Ap(Fe,f))},[f,ne]);const Je=o.useMemo(()=>Nu(f),[f]),{notifications:Ye,unreadCount:mt}=hh({conversations:Ge,liveSessionInboxState:Je}),{handleMarkDashboardNotificationRead:pt,handleMarkDashboardNotificationUnread:dt,handleDeleteDashboardNotification:Ce}=xh({notifications:Ye,sendDaemonCommand:e}),{containerRef:He,normalizedGroupAssignments:Xe,numGroups:ot,isSplitMode:ft,groupedConvs:W,moveTabToGroup:w,closeGroup:R,handleResizeStart:P,splitTabRelative:V}=ih({groupAssignments:k,updateGroupAssignments:b,updateFocusedGroup:L,updateGroupActiveTabIds:F,updateGroupTabOrders:A,groupSizes:$,updateGroupSizes:E,isMobile:z,visibleConversations:Ze,visibleTabKeys:Ae}),{activeConv:Z,openDesktopConversation:me,requestScrollToBottom:he,scrollToBottomRequest:Se,setDesktopActiveTab:Re}=Ch({isMobile:z,conversations:Ge,visibleConversations:Ze,groupActiveTabIds:H,focusedGroup:B,groupedConvs:W,setSearchParams:c});Ih({activeConv:Z,isMobile:z,liveSessionInboxState:Je,sendDaemonCommand:e});const{requestedDesktopTabKey:ke,requestedMobileTabKey:Ee,consumeRequestedActiveTab:$e}=Op({isMobile:z,urlActiveTab:l,resolveConversationBySessionId:Te,setSearchParams:c}),{remoteDialogConv:Be,remoteDialogIdeEntry:Ie,remoteDialogActiveConv:qe,setRemoteDialogActiveConv:ct,openRemoteDialog:pe,closeRemoteDialog:Le,cliStopDialogOpen:et,cliStopTargetConv:nt,requestCliStop:Oe,cancelCliStop:Tt,confirmCliStop:K}=Rh({isMobile:z,location:n,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:ke,conversations:we,ides:f,resolveConversationByTarget:Ue,activeConv:Z,sendDaemonCommand:e}),{historyModalOpen:se,openHistoryModal:xe,closeHistoryModal:Pe,historyTargetConv:Me,isSavedSessionHistoryTarget:_e,isHistoryCreatingChat:tt,isHistoryRefreshingHistory:yt,handleHistorySwitchSession:ut,handleHistoryNewChat:Ht,handleHistoryRefresh:lr,savedHistorySessions:Nl,savedHistoryFilters:Cl,setSavedHistoryFilters:Ml,isSavedHistoryLoading:Tl,resumingSavedHistorySessionId:Il,handleRefreshSavedHistory:Al,handleResumeSavedHistorySession:Ll}=Ah({activeConv:Z,remoteDialogConv:Be,remoteDialogActiveConv:qe,ides:f,sendDaemonCommand:e,updateRouteChats:N,setToasts:p,setClearedTabs:ce,setSearchParams:c}),Rl=o.useMemo(()=>Ze,[Ze]),dr=z&&ye==="chat",_l=o.useMemo(()=>Ge.filter(Fe=>Ga(J,Fe)),[Ge,J]),so=o.useCallback(Fe=>{const It=new URLSearchParams(i);It.set("activeTab",Fe),c(It,{replace:!0})},[i,c]),{trackPendingLaunch:Pl}=jh({ides:f,conversations:we,onOpenSession:so}),{handleBrowseMachineDirectory:Dl,handleSaveMachineWorkspace:El,handleLaunchMachineIde:$l,handleLaunchMachineProvider:Bl,handleListMachineSavedSessions:Kl,setActiveCliViewMode:Ol}=kh({sendDaemonCommand:e,trackPendingLaunch:Pl,onOpenSession:so,activeConv:Z,ides:f,setCliViewModeOverrides:q});Lp({visibleConversations:Ne,clearedTabs:ue,setClearedTabs:ce,setActionLogs:G}),Wp({ides:f,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Ue});const{isRefreshingHistory:Wl,handleRefreshHistory:Hl}=Jc({sendDaemonCommand:e,activeConv:Z,chats:(co=f.find(Fe=>Fe.id===(Z==null?void 0:Z.routeId)))==null?void 0:co.chats,updateRouteChats:N,setToasts:p,setClearedTabs:ce});sh({urlActiveTab:z&&!dr?l:null,conversations:we,resolveConversationBySessionId:Te,normalizedGroupAssignments:Xe,hasHydratedStoredLayout:z&&!dr?Y:!0,hydrateStoredLayout:z&&!dr?ve:()=>{},focusConversationTab:re,setSearchParams:c,historyModalOpen:se,activeConv:Z,isRefreshingHistory:Wl,ides:f,handleRefreshHistory:Hl});const Fl=o.useMemo(()=>!Z||!Qe(Z)||Ve(Z)?null:Ls(Z),[Z]),{versionMismatchDaemons:Ul,hasRequiredVersionDaemons:ro,appVersion:zl,versionBannerDismissed:Vl,setVersionBannerDismissed:Gl,upgradingDaemons:ql,handleBannerUpgrade:Yl}=ch({ides:f,sendDaemonCommand:e}),no=o.useCallback(Fe=>{ie(Fe),me(Fe)},[me,ie]),Xl=o.useCallback(Fe=>{de(Fe)},[de]);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(Sf,{terminalBackend:oe,isStandalone:fe,machineLabel:te,machineKey:ee}),(!Vl||ro)&&s.jsx(Fx,{daemons:Ul,targetVersion:zl,required:ro,upgradingDaemons:ql,onUpgrade:Yl,onDismiss:()=>Gl(!0)}),s.jsx(Ex,{showMobileChatMode:dr,isMobile:z,activeConv:Z,wsStatus:C,isConnected:I,onOpenHistory:Fe=>{Fe&&ct(Fe),xe()},onOpenRemote:pe,onStopCli:Oe,activeCliViewMode:Fl,onSetActiveCliViewMode:Ol,mobileChatConversations:Rl,ides:f,actionLogs:ge,sendDaemonCommand:e,setActionLogs:G,setCliViewModeOverrides:q,isStandalone:fe,initialDataLoaded:j,userName:h.userName,requestedMobileTabKey:Ee,onRequestedMobileTabConsumed:$e,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:He,isSplitMode:ft,numGroups:ot,groupSizes:$,groupedConvs:W,clearedTabs:ue,focusedGroup:B,focusGroup:_,moveTabToGroup:w,splitTabRelative:V,closeGroup:R,handleResizeStart:P,groupActiveTabIds:H,setGroupActiveTab:O,groupTabOrders:M,setGroupTabOrder:U,toggleHiddenTab:Fe=>D(We.get(Fe)||{tabKey:Fe}),visibleConversations:Ze,hiddenConversations:_l,requestedDesktopTabKey:ke,onRequestedDesktopTabConsumed:$e,onDesktopActiveTabChange:Re,onRequestScrollToBottom:he,onHideConversation:Xl,onShowHiddenConversation:no,onShowAllHiddenConversations:Q,scrollToBottomRequest:Se,machineEntries:je,layoutProfile:S,onBrowseMachineDirectory:Dl,onSaveMachineWorkspace:El,onLaunchMachineIde:$l,onLaunchMachineProvider:Bl,onListMachineSavedSessions:Kl,notifications:Ye,notificationUnreadCount:mt,liveSessionInboxState:Je,onMarkNotificationRead:pt,onMarkNotificationUnread:dt,onDeleteNotification:Ce}),s.jsx("style",{children:`
|
|
56
|
+
`})]})}function Ex({hasExtensions:e,ideName:t,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:t}),n.map(i=>{const c=r===i.tabKey,l=i.status==="waiting_approval",u=i.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${c?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(i.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"0 0 6px var(--accent-primary)":"none"}}),i.title,l&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},i.tabKey)})]}):null}function $x({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,c]=o.useState(()=>a||"native"),l=o.useMemo(()=>Cc(t),[t]),u=o.useMemo(()=>e?Ha(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),m=o.useMemo(()=>u.find(p=>p.streamSource==="native"),[u]),d=o.useMemo(()=>u.filter(p=>p.streamSource==="agent-stream"),[u]),h=o.useMemo(()=>e?_t(u,e.id):null,[u,e]);o.useEffect(()=>{a&&c(a)},[a]),o.useEffect(()=>{if(a||!h)return;const p=h.streamSource==="native"?"native":h.tabKey;!p||i===p||i==="native"&&c(p)},[i,h,a]),o.useEffect(()=>{var p;i!=="native"&&(d.some(x=>x.tabKey===i)||c(((p=d[0])==null?void 0:p.tabKey)||"native"))},[i,d]),o.useEffect(()=>{i==="native"&&(m||d[0]&&c(d[0].tabKey))},[i,m,d]);const f=o.useMemo(()=>i==="native"&&m?m:d.find(p=>p.tabKey===i)||h||m||d[0],[i,m,h,d]),j=o.useMemo(()=>d.map(p=>({tabKey:p.tabKey,title:yc(p)||n,status:p.status})),[d,n]),N=o.useCallback(p=>{if(p)return u.find(x=>ra(x,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[u]);return{activeChatTab:i,setActiveChatTab:c,activeConv:f,conversations:u,extensionTabs:j,hasExtensions:j.length>0,resolveConversationByTarget:N}}function Bx({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:i,setActionLogs:c,isStandalone:l,userName:u,onOpenHistory:m,onConversationChange:d,onClose:h}){const[f,j]=o.useState("split"),[N,p]=o.useState(()=>Ut(e)?"native":e.tabKey),x=o.useRef(null),y=o.useMemo(()=>t||r.find(A=>A.id===e.routeId),[e.routeId,t,r]),g=o.useMemo(()=>rt((y==null?void 0:y.type)||""),[y==null?void 0:y.type]),{conversations:C,extensionTabs:I,hasExtensions:v}=$x({ideData:y,allIdes:r,connectionStates:n,ideName:g||"IDE",preferredTabKey:Ut(e)?void 0:e.tabKey}),M=o.useMemo(()=>y?_t(C,y.id):null,[y,C]);o.useEffect(()=>{const A=x.current,U={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(x.current=U,!(A&&A.routeId===U.routeId&&A.tabKey===U.tabKey&&A.streamSource===U.streamSource)){if(Ut(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(N==="native"){if(C.some(A=>A.streamSource==="native"))return;(M==null?void 0:M.streamSource)==="agent-stream"&&p(M.tabKey);return}if(!C.some(A=>A.tabKey===N)){if((M==null?void 0:M.streamSource)==="agent-stream"){p(M.tabKey);return}p("native")}},[C,N,M]);const S=o.useMemo(()=>N==="native"?C.find(A=>A.streamSource==="native")||e:C.find(A=>A.tabKey===N)||e,[e,C,N]),k=Oc(S),b=o.useMemo(()=>k.status||k.modalMessage||k.modalButtons?{...S,...k.status?{status:k.status}:{},...k.modalMessage!==void 0?{modalMessage:k.modalMessage}:{},...k.modalButtons!==void 0?{modalButtons:k.modalButtons}:{}}:S,[S,k]),B=Rs(b),L=on({sendDaemonCommand:i,activeConv:b,setActionLogs:c,isStandalone:l}),{connScreenshot:_,screenshotUsage:H,handleRemoteAction:F}=ol({doId:B,targetSessionId:ac(b),connState:b.connectionState||"new",viewMode:f}),O=o.useMemo(()=>a.filter(A=>A.routeId===b.tabKey),[a,b.tabKey]);o.useEffect(()=>{d==null||d(b)},[b,d]),o.useEffect(()=>{const A=U=>{U.key==="Escape"&&h()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[h]);const T=o.useCallback(A=>{A.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:h,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:T,children:[s.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(St,{size:16})}),s.jsx("span",{className:"truncate",children:Ia(S)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(A=>{const U=f===A;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${U?"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:()=>j(A),title:A==="split"?"Split view":"Remote only",children:A==="split"?s.jsx($d,{size:15}):s.jsx(St,{size:15})},A)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>m(S),title:"Chat History",children:[s.jsx(wa,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${f==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[f!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(Ex,{hasExtensions:v,ideName:g||"IDE",activeChatTab:N,extensionTabs:I,onSelectTab:p}),s.jsx(Ui,{activeConv:b,onModalButton:L.handleModalButton}),s.jsx(ca,{activeConv:b,ideEntry:y,showMetaChips:!1,handleSendChat:L.handleSendChat,isSendingChat:L.isSendingChat,sendFeedbackMessage:L.sendFeedbackMessage,handleFocusAgent:L.handleFocusAgent,isFocusingAgent:L.isFocusingAgent,actionLogs:O,userName:u})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${f==="split"?"order-1 md:order-2":""}`,children:s.jsx(Hi,{addLog:()=>{},connState:b.connectionState||"new",connScreenshot:_,screenshotUsage:H,transportType:b.transport,onAction:F})})]})]})})}function Kx({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=bf(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[s.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",i,"?"]}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:t?"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.":"This provider does not support graceful stop. Force Stop will end the runtime immediately."})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),s.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Force Stop"}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function Ox({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(wf,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(Wa,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),t.conversation&&s.jsx(Bx,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),r.open&&r.targetConv&&(Qe(r.targetConv)||Ve(r.targetConv))&&s.jsx(Kx,{activeConv:r.targetConv,canSaveAndStop:Qe(r.targetConv)&&!Ve(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(Nc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&s.jsx(Dx,{onClose:i.onClose})]})}function Wx({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:i}){return e.length===0?null:s.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(nr,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[r?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(c=>{const l=Tt(c,{fallbackId:c.id}),u=n[c.id],m=c.version||c.daemonVersion||"unknown",d=c.versionUpdateRequired===!0;return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:l}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),d&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:d?"Update now":"Upgrade"})]},c.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:s.jsx(vt,{size:16})})]})}function Hx(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Fx(e){const t=e.machine;return typeof(t==null?void 0:t.cpus)!="number"||typeof(t==null?void 0:t.totalMem)!="number"||typeof(t==null?void 0:t.arch)!="string"||typeof(t==null?void 0:t.release)!="string"}function Ux(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>Fx(t)).map(t=>t.id)}}function zx(){var ao,oo,io,co;const{sendCommand:e}=wt(),t=ir(),r=Kc(),n=ga(),a=Is(),[i,c]=nd(),l=i.get("activeTab"),u=((ao=n.state)==null?void 0:ao.openRemoteForTabKey)||null,m=((oo=n.state)==null?void 0:oo.openMachineId)||null,d=((io=n.state)==null?void 0:io.mobileSection)||null,h=hc(),f=h.ides||[],j=h.initialLoaded??!0,{updateRouteChats:N,setToasts:p}=h,[x,y]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),g=h.toasts||[],C=h.wsStatus||"connected",I=h.isConnected??!0,v=h.connectionStates||{},M=h.showReconnected||!1,{layoutProfile:S,groupAssignments:k,updateGroupAssignments:b,focusedGroup:B,updateFocusedGroup:L,focusGroup:_,groupActiveTabIds:H,updateGroupActiveTabIds:F,setGroupActiveTab:O,groupTabOrders:T,updateGroupTabOrders:A,setGroupTabOrder:U,groupSizes:$,updateGroupSizes:E,isMobile:z,hasHydratedStoredLayout:Y,hydrateStoredLayout:ve,focusConversationTab:re}=Qp(),[ye,le]=o.useState(()=>Va());o.useEffect(()=>xp(le),[]);const be=o.useMemo(()=>Hx({isMobile:z,mobileViewMode:ye}),[z,ye]),[ge,G]=o.useState([]),[ne,q]=o.useState({}),[ue,ce]=o.useState({});ar("Dashboard",{ideCount:f.length,toastCount:g.length,focusedGroup:B,groupCount:Object.keys(k).length,actionLogCount:ge.length});const je=o.useMemo(()=>f.filter(Fe=>Fe.type==="adhdev-daemon").sort(Ca),[f]),ae=je[0],fe=!!ae;o.useEffect(()=>{const{metadataDaemonIds:Fe,runtimeDaemonIds:It}=Ux(je);for(const _s of Fe)t(_s,{minFreshMs:3e4}).catch(()=>{});for(const _s of It)r(_s,{minFreshMs:3e4}).catch(()=>{})},[t,r,je]);const oe=(ae==null?void 0:ae.terminalBackend)||null,te=ae?Tt(ae,{fallbackId:ae.id}):null,ee=(ae==null?void 0:ae.id)||null,X=o.useMemo(()=>Tp(f,ne),[f,ne]),{hiddenTabs:J,hideTarget:de,toggleTarget:D,showTarget:ie,showAllTabs:Q}=Cp(),{conversations:we,visibleConversations:Ne,visibleTabKeys:Ae,resolveConversationBySessionId:Me,resolveConversationByTarget:Ue}=$p({ides:X,connectionStates:v,clearedTabs:ue,hiddenTabs:J}),We=o.useMemo(()=>new Map(we.map(Fe=>[Fe.tabKey,Fe])),[we]),Ke=Zm(Ne,be),Ge=o.useMemo(()=>Ro(we,Ke),[we,Ke]),Ze=o.useMemo(()=>Ro(Ne,Ke),[Ne,Ke]);o.useEffect(()=>{Object.keys(ne).length!==0&&q(Fe=>Mp(Fe,f))},[f,ne]);const Je=o.useMemo(()=>Su(f),[f]),{notifications:Ye,unreadCount:mt}=fh({conversations:Ge,liveSessionInboxState:Je}),{handleMarkDashboardNotificationRead:pt,handleMarkDashboardNotificationUnread:dt,handleDeleteDashboardNotification:Ce}=ph({notifications:Ye,sendDaemonCommand:e}),{containerRef:He,normalizedGroupAssignments:Xe,numGroups:ot,isSplitMode:ft,groupedConvs:W,moveTabToGroup:w,closeGroup:R,handleResizeStart:P,splitTabRelative:V}=ah({groupAssignments:k,updateGroupAssignments:b,updateFocusedGroup:L,updateGroupActiveTabIds:F,updateGroupTabOrders:A,groupSizes:$,updateGroupSizes:E,isMobile:z,visibleConversations:Ze,visibleTabKeys:Ae}),{activeConv:Z,openDesktopConversation:me,requestScrollToBottom:he,scrollToBottomRequest:Se,setDesktopActiveTab:Re}=Sh({isMobile:z,conversations:Ge,visibleConversations:Ze,groupActiveTabIds:H,focusedGroup:B,groupedConvs:W,setSearchParams:c});Th({activeConv:Z,isMobile:z,liveSessionInboxState:Je,sendDaemonCommand:e});const{requestedDesktopTabKey:ke,requestedMobileTabKey:Ee,consumeRequestedActiveTab:$e}=Bp({isMobile:z,urlActiveTab:l,resolveConversationBySessionId:Me,setSearchParams:c}),{remoteDialogConv:Be,remoteDialogIdeEntry:Ie,remoteDialogActiveConv:qe,setRemoteDialogActiveConv:ct,openRemoteDialog:pe,closeRemoteDialog:Le,cliStopDialogOpen:et,cliStopTargetConv:nt,requestCliStop:Oe,cancelCliStop:Mt,confirmCliStop:K}=Ah({isMobile:z,location:n,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:ke,conversations:we,ides:f,resolveConversationByTarget:Ue,activeConv:Z,sendDaemonCommand:e}),{historyModalOpen:se,openHistoryModal:xe,closeHistoryModal:Pe,historyTargetConv:Te,isSavedSessionHistoryTarget:_e,isHistoryCreatingChat:tt,isHistoryRefreshingHistory:yt,handleHistorySwitchSession:ut,handleHistoryNewChat:Ht,handleHistoryRefresh:lr,savedHistorySessions:Sl,savedHistoryFilters:Nl,setSavedHistoryFilters:Cl,isSavedHistoryLoading:Tl,resumingSavedHistorySessionId:Ml,handleRefreshSavedHistory:Il,handleResumeSavedHistorySession:Al}=Mh({activeConv:Z,remoteDialogConv:Be,remoteDialogActiveConv:qe,ides:f,sendDaemonCommand:e,updateRouteChats:N,setToasts:p,setClearedTabs:ce,setSearchParams:c}),Ll=o.useMemo(()=>Ze,[Ze]),dr=z&&ye==="chat",Rl=o.useMemo(()=>Ge.filter(Fe=>Ga(J,Fe)),[Ge,J]),so=o.useCallback(Fe=>{const It=new URLSearchParams(i);It.set("activeTab",Fe),c(It,{replace:!0})},[i,c]),{trackPendingLaunch:_l}=vh({ides:f,conversations:we,onOpenSession:so}),{handleBrowseMachineDirectory:Pl,handleSaveMachineWorkspace:Dl,handleLaunchMachineIde:El,handleLaunchMachineProvider:$l,handleListMachineSavedSessions:Bl,setActiveCliViewMode:Kl}=wh({sendDaemonCommand:e,trackPendingLaunch:_l,onOpenSession:so,activeConv:Z,ides:f,setCliViewModeOverrides:q});Ip({visibleConversations:Ne,clearedTabs:ue,setClearedTabs:ce,setActionLogs:G}),Kp({ides:f,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Ue});const{isRefreshingHistory:Ol,handleRefreshHistory:Wl}=Xc({sendDaemonCommand:e,activeConv:Z,chats:(co=f.find(Fe=>Fe.id===(Z==null?void 0:Z.routeId)))==null?void 0:co.chats,updateRouteChats:N,setToasts:p,setClearedTabs:ce});eh({urlActiveTab:z&&!dr?l:null,conversations:we,resolveConversationBySessionId:Me,normalizedGroupAssignments:Xe,hasHydratedStoredLayout:z&&!dr?Y:!0,hydrateStoredLayout:z&&!dr?ve:()=>{},focusConversationTab:re,setSearchParams:c,historyModalOpen:se,activeConv:Z,isRefreshingHistory:Ol,ides:f,handleRefreshHistory:Wl});const Hl=o.useMemo(()=>!Z||!Qe(Z)||Ve(Z)?null:Ls(Z),[Z]),{versionMismatchDaemons:Fl,hasRequiredVersionDaemons:ro,appVersion:Ul,versionBannerDismissed:zl,setVersionBannerDismissed:Vl,upgradingDaemons:Gl,handleBannerUpgrade:ql}=oh({ides:f,sendDaemonCommand:e}),no=o.useCallback(Fe=>{ie(Fe),me(Fe)},[me,ie]),Yl=o.useCallback(Fe=>{de(Fe)},[de]);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(jf,{terminalBackend:oe,isStandalone:fe,machineLabel:te,machineKey:ee}),(!zl||ro)&&s.jsx(Wx,{daemons:Fl,targetVersion:Ul,required:ro,upgradingDaemons:Gl,onUpgrade:ql,onDismiss:()=>Vl(!0)}),s.jsx(Px,{showMobileChatMode:dr,isMobile:z,activeConv:Z,wsStatus:C,isConnected:I,onOpenHistory:Fe=>{Fe&&ct(Fe),xe()},onOpenRemote:pe,onStopCli:Oe,activeCliViewMode:Hl,onSetActiveCliViewMode:Kl,mobileChatConversations:Ll,ides:f,actionLogs:ge,sendDaemonCommand:e,setActionLogs:G,setCliViewModeOverrides:q,isStandalone:fe,initialDataLoaded:j,userName:h.userName,requestedMobileTabKey:Ee,onRequestedMobileTabConsumed:$e,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:He,isSplitMode:ft,numGroups:ot,groupSizes:$,groupedConvs:W,clearedTabs:ue,focusedGroup:B,focusGroup:_,moveTabToGroup:w,splitTabRelative:V,closeGroup:R,handleResizeStart:P,groupActiveTabIds:H,setGroupActiveTab:O,groupTabOrders:T,setGroupTabOrder:U,toggleHiddenTab:Fe=>D(We.get(Fe)||{tabKey:Fe}),visibleConversations:Ze,hiddenConversations:Rl,requestedDesktopTabKey:ke,onRequestedDesktopTabConsumed:$e,onDesktopActiveTabChange:Re,onRequestScrollToBottom:he,onHideConversation:Yl,onShowHiddenConversation:no,onShowAllHiddenConversations:Q,scrollToBottomRequest:Se,machineEntries:je,layoutProfile:S,onBrowseMachineDirectory:Pl,onSaveMachineWorkspace:Dl,onLaunchMachineIde:El,onLaunchMachineProvider:$l,onListMachineSavedSessions:Bl,notifications:Ye,notificationUnreadCount:mt,liveSessionInboxState:Je,onMarkNotificationRead:pt,onMarkNotificationUnread:dt,onDeleteNotification:Ce}),s.jsx("style",{children:`
|
|
57
57
|
body { overflow: hidden; overscroll-behavior: none; }
|
|
58
|
-
`}),s.jsx(
|
|
58
|
+
`}),s.jsx(Ox,{historyModal:{open:se,targetConv:Te,ides:f,isCreatingChat:tt,isRefreshingHistory:_e?!1:yt,savedSessions:Sl,savedHistoryFilters:Nl,onSavedHistoryFiltersChange:Cl,isSavedSessionsLoading:Tl,isResumingSavedSessionId:Ml,onClose:Pe,onNewChat:Ht,onSwitchSession:ut,onRefreshHistory:_e?Il:lr,onResumeSavedSession:Al},remoteDialog:{conversation:Be,ideEntry:Ie,ides:f,connectionStates:v,actionLogs:ge,sendDaemonCommand:e,setActionLogs:G,isStandalone:fe,userName:h.userName,onOpenHistory:Fe=>{Fe&&ct(Fe),xe()},onConversationChange:ct,onClose:Le},cliStopDialog:{open:et,targetConv:nt,onCancel:Mt,onStopNow:async()=>{await K("hard")},onSaveAndStop:async()=>{await K("save")}},connectionBanner:{wsStatus:C,showReconnected:M,loginUrl:h.connectionLoginUrl,onReconnect:h.retryServerConnection},toastOverlay:{toasts:g,onDismiss:Fe=>p(It=>It.filter(_s=>_s.id!==Fe)),onClick:Fe=>{if(Fe.targetKey){const It=Ue(Fe.targetKey);It&&(re(It.tabKey,Xe),no(It),he(It.tabKey,"toast-open"))}}},onboarding:{open:x,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}y(!1)}}})]})}function Vx({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,u]=o.useState(null),[m,d]=o.useState(null),[h,f]=o.useState(!1),[j,N]=o.useState(null),[p,x]=o.useState(!1),[y,g]=o.useState(""),C=o.useRef(null),I=o.useCallback($=>{C.current=$},[]),v=o.useCallback(($,E,z=!1)=>{c(Y=>[...Y.slice(-100),{timestamp:Date.now(),level:$,message:E}]),setTimeout(()=>{var Y;return(Y=a.current)==null?void 0:Y.scrollIntoView({behavior:"smooth"})},100),z&&it.showToast(E,$==="error"||$==="warn"?"warning":"success")},[a]),M=o.useCallback($=>{const E=$ instanceof Error?$.message:String($||"");return E.includes("P2P command timeout")||E.includes("P2P not connected")||E.includes("P2P not available")},[]),S=o.useCallback(async($,E)=>{var z;if(!e||l)return!1;u($),v("info",`Launching ${rt($)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const Y={ideType:$,enableCdp:!0};(z=E==null?void 0:E.workspace)!=null&&z.trim()?Y.workspace=E.workspace.trim():E!=null&&E.useDefaultWorkspace&&(Y.useDefaultWorkspace=!0);const ve=await r(e,"launch_ide",Y);return v(ve!=null&&ve.success?"info":"error",ve!=null&&ve.success?`${rt($)} launched`:`Failed: ${ve==null?void 0:ve.error}`,!0),!!(ve!=null&&ve.success)}catch(Y){return v("error",`Launch error: ${Y.message}`,!0),!1}finally{u(null)}},[e,l,v,r]),k=o.useCallback(async $=>{if(!e)return{success:!1};const{cliType:E,dir:z,workspaceId:Y,useDefaultWorkspace:ve,useHome:re,argsStr:ye,model:le,resumeSessionId:be}=$;if(!E)return v("warn","Select a CLI or ACP provider first",!0),{success:!1};const ge=ye?ye.split(/\s+/).filter(Boolean):void 0,G=(z==null?void 0:z.trim())||(Y?"(saved id)":ve?"(default workspace)":re?"(home)":"");v("info",`Launching ${E}${G?` in ${G}`:""}${le?` (model: ${le})`:""}...`),d(E);try{const ne={cliType:E,cliArgs:ge,initialModel:le||void 0};z!=null&&z.trim()?ne.dir=z.trim():Y?ne.workspaceId=Y:ve?ne.useDefaultWorkspace=!0:re&&(ne.useHome=!0),be&&(ne.resumeSessionId=be);const q=await r(e,"launch_cli",ne),ue=(q==null?void 0:q.result)||q;return q!=null&&q.success?(v("info",`${E} launched`,!0),(ue==null?void 0:ue.launchSource)==="home"?v("info","📂 Running in home directory (explicit choice)"):(ue==null?void 0:ue.launchSource)==="defaultWorkspace"&&v("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ue==null?void 0:ue.sessionId}):(v("error",`Failed: ${(q==null?void 0:q.error)||(ue==null?void 0:ue.error)}`,!0),(q==null?void 0:q.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&N({cliType:E,argsStr:ye,model:le}),{success:!1,sessionId:ue==null?void 0:ue.sessionId})}catch(ne){return M(ne)?(v("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(v("error",`Launch error: ${ne.message}`,!0),{success:!1})}finally{d(null)}},[e,v,M,r]),b=o.useCallback(async($,E,z,Y)=>e?$?E.trim()?k({cliType:$,dir:E,argsStr:z,model:Y}):(N({cliType:$,argsStr:z,model:Y}),{success:!1}):(v("warn","Select a provider",!0),{success:!1}):{success:!1},[e,v,k]),B=o.useCallback(async($,E,z)=>{if(e&&window.confirm(`Stop ${$}?
|
|
59
59
|
This will terminate the process.`))try{const Y=await r(e,"stop_cli",{cliType:$,dir:E,targetSessionId:z});Y!=null&&Y.success?v("info",`${$} stopped`,!0):v("error",`Stop failed: ${(Y==null?void 0:Y.error)||"Unknown error"}`,!0)}catch(Y){v("error",`Stop failed: ${Y.message}`,!0)}},[e,v,r]),L=o.useCallback(async $=>{try{await r($.daemonId,"restart_ide",{ideType:$.type}),v("info",`${rt($.type)} restart initiated`,!0)}catch(E){v("error",`Restart failed: ${E.message}`,!0)}},[v,r]),_=o.useCallback(async $=>{if(window.confirm(`Stop ${rt($.type)}?
|
|
60
|
-
This will disconnect CDP and optionally kill the process.`))try{const E=await r($.daemonId,"stop_ide",{ideType:$.type,killProcess:!0});E!=null&&E.success?v("info",`${rt($.type)} stopped`,!0):v("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){v("error",`Stop failed: ${E.message}`,!0)}},[v,r]),H=o.useCallback(async()=>{if(e)try{const $=await r(e,"detect_ides",{});v("info",`Found ${(($==null?void 0:$.result)||[]).length} IDE(s)`,!0)}catch($){v("error",`Detection failed: ${$.message}`,!0)}},[e,v,r]),F=o.useCallback(async $=>{if(!e||!$.trim())return!1;f(!0);try{const E=await r(e,"workspace_add",{path:$.trim()});return E!=null&&E.success?(v("info",`Workspace added: ${$.trim()}`),!0):(v("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return v("error",E.message),!1}finally{f(!1)}},[e,v,r]),O=o.useCallback(async $=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){f(!0);try{const E=await r(e,"workspace_remove",{id:$});E!=null&&E.success?v("info","Workspace removed",!0):v("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){v("error",E.message,!0)}finally{f(!1)}}},[e,v,r]),
|
|
61
|
-
✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[e,t.type,r,a]),
|
|
62
|
-
⚠️ Auto-fix cancelled.`]),i("done"),y.current&&clearInterval(y.current)}catch{}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:k=>k.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:Zx.map(k=>s.jsxs("button",{onClick:()=>l(k.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===k.value?k.color+"66":"var(--border-subtle)",background:c===k.value?k.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===k.value?k.color:"var(--text-primary)"},children:k.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:k.desc})]},k.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:C,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:I,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(k=>s.jsxs("button",{onClick:()=>g(k),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(k)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(k)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(k)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(k)?"☑ ":"☐ ",k]},k))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",s.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:d,onChange:k=>h(k.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[f.map((k,b)=>s.jsx("div",{className:k.startsWith("✅")?"text-green-400":"",style:k.startsWith("❌")||k.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:k},b)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:x})]}),N&&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:N})]})]}),s.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[s.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&u.length>0&&`${u.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),s.jsxs("div",{className:"flex gap-2",children:[a==="config"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:T,disabled:u.length===0,className:"machine-btn",style:{background:u.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:u.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:u.length>0?"#a78bfa":void 0,opacity:u.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&s.jsx("button",{onClick:S,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"),j([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function tb({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var v;const i=t.filter(T=>T.category==="ide"),[c,l]=o.useState(((v=i[0])==null?void 0:v.type)||""),[u,m]=o.useState(""),[d,h]=o.useState(""),[f,j]=o.useState(!1),[N,p]=o.useState(""),[x,y]=o.useState(!1),g=T=>{const S=T.toLowerCase().replace(/[^a-z0-9-]/g,"");m(S),(!d||d===C(u))&&h(C(S))},C=T=>T.split("-").map(S=>S.charAt(0).toUpperCase()+S.slice(1)).join(" "),I=async()=>{if(!(!u||!d||!c)){j(!0),p("");try{const T=await r(e,"provider_clone",{type:u,name:d,category:"ide",location:"user",cloneFrom:c});T!=null&&T.success||T!=null&&T.created?(y(!0),a==null||a(u)):p((T==null?void 0:T.error)||"Failed to create provider")}catch(T){p((T==null?void 0:T.message)||"Connection failed")}j(!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:T=>T.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:x?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:u})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",u,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",u]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(T=>s.jsxs("button",{onClick:()=>l(T.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===T.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===T.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:T.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===T.type?"#a78bfa":"var(--text-secondary)"},children:T.displayName})]},T.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:u,onChange:T=>g(T.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",u||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:d,onChange:T=>h(T.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"})]}),N&&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:N})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:x?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:I,disabled:!u||!d||f,className:"machine-btn",style:{background:u&&d?"rgba(34,197,94,0.12)":void 0,borderColor:u&&d?"rgba(34,197,94,0.3)":void 0,color:u&&d?"#86efac":void 0,opacity:!u||!d||f?.4:1},children:f?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function li(e){return e==="cli"||e==="acp"}function sb(e){switch(e){case"detected":return"Detected";case"not_detected":return"Not detected";case"enabled_unchecked":return"Enabled, not checked";case"disabled":return"Disabled";default:return"Disabled"}}function rb(e){switch(e){case"detected":return"bg-green-500/[0.10] border-green-500/25 text-green-400";case"not_detected":return"bg-red-500/[0.10] border-red-500/25 text-red-400";case"enabled_unchecked":return"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400";case"disabled":default:return"bg-white/[0.04] border-white/[0.10] text-text-muted"}}function di(e){if(!e)return"No result yet";const t=e.stage||"check",r=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${t}: ${r} — ${n}`:`${t}: ${r}`}function nb({machineId:e,providers:t,sendDaemonCommand:r}){var F;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[m,d]=o.useState("all"),[h,f]=o.useState(null),[j,N]=o.useState(!1),[p,x]=o.useState(null),[y,g]=o.useState("normal"),[C,I]=o.useState(""),[v,T]=o.useState(!1),S=o.useCallback(async()=>{if(e)try{const O=await r(e,"get_provider_source_config",{}),M=ii(O);M&&(x(M),g(M.sourceMode),I(M.explicitProviderDir||""))}catch{}},[e,r]),k=o.useCallback(async()=>{if(e){c(!0);try{const O=await r(e,"get_provider_settings",{}),M=Xx(O);if(M){const A=Jx(M,t,{filterSchema:U=>U.filter($=>$.key!=="enabled")});A.sort((U,$)=>U.category.localeCompare($.category)||U.displayName.localeCompare($.displayName)),a(A)}}catch{}c(!1)}},[e,t,r]);o.useEffect(()=>{n.length===0&&k(),p||S()},[]);const b=async(O,M,A)=>{u(`${O}.${M}`),a(U=>U.map($=>$.type===O?{...$,values:{...$.values,[M]:A}}:$));try{const U=await r(e,"set_provider_setting",{providerType:O,key:M,value:A});U!=null&&U.success||k()}catch{k()}u(null)},B=async(O,M)=>{await b(O,"enabled",M),await k()},L=async O=>{u(`${O}.detect`);try{await r(e,"detect_provider",{providerType:O})}finally{await k(),u(null)}},_=async O=>{await b(O,"executablePath",""),await b(O,"executableArgs",""),await k()},H=async()=>{T(!0);try{const O=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:Qx(C)}),M=ii(O);M?(x(M),g(M.sourceMode),I(M.explicitProviderDir||"")):await S(),await k()}catch{await S()}T(!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(O=>s.jsx("button",{onClick:()=>d(O),className:`machine-btn text-[10px] px-2 py-0.5 ${m===O?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:O.toUpperCase()},O))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>N(!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:k,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:S,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),s.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),s.jsxs("select",{value:y,onChange:O=>g(O.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:C,onChange:O=>I(O.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void H(),disabled:v,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:v?"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:"})," ",((F=p==null?void 0:p.providerRoots)==null?void 0:F.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(O=>O.category===m).length>1&&(()=>{const O=n.filter($=>$.category===m),M=new Map;for(const $ of O)for(const E of $.schema){if(E.type!=="boolean")continue;const z=M.get(E.key),Y=!!($.values[E.key]??E.default);z?(z.onCount+=Y?1:0,z.total+=1):M.set(E.key,{label:E.label||E.key,onCount:Y?1:0,total:1})}const A=[...M.entries()].filter(([,$])=>$.total===O.length);if(A.length===0)return null;const U=async($,E)=>{for(const z of O)await b(z.type,$,E)};return s.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[s.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",O.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:A.map(([$,E])=>{const z=E.onCount===E.total,Y=E.onCount===0;return s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:E.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",E.onCount,"/",E.total,")"]}),s.jsx("button",{onClick:()=>void U($,!0),disabled:z,className:`machine-btn text-[9px] px-1.5 py-px ${z?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void U($,!1),disabled:Y,className:`machine-btn text-[9px] px-1.5 py-px ${Y?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},$)})})]})})(),i&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):s.jsx("div",{className:"flex flex-col gap-2",children:n.filter(O=>m==="all"||O.category===m).map(O=>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:O.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:O.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:O.category==="acp"?"rgba(139,92,246,0.08)":O.category==="cli"?"rgba(59,130,246,0.08)":O.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:O.category==="acp"?"#a78bfa":O.category==="cli"?"#60a5fa":O.category==="ide"?"#86efac":"var(--status-warning)"},children:O.category}),li(O.category)&&(()=>{const M=t.find($=>$.type===O.type),A=(M==null?void 0:M.enabled)===!0||O.values.enabled===!0,U=(M==null?void 0:M.machineStatus)||(A?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${rb(U)}`,children:sb(U)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void B(O.type,!A),disabled:l===`${O.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${A?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:A?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void L(O.type),disabled:!A||l===`${O.type}.detect`,title:A?"Run detection for the configured executable":"Enable this provider before detection",className:`machine-btn text-[9px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${A?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void _(O.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),O.category==="ide"&&s.jsx("button",{onClick:()=>f(t.find(M=>M.type===O.type)||{type:O.type,name:O.displayName,displayName:O.displayName,icon:O.icon,category:O.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"})]}),li(O.category)&&(()=>{const M=t.find(A=>A.type===O.type);return s.jsxs("div",{className:"mb-2.5 grid gap-1 rounded-lg border border-white/[0.06] bg-bg-primary/40 px-3 py-2 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Detection:"})," ",di(M==null?void 0:M.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",di(M==null?void 0:M.lastVerification)]}),s.jsx("div",{className:"text-[9px] text-text-muted",children:"Supported catalog entry only becomes launchable after Enable + Detect succeeds. Custom executable path/args below are machine-local overrides."})]})})(),s.jsx("div",{className:"flex flex-col gap-2",children:O.schema.map(M=>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:[M.label||M.key,l===`${O.type}.${M.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),M.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:M.description})]}),s.jsx("div",{className:"shrink-0",children:M.type==="boolean"?s.jsx("button",{onClick:()=>b(O.type,M.key,!(O.values[M.key]??M.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:O.values[M.key]??M.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:O.values[M.key]??M.default?21:3}})}):M.type==="number"?s.jsx("input",{type:"number",value:Number(O.values[M.key]??M.default??0)||0,min:M.min,max:M.max,onChange:A=>{const U=parseInt(A.target.value)||0;M.min!==void 0&&U<M.min||M.max!==void 0&&U>M.max||b(O.type,M.key,U)},className:"machine-input w-20 text-center text-[11px]"}):M.type==="select"&&M.options?s.jsx("select",{value:String(O.values[M.key]??M.default??""),onChange:A=>b(O.type,M.key,A.target.value),className:"machine-input text-[11px]",children:M.options.map(A=>s.jsx("option",{value:A,children:A},A))}):s.jsx("input",{type:"text",value:String(O.values[M.key]??M.default??""),onBlur:A=>b(O.type,M.key,A.target.value),className:"machine-input w-[120px] text-[11px]"})})]},M.key))})]},O.type))}),h&&s.jsx(eb,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>f(null)}),j&&s.jsx(tb,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>N(!1),onCreated:()=>{N(!1),k()}})]})}const ab=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function ob({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function ib(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function cb(e){return e.trim().toLowerCase()}function dn(e,t){const r=cb(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Za(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Ts(e,t=220){const r=Za(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function lb(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 db(e,t){return e.filter(r=>dn([r.level,r.message],t))}function ui(e){return`${e.timestamp}:${e.level}:${e.message}`}function ub(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const c of e.entries)n.set(ui(c),c);for(const c of t.entries)n.set(ui(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 mb(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 fb(e,t){return e.split(`
|
|
63
|
-
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>dn([r],t))}function
|
|
60
|
+
This will disconnect CDP and optionally kill the process.`))try{const E=await r($.daemonId,"stop_ide",{ideType:$.type,killProcess:!0});E!=null&&E.success?v("info",`${rt($.type)} stopped`,!0):v("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){v("error",`Stop failed: ${E.message}`,!0)}},[v,r]),H=o.useCallback(async()=>{if(e)try{const $=await r(e,"detect_ides",{});v("info",`Found ${(($==null?void 0:$.result)||[]).length} IDE(s)`,!0)}catch($){v("error",`Detection failed: ${$.message}`,!0)}},[e,v,r]),F=o.useCallback(async $=>{if(!e||!$.trim())return!1;f(!0);try{const E=await r(e,"workspace_add",{path:$.trim()});return E!=null&&E.success?(v("info",`Workspace added: ${$.trim()}`),!0):(v("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return v("error",E.message),!1}finally{f(!1)}},[e,v,r]),O=o.useCallback(async $=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){f(!0);try{const E=await r(e,"workspace_remove",{id:$});E!=null&&E.success?v("info","Workspace removed",!0):v("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){v("error",E.message,!0)}finally{f(!1)}}},[e,v,r]),T=o.useCallback(async $=>{var E;if(e){f(!0);try{const z=await r(e,"workspace_set_default",$===null?{clear:!0}:{id:$});if(z!=null&&z.success){v("info",$?"Default workspace updated":"Default workspace cleared",!0);const Y=typeof z.defaultWorkspacePath=="string"?z.defaultWorkspacePath:"";Y&&((E=C.current)==null||E.call(C,Y))}else v("error",(z==null?void 0:z.error)||"workspace_set_default failed",!0)}catch(z){v("error",z.message,!0)}finally{f(!1)}}},[e,v,r]),A=o.useCallback(async $=>{var z;if(!e||!$.trim())return;const E=$.trim();f(!0);try{const Y=await r(e,"workspace_set_default",{path:E});Y!=null&&Y.success?(v("info","Default workspace set from history"),(z=C.current)==null||z.call(C,E)):v("error",(Y==null?void 0:Y.error)||"Could not set default (path missing on disk?)")}catch(Y){v("error",Y.message)}finally{f(!1)}},[e,v,r]),U=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:y})}catch($){v("warn",`Live nickname updated, but account sync failed: ${$.message}`)}v("info",`Nickname set to "${y||"(cleared)"}"`),x(!1)}catch($){v("error",`Failed: ${$.message}`)}},[e,y,t,v,n,r]);return{logs:i,launchingIde:l,launchingAgentType:m,workspaceBusy:h,launchPick:j,setLaunchPick:N,editingNickname:p,setEditingNickname:x,nicknameInput:y,setNicknameInput:g,addLog:v,handleLaunchIde:S,runLaunchCliCore:k,handleLaunchCli:b,handleStopCli:B,handleRestartIde:L,handleStopIde:_,handleDetectIdes:H,handleWorkspaceAdd:F,handleWorkspaceRemove:O,handleWorkspaceSetDefault:T,handleWorkspaceResumePath:A,handleSaveNickname:U,setOnDefaultWorkspaceChanged:I}}function Gx({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var L;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:m,handleWorkspaceSetDefault:d}=i,[h,f]=o.useState(!1),[j,N]=o.useState(""),[p,x]=o.useState([]),[y,g]=o.useState(!1),[C,I]=o.useState(""),v=o.useCallback(async _=>{g(!0),I("");try{const H=await an(c,e,_);N(H.path),x(H.directories)}catch(H){I(H instanceof Error?H.message:"Could not load folder")}finally{g(!1)}},[e,c]),M=o.useCallback(()=>{f(!0);const _=[...r.map(F=>F.workspace),...n.map(F=>F.workspace),...a.map(F=>F.workspace)],H=nn(t.platform,rn(_,t.defaultWorkspacePath,(t.workspaces||[]).map(F=>F.path)));v(H)},[a,n,r,v,t.defaultWorkspacePath,t.platform,t.workspaces]),S=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,k=t.availableMem??t.freeMem??t.totalMem,b=S&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-k)/t.totalMem*100))):0,B=((L=t.loadavg)==null?void 0:L[0])||0;return s.jsxs("div",{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[s.jsx(fr,{icon:s.jsx(Di,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?Mu(t.uptime):"Waiting…"}),s.jsx(fr,{icon:s.jsx(St,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(fr,{icon:s.jsx(ja,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(fr,{icon:s.jsx(Kd,{size:16}),label:"ACPs",value:`${a.length}`})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),s.jsxs("div",{className:"flex gap-6",children:[s.jsx(go,{value:S?Math.min(Math.round(B/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:S?`${B.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(go,{value:b,max:100,label:"Memory",color:"#3b82f6",detail:S?`${xn(t.totalMem-k)} / ${xn(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${xn(t.totalMem)} total`})]})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[s.jsx(Ss,{size:14})," Workspaces"]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),s.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:l,value:t.defaultWorkspaceId||"",onChange:_=>void d(_.target.value===""?null:_.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(_=>s.jsx("option",{value:_.id,children:_.label||_.path},_.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:M,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(_=>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:[_.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:en(_.path,_.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:_.path,children:_.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void m(_.id),children:"Remove"})]},_.id))})]}),h&&s.jsx(cn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:j,directories:p,busy:y,error:C,confirmLabel:"Add workspace",onClose:()=>f(!1),onNavigate:_=>{v(_)},onConfirm:_=>{(async()=>{if(!_)return;await u(_)&&f(!1)})()}})]})}function qx(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function Yx(e,t,r){const n=[];for(const[a,i]of Object.entries(e.settings)){const c=r!=null&&r.filterSchema?r.filterSchema(i):i;if(c.length===0)continue;const l=t.find(u=>u.type===a);n.push({type:a,displayName:(l==null?void 0:l.displayName)||a,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[a]||{}})}return n}function Bn(e){if(!e||typeof e!="object")return!1;const t=e;return(t.sourceMode==="normal"||t.sourceMode==="no-upstream")&&typeof t.disableUpstream=="boolean"&&(t.explicitProviderDir===null||typeof t.explicitProviderDir=="string")&&typeof t.userDir=="string"&&typeof t.upstreamDir=="string"&&Array.isArray(t.providerRoots)}function oi(e){if(!e||typeof e!="object")return null;if(Bn(e))return e;const t=e,r=t.result;return Bn(r)?r:Bn(t.sourceConfig)?t.sourceConfig:null}function Xx(e){const t=e.trim();return t||null}const ii=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Jx=[{value:"codex-cli",label:"Codex CLI",desc:"OpenAI o3/gpt-5.4",color:"#22c55e"},{value:"claude-cli",label:"Claude Code",desc:"Anthropic Claude",color:"#a855f7"},{value:"gemini-cli",label:"Gemini CLI",desc:"Google Gemini",color:"#3b82f6"}];function Qx({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[u,m]=o.useState([]),[d,h]=o.useState(""),[f,j]=o.useState([]),[N,p]=o.useState(""),x=o.useRef(null),y=o.useRef(null),g=k=>{m(b=>b.includes(k)?b.filter(B=>B!==k):[...b,k])},C=()=>m([...ii]),I=()=>m([]);o.useEffect(()=>{var k;(k=x.current)==null||k.scrollIntoView({behavior:"smooth"})},[f]),o.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const v=o.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const k=await r(e,"provider_auto_fix_status",{providerType:t.type});(k==null?void 0:k.running)===!1&&a==="running"&&(i("done"),j(b=>[...b,`
|
|
61
|
+
✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[e,t.type,r,a]),M=async()=>{if(u.length!==0){i("running"),j(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,d?`💬 Comment: ${d}`:"",""]),p("");try{const k=await r(e,"provider_auto_fix",{providerType:t.type,functions:u,agent:c,...d?{comment:d}:{}});k!=null&&k.success&&(k!=null&&k.started||k!=null&&k.running)?(j(b=>[...b,"✅ Agent started. Monitoring progress..."]),v()):(i("error"),p((k==null?void 0:k.error)||"Failed to start auto-fix"))}catch(k){i("error"),p((k==null?void 0:k.message)||"Connection failed")}}},S=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),j(k=>[...k,`
|
|
62
|
+
⚠️ Auto-fix cancelled.`]),i("done"),y.current&&clearInterval(y.current)}catch{}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:k=>k.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:t.icon||"🔧"}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",t.displayName]}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),s.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),s.jsx("div",{className:"flex gap-2",children:Jx.map(k=>s.jsxs("button",{onClick:()=>l(k.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===k.value?k.color+"66":"var(--border-subtle)",background:c===k.value?k.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===k.value?k.color:"var(--text-primary)"},children:k.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:k.desc})]},k.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:C,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:I,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:ii.map(k=>s.jsxs("button",{onClick:()=>g(k),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(k)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(k)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(k)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(k)?"☑ ":"☐ ",k]},k))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",s.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:d,onChange:k=>h(k.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[f.map((k,b)=>s.jsx("div",{className:k.startsWith("✅")?"text-green-400":"",style:k.startsWith("❌")||k.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:k},b)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:x})]}),N&&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:N})]})]}),s.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[s.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&u.length>0&&`${u.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),s.jsxs("div",{className:"flex gap-2",children:[a==="config"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:M,disabled:u.length===0,className:"machine-btn",style:{background:u.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:u.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:u.length>0?"#a78bfa":void 0,opacity:u.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&s.jsx("button",{onClick:S,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"),j([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Zx({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var v;const i=t.filter(M=>M.category==="ide"),[c,l]=o.useState(((v=i[0])==null?void 0:v.type)||""),[u,m]=o.useState(""),[d,h]=o.useState(""),[f,j]=o.useState(!1),[N,p]=o.useState(""),[x,y]=o.useState(!1),g=M=>{const S=M.toLowerCase().replace(/[^a-z0-9-]/g,"");m(S),(!d||d===C(u))&&h(C(S))},C=M=>M.split("-").map(S=>S.charAt(0).toUpperCase()+S.slice(1)).join(" "),I=async()=>{if(!(!u||!d||!c)){j(!0),p("");try{const M=await r(e,"provider_clone",{type:u,name:d,category:"ide",location:"user",cloneFrom:c});M!=null&&M.success||M!=null&&M.created?(y(!0),a==null||a(u)):p((M==null?void 0:M.error)||"Failed to create provider")}catch(M){p((M==null?void 0:M.message)||"Connection failed")}j(!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:M=>M.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:x?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:u})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",u,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",u]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(M=>s.jsxs("button",{onClick:()=>l(M.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===M.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===M.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:M.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===M.type?"#a78bfa":"var(--text-secondary)"},children:M.displayName})]},M.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:u,onChange:M=>g(M.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",u||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:d,onChange:M=>h(M.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"})]}),N&&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:N})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:x?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:I,disabled:!u||!d||f,className:"machine-btn",style:{background:u&&d?"rgba(34,197,94,0.12)":void 0,borderColor:u&&d?"rgba(34,197,94,0.3)":void 0,color:u&&d?"#86efac":void 0,opacity:!u||!d||f?.4:1},children:f?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function ci(e){return e==="cli"||e==="acp"}function eb(e){switch(e){case"detected":return"Detected";case"not_detected":return"Not detected";case"enabled_unchecked":return"Enabled, not checked";case"disabled":return"Disabled";default:return"Disabled"}}function tb(e){switch(e){case"detected":return"bg-green-500/[0.10] border-green-500/25 text-green-400";case"not_detected":return"bg-red-500/[0.10] border-red-500/25 text-red-400";case"enabled_unchecked":return"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400";case"disabled":default:return"bg-white/[0.04] border-white/[0.10] text-text-muted"}}function li(e){if(!e)return"No result yet";const t=e.stage||"check",r=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${t}: ${r} — ${n}`:`${t}: ${r}`}function sb({machineId:e,providers:t,sendDaemonCommand:r}){var F;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[m,d]=o.useState("all"),[h,f]=o.useState(null),[j,N]=o.useState(!1),[p,x]=o.useState(null),[y,g]=o.useState("normal"),[C,I]=o.useState(""),[v,M]=o.useState(!1),S=o.useCallback(async()=>{if(e)try{const O=await r(e,"get_provider_source_config",{}),T=oi(O);T&&(x(T),g(T.sourceMode),I(T.explicitProviderDir||""))}catch{}},[e,r]),k=o.useCallback(async()=>{if(e){c(!0);try{const O=await r(e,"get_provider_settings",{}),T=qx(O);if(T){const A=Yx(T,t,{filterSchema:U=>U.filter($=>$.key!=="enabled")});A.sort((U,$)=>U.category.localeCompare($.category)||U.displayName.localeCompare($.displayName)),a(A)}}catch{}c(!1)}},[e,t,r]);o.useEffect(()=>{n.length===0&&k(),p||S()},[]);const b=async(O,T,A)=>{u(`${O}.${T}`),a(U=>U.map($=>$.type===O?{...$,values:{...$.values,[T]:A}}:$));try{const U=await r(e,"set_provider_setting",{providerType:O,key:T,value:A});U!=null&&U.success||k()}catch{k()}u(null)},B=async(O,T)=>{await b(O,"enabled",T),await k()},L=async O=>{u(`${O}.detect`);try{await r(e,"detect_provider",{providerType:O})}finally{await k(),u(null)}},_=async O=>{await b(O,"executablePath",""),await b(O,"executableArgs",""),await k()},H=async()=>{M(!0);try{const O=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:Xx(C)}),T=oi(O);T?(x(T),g(T.sourceMode),I(T.explicitProviderDir||"")):await S(),await k()}catch{await S()}M(!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(O=>s.jsx("button",{onClick:()=>d(O),className:`machine-btn text-[10px] px-2 py-0.5 ${m===O?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:O.toUpperCase()},O))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>N(!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:k,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:S,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),s.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),s.jsxs("select",{value:y,onChange:O=>g(O.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:C,onChange:O=>I(O.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void H(),disabled:v,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:v?"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:"})," ",((F=p==null?void 0:p.providerRoots)==null?void 0:F.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(O=>O.category===m).length>1&&(()=>{const O=n.filter($=>$.category===m),T=new Map;for(const $ of O)for(const E of $.schema){if(E.type!=="boolean")continue;const z=T.get(E.key),Y=!!($.values[E.key]??E.default);z?(z.onCount+=Y?1:0,z.total+=1):T.set(E.key,{label:E.label||E.key,onCount:Y?1:0,total:1})}const A=[...T.entries()].filter(([,$])=>$.total===O.length);if(A.length===0)return null;const U=async($,E)=>{for(const z of O)await b(z.type,$,E)};return s.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[s.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",O.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:A.map(([$,E])=>{const z=E.onCount===E.total,Y=E.onCount===0;return s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:E.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",E.onCount,"/",E.total,")"]}),s.jsx("button",{onClick:()=>void U($,!0),disabled:z,className:`machine-btn text-[9px] px-1.5 py-px ${z?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void U($,!1),disabled:Y,className:`machine-btn text-[9px] px-1.5 py-px ${Y?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},$)})})]})})(),i&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):s.jsx("div",{className:"flex flex-col gap-2",children:n.filter(O=>m==="all"||O.category===m).map(O=>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:O.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:O.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:O.category==="acp"?"rgba(139,92,246,0.08)":O.category==="cli"?"rgba(59,130,246,0.08)":O.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:O.category==="acp"?"#a78bfa":O.category==="cli"?"#60a5fa":O.category==="ide"?"#86efac":"var(--status-warning)"},children:O.category}),ci(O.category)&&(()=>{const T=t.find($=>$.type===O.type),A=(T==null?void 0:T.enabled)===!0||O.values.enabled===!0,U=(T==null?void 0:T.machineStatus)||(A?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${tb(U)}`,children:eb(U)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void B(O.type,!A),disabled:l===`${O.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${A?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:A?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void L(O.type),disabled:!A||l===`${O.type}.detect`,title:A?"Run detection for the configured executable":"Enable this provider before detection",className:`machine-btn text-[9px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${A?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void _(O.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),O.category==="ide"&&s.jsx("button",{onClick:()=>f(t.find(T=>T.type===O.type)||{type:O.type,name:O.displayName,displayName:O.displayName,icon:O.icon,category:O.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),ci(O.category)&&(()=>{const T=t.find(A=>A.type===O.type);return s.jsxs("div",{className:"mb-2.5 grid gap-1 rounded-lg border border-white/[0.06] bg-bg-primary/40 px-3 py-2 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Detection:"})," ",li(T==null?void 0:T.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",li(T==null?void 0:T.lastVerification)]}),s.jsx("div",{className:"text-[9px] text-text-muted",children:"Supported catalog entry only becomes launchable after Enable + Detect succeeds. Custom executable path/args below are machine-local overrides."})]})})(),s.jsx("div",{className:"flex flex-col gap-2",children:O.schema.map(T=>s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[T.label||T.key,l===`${O.type}.${T.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),T.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:T.description})]}),s.jsx("div",{className:"shrink-0",children:T.type==="boolean"?s.jsx("button",{onClick:()=>b(O.type,T.key,!(O.values[T.key]??T.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:O.values[T.key]??T.default?"#8b5cf6":"var(--border-subtle)"},children:s.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:O.values[T.key]??T.default?21:3}})}):T.type==="number"?s.jsx("input",{type:"number",value:Number(O.values[T.key]??T.default??0)||0,min:T.min,max:T.max,onChange:A=>{const U=parseInt(A.target.value)||0;T.min!==void 0&&U<T.min||T.max!==void 0&&U>T.max||b(O.type,T.key,U)},className:"machine-input w-20 text-center text-[11px]"}):T.type==="select"&&T.options?s.jsx("select",{value:String(O.values[T.key]??T.default??""),onChange:A=>b(O.type,T.key,A.target.value),className:"machine-input text-[11px]",children:T.options.map(A=>s.jsx("option",{value:A,children:A},A))}):s.jsx("input",{type:"text",value:String(O.values[T.key]??T.default??""),onBlur:A=>b(O.type,T.key,A.target.value),className:"machine-input w-[120px] text-[11px]"})})]},T.key))})]},O.type))}),h&&s.jsx(Qx,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>f(null)}),j&&s.jsx(Zx,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>N(!1),onCreated:()=>{N(!1),k()}})]})}const rb=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function nb({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function ab(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function ob(e){return e.trim().toLowerCase()}function dn(e,t){const r=ob(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Za(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Ms(e,t=220){const r=Za(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function ib(e){const t=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(t))return{kind:t.length>0?"structured":"empty",entries:t.map(r=>{const n=r;return{timestamp:Number(n.ts)||0,level:n.level||"info",message:`[${String(n.category||"daemon")}] ${String(n.message||"")}`.trim()}}),rawText:""};if(typeof t=="string"){const r=t.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function cb(e,t){return e.filter(r=>dn([r.level,r.message],t))}function di(e){return`${e.timestamp}:${e.level}:${e.message}`}function lb(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const c of e.entries)n.set(di(c),c);for(const c of t.entries)n.set(di(c),c);const a=Array.from(n.values()).sort((c,l)=>c.timestamp-l.timestamp).slice(-r),i=a.reduce((c,l)=>Math.max(c,Number(l.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:i}}return t.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:t.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function db(e,t,r=120){if(t.length===0)return e;const n=new Map;for(const a of e)n.set(a.id,a);for(const a of t)n.set(a.id,a);return Array.from(n.values()).sort((a,i)=>a.ts-i.ts).slice(-r)}function ub(e,t){return e.split(`
|
|
63
|
+
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>dn([r],t))}function mb(e,t){return e.filter(r=>dn([r.level,r.category,r.stage,r.interactionId,Za(r.payload)],t))}function fb(e,t){return e.filter(r=>dn([r.kind,r.topic,r.interactionId,Za(r.payload)],t))}function ui(e){return e==="warn"||e==="error"}function pb({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){return{all:e.length+t.length+r.length+n.length,info:e.filter(a=>a.level!=="debug").length+r.filter(a=>a.level!=="debug").length+n.length,issues:e.filter(a=>ui(a.level)).length+r.filter(a=>ui(a.level)).length}}function hb({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(i=>`${new Date(i.timestamp).toISOString()} ${i.level.toUpperCase()} ${i.message}`)].join(`
|
|
64
64
|
`)):t.length>0&&a.push(["[daemon logs]",...t].join(`
|
|
65
|
-
`)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${
|
|
66
|
-
`)),n.length>0&&a.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${
|
|
65
|
+
`)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${Ms(i.payload,500)}`.trim())].join(`
|
|
66
|
+
`)),n.length>0&&a.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${Ms(i.payload,500)}`.trim())].join(`
|
|
67
67
|
`)),a.join(`
|
|
68
68
|
|
|
69
|
-
`)}function
|
|
69
|
+
`)}function xb({machineId:e,sendDaemonCommand:t}){const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[u,m]=o.useState([]),[d,h]=o.useState([]),[f,j]=o.useState(null),[N,p]=o.useState(!0),[x,y]=o.useState("info"),[g,C]=o.useState("all"),[I,v]=o.useState(!0),[M,S]=o.useState(!0),[k,b]=o.useState(""),[B,L]=o.useState(""),[_,H]=o.useState(0),F=o.useRef(0),O=o.useRef(0),T=o.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),A=o.useRef([]),U=o.useCallback(()=>{const ye={entries:[],kind:"empty",rawText:"",lastTs:0};T.current=ye,F.current=0,n([]),l(""),i("empty"),v(!0)},[]),$=o.useCallback(()=>{A.current=[],O.current=0,m([]),S(!0)},[]),E=o.useCallback(ye=>{ye!==x&&(U(),y(ye))},[x,U]),z=o.useCallback(ye=>{C(le=>le===ye?le:ye)},[]),Y=o.useCallback(()=>{U(),$(),h([]),j(null),b(""),L(""),js.clear()},[U,$]),ve=o.useCallback(()=>{H(ye=>ye+1)},[]),re=o.useCallback(async()=>{if(!e)return;const ye=F.current,le=O.current,[be,ge]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:x,since:ye}),t(e,"get_debug_trace",nb({count:120,since:le,category:g}))]);if(be.status==="fulfilled"){const G=be.value,ne=(G==null?void 0:G.result)||G,q=ib(ne),ue=lb(T.current,q,300);T.current=ue,F.current=ue.lastTs,v(!1),b((G==null?void 0:G.success)===!1?String((G==null?void 0:G.error)||"Could not load daemon logs"):""),i(ue.kind),l(ue.rawText),n(ue.entries)}else v(!1),b(be.reason instanceof Error?be.reason.message:"Could not load daemon logs");if(ge.status==="fulfilled"){const G=ge.value,ne=(G==null?void 0:G.result)||G;if((G==null?void 0:G.success)===!1)L(String((G==null?void 0:G.error)||"Could not load daemon trace"));else if(Array.isArray(ne==null?void 0:ne.trace)){const q=ne.trace,ue=db(A.current,q,120),ce=q.reduce((je,ae)=>Math.max(je,Number(ae.ts||0)),le);A.current=ue,ce>le&&(O.current=ce),L(""),m(ue)}else L("");S(!1)}else S(!1),L(ge.reason instanceof Error?ge.reason.message:"Could not load daemon trace");h(js.list({limit:120})),j(Date.now())},[x,e,t,g]);return o.useEffect(()=>{$()},[$,g]),o.useEffect(()=>{if(!e||(re(),!N))return;const ye=setInterval(()=>{re()},3e3);return()=>clearInterval(ye)},[N,re,e,_]),{daemonLogs:r,daemonLogKind:a,daemonRawText:c,debugTrace:u,webEvents:d,lastUpdatedAt:f,autoRefresh:N,logLevel:x,traceCategory:g,daemonLoading:I,traceLoading:M,daemonFetchError:k,traceFetchError:B,setAutoRefresh:p,setLogLevel:E,setTraceCategory:z,refresh:ve,clear:Y}}function bb({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:i,daemonRawLineCount:c,traceCount:l,webEventCount:u}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":i>0||c>0?"ok":"empty",detail:r||(a==="text"?`${c} raw file-fallback line(s)`:`${i} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":t?"loading":l>0?"ok":"empty",detail:n||`${l} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:u>0?"ok":"empty",detail:u>0?`${u} local browser event(s)`:"No browser events captured"}]}function mi(e){return e==="warn"||e==="error"}function gb(e){const t=e.toLowerCase();return/\[(err|error)\]/i.test(e)||t.includes(" error ")||t.includes(" failed")?"error":/\[(wrn|warn|warning)\]/i.test(e)||t.includes(" warning ")||t.includes(" timeout")?"warn":/\[(dbg|debug)\]/i.test(e)?"debug":"info"}function yb(e,t){const r=e.match(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\b/);if(r){const n=Date.parse(r[0]);if(Number.isFinite(n))return n}return Number.MAX_SAFE_INTEGER-1e5+t}function fi(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function vb(e){const t=Ms(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function wb(e){const t=Ms(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function jb({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.forEach((i,c)=>{a.push({id:`daemon-log-${i.timestamp}-${c}`,source:"daemon_log",ts:Number(i.timestamp||0),severity:i.level,message:i.message,raw:i.message})}),n.forEach(i=>{a.push({id:`browser-event-${i.id}`,source:"browser_event",ts:Number(i.ts||0),severity:"info",message:wb(i),topic:i.topic,interactionId:i.interactionId,payload:i.payload})}),r.forEach(i=>{a.push({id:`daemon-trace-${i.id}`,source:"daemon_trace",ts:Number(i.ts||0),severity:i.level,message:vb(i),category:i.category,stage:i.stage,interactionId:i.interactionId,payload:i.payload})}),t.forEach((i,c)=>{a.push({id:`raw-file-${c}`,source:"raw_file",ts:yb(i,c),severity:gb(i),message:i,raw:i})}),a.sort((i,c)=>i.ts!==c.ts?i.ts-c.ts:fi(i.source)-fi(c.source))}function kb(e){return`${e.source}:${e.severity}:${e.message}`}function Sb(e){const t=e.filter(n=>mi(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!mi(n.severity))continue;const a=kb(n),i=r.get(a);i?(i.count+=1,i.firstTs=Math.min(i.firstTs,n.ts),i.lastTs=Math.max(i.lastTs,n.ts)):r.set(a,{key:a,source:n.source,severity:n.severity,message:n.message,count:1,firstTs:n.ts,lastTs:n.ts})}return{totalCount:e.length,issueCount:t.length,latestIssue:t[0]||null,repeatedPatterns:Array.from(r.values()).filter(n=>n.count>1).sort((n,a)=>a.count!==n.count?a.count-n.count:a.lastTs-n.lastTs).slice(0,5)}}function Nb(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function pi(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${Nb(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function Cb({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
|
|
70
70
|
`)),a.push(["[source status]",...r.map(c=>`${c.label}: ${c.status} - ${c.detail}`)].join(`
|
|
71
|
-
`)),t.latestIssue&&a.push(["[latest issue]",
|
|
71
|
+
`)),t.latestIssue&&a.push(["[latest issue]",pi(t.latestIssue)].join(`
|
|
72
72
|
`)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(c=>`${c.count}x ${c.severity.toUpperCase()} ${c.source} ${c.message}`)].join(`
|
|
73
|
-
`));const i=e.slice(-n);return a.push(["[timeline]",...i.length>0?i.map(
|
|
73
|
+
`));const i=e.slice(-n);return a.push(["[timeline]",...i.length>0?i.map(pi):["No diagnostic events captured."]].join(`
|
|
74
74
|
`)),a.join(`
|
|
75
75
|
|
|
76
|
-
`)}function Ib(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Ab(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Lb({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:i,quickFilter:c,searchQuery:l,daemonLoading:u,traceLoading:m,daemonFetchError:d,traceFetchError:h}){const f=ib(n,i),j=db(e,l),N=fb(t,l),p=pb(f,l),x=hb(a,l),y=Ib(j,c),g=c==="all"?N:[],C=Ab(p,c),I=c==="issues"?[]:x,v=xb({daemonLogs:j,daemonRawLines:N,trace:p,webEvents:x}),T=Sb({daemonLogs:y,daemonRawLines:g,trace:C,webEvents:I}),S=Cb(T),k=yb({daemonLoading:u,traceLoading:m,daemonFetchError:d,traceFetchError:h,daemonLogKind:r,daemonLogsCount:j.length,daemonRawLineCount:N.length,traceCount:p.length,webEventCount:x.length});return{filteredDaemonLogs:j,filteredDaemonRawLines:N,filteredTraceEntries:p,filteredWebEvents:x,visibleDaemonLogs:y,visibleDaemonRawLines:g,visibleTraceEntries:C,visibleWebEvents:I,quickFilterCounts:v,diagnosticEvents:T,diagnosticsSummary:S,sourceStates:k}}function Rb(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function wl(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function pa(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 Kn(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 eo(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function _b({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${pa(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:wl(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:eo(e.source)}),e.category&&e.stage&&s.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&s.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&s.jsxs("span",{children:["ix=",e.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function Pb({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:c,onCopyVisible:l,onToggleAutoRefresh:u,onRefresh:m,onClear:d}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(h=>s.jsx("button",{type:"button",onClick:()=>a(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),s.jsx("input",{value:r,onChange:h=>i(h.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:l,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:u,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:d,className:"machine-btn",children:"Clear"})]})]})}function Db({logLevel:e,traceCategory:t,onLogLevelChange:r,onTraceCategoryChange:n}){return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>s.jsxs("button",{onClick:()=>r(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:ab.map(a=>s.jsx("button",{onClick:()=>n(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function Eb({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:i,daemonFetchError:c,traceFetchError:l}){var d,h;const u=((d=e.latestIssue)==null?void 0:d.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",m=c||l?"danger":i?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Kn(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:n.trim()?`Filtered by “${n.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Kn(u)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[eo(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:wl(e.latestIssue.ts)})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Kn(m)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:c||l?"Needs attention":i?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",Rb(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(f=>s.jsxs("div",{children:[f.label,": ",f.status]},f.id))})]})]})}function $b({patterns:e}){return e.length===0?null:s.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[s.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",eo(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function Bb({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:i,visibleTraceEntries:c,visibleWebEvents:l,quickFilter:u,searchQuery:m}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,timeline:!d.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(d=>s.jsx(_b,{event:d},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,daemon:!d.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${i.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&i.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&i.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:u==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&i.map((d,h)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:d},`raw-${h}`)),e.daemonLogKind!=="text"&&a.map((d,h)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${pa(d.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(d.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:d.level==="error"?"ERR":d.level==="warn"?"WRN":d.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:d.message})]},`log-${h}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,trace:!d.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&c.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),c.map(d=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${pa(d.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.level.toUpperCase()}),s.jsxs("span",{children:[d.category,".",d.stage]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Ts(d.payload,360)||"No payload"})]},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,web:!d.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[l.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),l.map(d=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.kind}),d.topic&&s.jsxs("span",{children:["topic=",d.topic]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Ts(d.payload,360)||"No payload"})]},d.id))]})]})]})}function Kb({machineId:e,sendDaemonCommand:t}){const r=gb({machineId:e,sendDaemonCommand:t}),[n,a]=o.useState("info"),[i,c]=o.useState(""),[l,u]=o.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=o.useRef(null),d=o.useRef(!1),h=o.useMemo(()=>Lb({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:i,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,i,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);o.useEffect(()=>{if(r.autoRefresh&&h.diagnosticEvents.length>0){const N=d.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:N}),d.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const f=o.useCallback(async()=>{var p;const N=bb({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!N.trim()){it.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(N)),it.showToast("Copied visible logs to clipboard.","success")}catch(x){it.showToast(x instanceof Error?x.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),j=o.useCallback(async()=>{var p;const N=Tb({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(N)),it.showToast("Copied diagnostic bundle to clipboard.","success")}catch(x){it.showToast(x instanceof Error?x.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(Pb,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:i,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{j()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>r.setAutoRefresh(N=>!N),onRefresh:r.refresh,onClear:r.clear}),s.jsx(Db,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(Eb,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:i,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx($b,{patterns:h.diagnosticsSummary.repeatedPatterns}),s.jsx(Bb,{streams:r,sectionsOpen:l,setSectionsOpen:u,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:i}),s.jsx("div",{ref:m})]})}function Ob(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 jl(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 Wb(e){var a;const t=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=jl((i==null?void 0:i.meta)||void 0),u=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?t.push(i):(c==="stopped"||c==="failed")&&(u||l)?r.push(i):n.push(i)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function Hb(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function On(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 Wn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Hn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function xi(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 Fb(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Ub(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 zb(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 Vb({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),m=Np(e,{enabled:!!e,includeSessions:!0,limit:To,intervalMs:Em}),d=m.diagnostics,h=m.loading,f=m.applyDiagnostics,j=o.useMemo(()=>Ob({diagnostics:d,loading:h,refreshing:l,error:n}),[d,h,l,n]),N=o.useMemo(()=>new Map(t.map(L=>[L.sessionId||L.id,L])),[t]),p=o.useCallback(async()=>{if(e){u(!0);try{const L=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:To}),_=Wn(L);if(!(_!=null&&_.success))throw new Error((_==null?void 0:_.error)||"Could not load hosted runtime diagnostics");f(_.diagnostics||_.result||null),a("")}catch(L){const _=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";a(_)}finally{u(!1)}}},[f,e,r]);o.useEffect(()=>{!e||d||h||l||p()},[d,h,e,p,l]);const x=o.useCallback(async(L,_)=>{const H=`${L}:${_.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${_.displayName}?
|
|
77
|
-
This will terminate the hosted runtime.`))){c(H);try{const F=await r(e,L,{sessionId:_.sessionId}),O=Wn(F);if(!(O!=null&&O.success))throw new Error((O==null?void 0:O.error)||"Session host action failed");const
|
|
78
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const _=await r(e,"session_host_prune_duplicate_sessions",{}),H=Wn(_);if(!(H!=null&&H.success))throw new Error((H==null?void 0:H.error)||"Duplicate prune failed");const F=H.result||{},O=Array.isArray(F.prunedSessionIds)?F.prunedSessionIds.length:0,M=typeof F.duplicateGroupCount=="number"?F.duplicateGroupCount:0;it.showToast(`Pruned ${O} duplicate runtime(s) across ${M} group(s)`,"success"),await p()}catch(_){const H=_ instanceof Error?_.message:"Duplicate prune failed";it.showToast(H,"warning"),a(H)}finally{c(_=>_==="session_host_prune_duplicate_sessions"?null:_)}}},[e,p,r]),g=o.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((L,_)=>(_.lastActivityAt||0)-(L.lastActivityAt||0)),[d==null?void 0:d.sessions]),C=o.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:Wb(g),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,g]),I=C.liveRuntimes,v=C.recoverySnapshots,T=C.inactiveRecords,S=o.useMemo(()=>zb(I),[I]),k=o.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),b=o.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[d==null?void 0:d.recentLogs]),B=(L,_)=>{var z;const H=i===`session_host_resume_session:${L.sessionId}`,F=i===`session_host_restart_session:${L.sessionId}`,O=i===`session_host_stop_session:${L.sessionId}`,M=jl(L.meta),A=N.get(L.sessionId),U=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,$=_==="recovery"?"Recover":"Resume",E=Hb(_);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:L.displayName||(A==null?void 0:A.cliName)||L.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Ub(L.lifecycle)}`,children:L.lifecycle}),M&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:M})]}),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:L.workspaceLabel||(A==null?void 0:A.runtimeWorkspaceLabel)||L.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:L.runtimeKey}),L.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",L.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((z=L.writeOwner)==null?void 0:z.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Fb(L.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(Li,{size:11})," ",U]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",xi(L.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[_==="recovery"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_resume_session",L)},children:H?`${$}ing…`:$}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_restart_session",L)},children:F?"Restarting…":"Restart"}),_==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{x("session_host_stop_session",L)},children:O?"Stopping…":"Stop"})]})]})},L.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(is,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Lf()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[S>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${S})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${j.toneClass}`,children:j.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||l,children:[s.jsx(nr,{size:13}),h||l?"Refreshing…":"Refresh"]})]})]}),n&&!d&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(Zs,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:v.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:xi(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Hn(d.hostStartedAt)})]})]}),b&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(Zs,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:b.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Hn(b.timestamp),b.sessionId?` · ${b.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(ja,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:On("live")}),I.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:I.map(L=>B(L,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(is,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:On("recovery")}),v.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:v.map(L=>B(L,"recovery"))})]}),T.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:On("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:T.map(L=>B(L,"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"}),k.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:k.map(L=>{var H;const _=g.find(F=>F.sessionId===L.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:(_==null?void 0:_.displayName)||((H=N.get(L.sessionId))==null?void 0:H.cliName)||L.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[L.action,L.lifecycle?` · ${L.lifecycle}`:"",L.detail?` · ${L.detail}`:"",L.error?` · ${L.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${L.success===!1?"text-red-300":"text-text-secondary"}`,children:Hn(L.timestamp)})]},`${L.sessionId}:${L.timestamp}:${L.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Gb({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 Fn({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 Un({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 qb({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),d=qs(e,"0.9.44");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(Fn,{icon:s.jsx(Wt,{size:13}),children:"Current Chats"}),s.jsx(Un,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const f=na(h);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(h),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:at(h)}),f>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Qr(f)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ls(h)})]},h.tabKey)})})})]}),u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Fn,{icon:s.jsx(Ei,{size:13}),children:"Recent Launches"}),s.jsx(Un,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:f,updatedLabel:j}=rl(h);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(h),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:h.label}),j&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:j})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:f})]},h.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Fn,{icon:s.jsx(Zs,{size:13}),children:"Daemon Update"}),s.jsx(Un,{className:"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:d?"Daemon update required":"Version mismatch detected"}),s.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:d?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(nr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Yb(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function Xb({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:i,onCustomPathChange:c,onOpenBrowseDialog:l}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,onChange:u=>{const m=u.target.value;if(i(m),m==="__custom__"&&a){l();return}m!=="__custom__"&&c("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(e.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(u=>s.jsxs("option",{value:u.id,children:[u.id===e.defaultWorkspaceId?"⭐ ":"",en(u.path,u.label)]},u.id)),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),t==="__custom__"&&(a?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:l,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:u=>c(u.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:t==="__custom__"?r?s.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:t===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const Jb={ide:{label:"IDE",plural:"IDEs",accent:"border-blue-500/[0.12]"},cli:{label:"CLI",plural:"CLIs",accent:"border-violet-500/[0.12]"},acp:{label:"ACP Agent",plural:"ACP agents",accent:"border-emerald-500/[0.12]"}};function Nr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function zn({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:m}){const d=Is(),{handleLaunchIde:h,handleStopCli:f,handleRestartIde:j,handleStopIde:N,handleDetectIdes:p,launchingIde:x,launchingAgentType:y,addLog:g}=c,[C,I]=o.useState(null),v=o.useCallback(K=>{K&&d(zt(K))},[d]),T=Jb[e],S=e==="ide",k=e==="acp",b=o.useMemo(()=>n.filter(K=>us(K,e)),[e,n]),B=o.useMemo(()=>new Map(b.map(K=>[K.type,K.displayName||K.type])),[b]),[L,_]=o.useState(""),[H,F]=o.useState(""),[O,M]=o.useState([]),[A,U]=o.useState(""),[$,E]=o.useState(""),[z,Y]=o.useState([]),[ve,re]=o.useState(!1),[ye,le]=o.useState(!1),[be,ge]=o.useState(""),[G,ne]=o.useState(!1),[q,ue]=o.useState(()=>ht()),[ce,je]=o.useState(null),[ae,fe]=o.useState(m?"__custom__":u||t.defaultWorkspaceId||""),[oe,te]=o.useState(m||""),[ee,X]=o.useState([]),[J,de]=o.useState(!1),[D,ie]=o.useState(""),[Q,we]=o.useState([]),[Ne,Ae]=o.useState(!1),[Te,Ue]=o.useState(""),We=o.useRef(null),[Ke,Ge]=o.useState(null),Ze=o.useRef("__home__"),[Je,Ye]=o.useState("__home__"),[mt,pt]=o.useState(!1),dt=o.useRef(0),Ce=ee.filter(K=>!a.some(se=>se.type===K&&bt(se.status)!=="stopped")),He=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!ae&&fe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(m){fe("__custom__"),te(m);return}u&&(fe(u),te(""))},[u,m]),o.useEffect(()=>{S||L&&(b.some(K=>K.type===L)||(_(""),E("")))},[b,S,L]);const Xe=(()=>{if(ae==="__custom__")return oe.trim();if(!ae)return"";const K=(t.workspaces||[]).find(se=>se.id===ae);return(K==null?void 0:K.path)||""})(),ot=o.useCallback(K=>{const se=He.current[K];se&&(clearTimeout(se),delete He.current[K]),X(xe=>xe.includes(K)?xe.filter(Pe=>Pe!==K):xe)},[]),ft=o.useRef(new Set),W=o.useCallback(async K=>{if(l){Ae(!0),Ue("");try{const se=await an(l,r,K);ie(se.path),te(se.path),we(se.directories)}catch(se){Ue(se instanceof Error?se.message:"Could not load folder")}finally{Ae(!1)}}},[r,l]),w=o.useCallback(()=>{if(!l)return;fe("__custom__"),de(!0);const K=a.map(xe=>xe.workspace),se=nn(t.platform,rn(oe.trim(),Xe,m,K,t.defaultWorkspacePath,(t.workspaces||[]).map(xe=>xe.path)));W(se)},[oe,m,W,t.defaultWorkspacePath,t.platform,t.workspaces,a,Xe,l]),R=o.useCallback(K=>{const se=String(K.workspace||"").trim();if(!se)return;const xe=(t.workspaces||[]).find(Pe=>Nr(Pe.path)===Nr(se));if(xe){fe(xe.id),te("");return}fe("__custom__"),te(se)},[t.workspaces]),P=o.useCallback(K=>{const se=String(K.workspace||"").trim();if(!se)return{workspaceId:null,workspacePath:"",useHome:!0};const xe=(t.workspaces||[]).find(Pe=>Nr(Pe.path)===Nr(se));return xe?{workspaceId:xe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:se,useHome:!1}},[t.workspaces]),V=o.useCallback(async K=>{if(!l||!K||e!=="cli"){Y([]),re(!1),le(!1),ge("");return}const se=dt.current+1;dt.current=se,re(!0),ge("");try{const xe=await l(r,"list_saved_sessions",{providerType:K,kind:"cli",limit:30});if(dt.current!==se)return;const Pe=(xe==null?void 0:xe.result)??xe;Y(Array.isArray(Pe==null?void 0:Pe.sessions)?Pe.sessions:[])}catch(xe){if(dt.current!==se)return;Y([]),ge(xe instanceof Error?xe.message:"Could not load saved sessions")}finally{dt.current===se&&(re(!1),le(!0))}},[e,r,l]),Z=o.useMemo(()=>{if(e!=="cli"||!L)return null;const K=B.get(L)||L;return{routeId:r,daemonId:r,providerSessionId:$||void 0,transport:"pty",mode:"chat",agentName:K,agentType:L,status:"idle",title:K,messages:[],ideType:L,workspaceName:Xe,displayPrimary:K,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${L}`}},[e,r,B,Xe,$,L]),me=o.useCallback(K=>{if(e==="ide"||!K){M([]);return}M(bl(r,K))},[e,r]);o.useEffect(()=>{dt.current+=1,E(""),me(L),le(!1),Y([]),ge(""),re(!1)},[e,me,V,L]);const he=o.useMemo(()=>z.find(K=>K.providerSessionId===$)||null,[z,$]);o.useEffect(()=>{if(!$)return;const K=z.find(se=>se.providerSessionId===$);K!=null&&K.canResume||E("")},[z,$]);const Se=o.useCallback((K,se)=>{We.current=se,Ze.current=K.selectedWorkspaceKey||"__home__",Ye(K.selectedWorkspaceKey||"__home__"),Ge(K)},[]),Re=o.useCallback(()=>{We.current&&(pt(!0),We.current().finally(()=>{We.current=null,pt(!1),Ge(null)}))},[]),ke=o.useCallback(K=>{if(!K)return;X(xe=>xe.includes(K)?xe:[...xe,K]);const se=He.current[K];se&&clearTimeout(se),He.current[K]=setTimeout(()=>{X(xe=>xe.includes(K)?xe.filter(Pe=>Pe!==K):xe),delete He.current[K]},2e4)},[]);o.useEffect(()=>{for(const se of a)bt(se.status)!=="stopped"&&(ee.includes(se.type)&&!ft.current.has(se.type)&&(ft.current.add(se.type),g("info",`${B.get(se.type)||se.type} launched`,!0)),ot(se.type));const K=new Set(a.filter(se=>bt(se.status)!=="stopped").map(se=>se.type));ft.current.forEach(se=>{!ee.includes(se)&&!K.has(se)&&ft.current.delete(se)})},[g,ot,a,ee,B]),o.useEffect(()=>()=>{Object.values(He.current).forEach(clearTimeout),He.current={}},[]);const[Ee,$e]=o.useState({}),[Be,Ie]=o.useState(null);o.useEffect(()=>{if(!S||!r||!l)return;(async()=>{try{const se=await l(r,"get_ide_extensions",{}),xe=(se==null?void 0:se.result)||se;xe!=null&&xe.success&&(xe!=null&&xe.ideExtensions)&&$e(xe.ideExtensions)}catch{}})()},[S,r,l]);const qe=K=>S?rt(K.type):e==="cli"?K.cliName:K.acpName,ct=S?t.detectedIdes||[]:[],pe=o.useCallback(async K=>{const se=(K==null?void 0:K.type)||L,xe=(K==null?void 0:K.workspacePath)??Xe;if(S){await h(se,xe?{workspace:xe}:void 0)&&ke(se);return}const Pe=await c.runLaunchCliCore({cliType:se,dir:K!=null&&K.workspaceId?void 0:xe||void 0,workspaceId:(K==null?void 0:K.workspaceId)||void 0,useHome:(K==null?void 0:K.useHome)||!(K!=null&&K.workspaceId)&&!xe,argsStr:(K==null?void 0:K.argsStr)??(H||void 0),model:(K==null?void 0:K.model)??(k&&A||void 0),resumeSessionId:(K==null?void 0:K.resumeSessionId)||!k&&e==="cli"&&se===L&&$||void 0});if(Pe.success||Pe.pending){const Me=(K==null?void 0:K.argsStr)??H;!S&&(Me!=null&&Me.trim())&&(gl(r,se,Me),me(se)),ke(se),Pe.success&&Pe.sessionId&&v(Pe.sessionId)}},[c,h,k,S,H,A,me,ke,r,v,Xe,$,L]),Le=Sc(S?"ide":k?"acp":"cli",!S&&!k&&!!$),et=Nc(S?"ide":k?"acp":"cli",!S&&!k&&!!$),nt=()=>{var Me;const K=S?rt(L):B.get(L)||L,se=!S&&!k&&!!$,{options:xe,selectedKey:Pe}=ns({machine:t,currentWorkspaceId:ae&&ae!=="__custom__"?ae:null,currentWorkspacePath:Xe});Se({title:se?Ka(K):es("start-fresh",K),description:se?Oa():ts("start-fresh"),confirmLabel:Le,busyLabel:et,workspaceOptions:xe,selectedWorkspaceKey:Pe,details:[{label:"Mode",value:T.label},{label:"Provider",value:K},...!S&&e==="cli"&&$?[{label:"Resume",value:((Me=z.find(_e=>_e.providerSessionId===$))==null?void 0:Me.title)||$}]:[],...!S&&H.trim()?[{label:"Arguments",value:H.trim()}]:[],...k&&A.trim()?[{label:"Model",value:A.trim()}]:[]]},async()=>{const _e=xe.find(tt=>tt.key===Ze.current);_e!=null&&_e.workspaceId?(fe(_e.workspaceId),te("")):_e!=null&&_e.workspacePath?(fe("__custom__"),te(_e.workspacePath)):(fe(""),te("")),await pe({workspaceId:(_e==null?void 0:_e.workspaceId)??null,workspacePath:(_e==null?void 0:_e.workspacePath)??"",useHome:!(_e!=null&&_e.workspaceId)&&!(_e!=null&&_e.workspacePath)})})},Oe=K=>{S?N(K):f(K.type,K.workspace,K.id)},Tt=o.useCallback(async(K,se,xe=!1)=>{if(K.mode===se){xe&&K.sessionId&&v(K.sessionId);return}if(!l||!K.sessionId){xe&&K.sessionId&&v(K.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:K.sessionId,cliType:K.type,mode:se}),xe&&v(K.sessionId)}catch(Pe){const Me=zc(Pe);Uc(Pe)?console.warn(Me?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Pe instanceof Error?Pe.message:String(Pe)):console.error("Failed to switch CLI view mode:",Pe)}},[r,v,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${T.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 ",T.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:S?ct.length>0?ct.map(K=>{const se=a.find(tt=>(tt.type||"").toLowerCase()===(K.type||"").toLowerCase()&&bt(tt.status)!=="stopped"),xe=K.running||!!se,Pe=!!se&&se.cdpConnected,Me=ee.includes(K.type||K.id||""),_e=L===(K.type||"");return s.jsxs("button",{onClick:()=>{if(Pe&&se){const tt=se.sessionId;tt?d(zt(tt),{state:{openRemoteForTabKey:tt}}):d("/dashboard",{state:{openRemoteForTabKey:se.id}});return}Me||_(tt=>tt===(K.type||"")?"":K.type||"")},disabled:!!x||Me,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Pe?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":_e?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:x&&x!==K.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(K.type)}),xe&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Pe?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:K.name||rt(K.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Pe?"text-green-400":Me?"text-orange-400":_e?"text-accent-primary":"text-text-muted"}`,children:Pe?"Open Session":Me?"Starting...":_e?"Configure":"Select"})]})]},K.type)}):s.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",s.jsxs("button",{onClick:p,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[s.jsx(Ed,{size:14})," Scan System"]})]}):b.length>0?b.map(K=>{const se=L===K.type,xe=ee.includes(K.type),Me=!!a.find(_e=>_e.type===K.type&&bt(_e.status)!=="stopped");return s.jsxs("button",{onClick:()=>_(_e=>_e===K.type?"":K.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${se?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:K.icon}),Me&&s.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:K.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${xe?"text-orange-400":se?"text-accent-primary":"text-text-muted"}`,children:xe?"Starting...":se?"Configure":"Select"})]})]},K.type)}):s.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),L&&(S?ct.find(K=>K.type===L):b.find(K=>K.type===L))&&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:S?rt(L):B.get(L)||L})]}),s.jsx(Xb,{machine:t,selectedWorkspace:ae,resolvedWorkspacePath:Xe,customPath:oe,canBrowse:!!l,onWorkspaceChange:fe,onCustomPathChange:te,onOpenBrowseDialog:w}),!S&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!k&&e==="cli"&&s.jsx(vl,{busy:!!y||!!x||ee.includes(L),savedSessionsLoading:ve,savedSessionsError:be,selectedSession:he,onRefresh:()=>void V(L),onOpenHistory:()=>{L&&(ne(!0),yl({hasLoadedInitialResults:ye,isLoading:ve})&&V(L))},onClearSelection:()=>E("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[k&&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:A,onChange:K=>U(K.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),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:H,onChange:K=>F(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"}),O.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:O.map(K=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>F(K),title:K,children:K},K))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:nt,disabled:!!y||!!x||ee.includes(L),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:y===L||x===L?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ee.filter(K=>!a.some(se=>se.type===K&&bt(se.status)!=="stopped")).length,")"]}),a.length===0&&Ce.length===0?s.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",T.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ce.map(K=>s.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(K)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:S?rt(K):B.get(K)||K}),s.jsx("div",{className:"text-[11px] text-text-muted",children:y===K?"Launching process...":"Waiting for process and session to register..."})]})]}),s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${K}`)),a.map(K=>{const se=S?K:null,xe=!S&&!k?K:null,Pe=bt(K.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(K.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[qe(K),(se==null?void 0:se.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",se.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[s.jsx("span",{children:K.workspace||"—"}),(xe==null?void 0:xe.mode)&&s.jsx("span",{className:xe.mode==="chat"?"text-violet-400":"text-text-secondary",children:xe.mode==="chat"?"Chat view":"Terminal view"})]}),xe&&(xe.runtimeKey||xe.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[xe.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 ",xe.runtimeKey]}),s.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Me;(Me=navigator.clipboard)==null||Me.writeText(`adhdev attach ${xe.runtimeKey}`),I(xe.runtimeKey||null),window.setTimeout(()=>{I(_e=>_e===xe.runtimeKey?null:_e)},1200)},children:C===xe.runtimeKey?"Copied":"Copy"})]}),xe.runtimeWriteOwner&&s.jsx("span",{style:{color:xe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:xe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Yb(xe.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Pe==="stopped"?"bg-red-500/[0.08] text-red-500":Pe==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Pe}),S&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Me=K.sessionId;if(Me){d(zt(Me),{state:{openRemoteForTabKey:Me}});return}d("/dashboard",{state:{openRemoteForTabKey:K.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:s.jsx(St,{size:13})}),s.jsx("button",{onClick:()=>{const Me=K.workspace||"",{options:_e,selectedKey:tt}=ns({machine:t,currentWorkspacePath:Me});Se({title:es("restart-ide",rt(K.type)),description:ts("restart-ide"),confirmLabel:Cs("restart-ide"),busyLabel:Ms("restart-ide"),workspaceOptions:_e,selectedWorkspaceKey:tt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:rt(K.type)}]},async()=>{const yt=_e.find(Ht=>Ht.key===Ze.current),ut=(yt==null?void 0:yt.workspacePath)??"";if(ut&&ut!==Me){await pe({type:K.type,workspacePath:ut});return}await j(K)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:s.jsx(nr,{size:14})})]}),k&&s.jsx("button",{onClick:()=>{const Me=K.sessionId;Me&&v(Me)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!K.sessionId,children:s.jsx(Wt,{size:14})}),xe&&Pe!=="stopped"&&s.jsxs(s.Fragment,{children:[xe.mode&&s.jsx(Ea,{mode:xe.mode,onChange:Me=>void Tt(xe,Me,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Me=K.sessionId;Me&&v(Me)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!K.sessionId,children:xe.mode==="chat"?s.jsx(Wt,{size:14}):s.jsx(St,{size:13})})]}),Pe==="stopped"?s.jsx("button",{onClick:()=>{const Me=K.workspace||"",_e=S?rt(K.type):qe(K),{options:tt,selectedKey:yt}=ns({machine:t,currentWorkspacePath:Me});Se({title:es("restart-stopped",_e),description:ts("restart-stopped"),confirmLabel:Cs("restart-stopped"),busyLabel:Ms("restart-stopped"),workspaceOptions:tt,selectedWorkspaceKey:yt,details:[{label:"Mode",value:T.label},{label:"Provider",value:_e}]},async()=>{const ut=tt.find(Ht=>Ht.key===Ze.current);await pe({type:K.type,workspaceId:(ut==null?void 0:ut.workspaceId)??null,workspacePath:(ut==null?void 0:ut.workspacePath)??"",useHome:!(ut!=null&&ut.workspaceId)&&!(ut!=null&&ut.workspacePath)})})},disabled:ee.includes(K.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:ee.includes(K.type)?"⏳":s.jsx(ka,{size:14})}):s.jsx("button",{onClick:()=>Oe(K),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:s.jsx(vt,{size:14})})]})]}),se&&se.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:se.aiAgents.map(Me=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Gi(Me.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Me.name," · ",bt(Me.status)]},Me.id))}),se&&(Ee[se.type]||[]).length>0&&l&&s.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[s.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(Ee[se.type]||[]).map(Me=>s.jsxs("button",{disabled:Be===`${se.type}.${Me.type}`,onClick:async()=>{const _e=`${se.type}.${Me.type}`;Ie(_e);try{await l(r,"set_ide_extension",{ideType:se.type,extensionType:Me.type,enabled:!Me.enabled}),$e(tt=>({...tt,[se.type]:(tt[se.type]||[]).map(yt=>yt.type===Me.type?{...yt,enabled:!yt.enabled}:yt)}))}catch(tt){console.error("Extension toggle failed:",tt)}finally{Ie(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Me.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Me.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Me.name,s.jsx("span",{className:"text-[9px] font-normal",children:Me.enabled?"ON":"OFF"})]},Me.type))})]})]},K.id)})]}),J&&l&&s.jsx(cn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:D,directories:Q,busy:Ne,error:Te,confirmLabel:"Use this folder",onClose:()=>de(!1),onNavigate:K=>{W(K)},onConfirm:K=>{te(K),fe("__custom__"),de(!1)}}),Ke&&s.jsx(Ja,{title:Ke.title,description:Ke.description,details:Ke.details,workspaceOptions:Ke.workspaceOptions,selectedWorkspaceKey:Je,onWorkspaceChange:K=>{Ze.current=K,Ye(K)},confirmLabel:Ke.confirmLabel,busyLabel:Ke.busyLabel,busy:mt,onConfirm:Re,onCancel:()=>{We.current=null,Ge(null)}}),G&&Z&&s.jsx(Wa,{activeConv:Z,ides:[],isCreatingChat:!1,isRefreshingHistory:ve,savedSessions:z,isSavedSessionsLoading:ve,isResumingSavedSessionId:ce,savedHistoryFilters:q,onSavedHistoryFiltersChange:ue,onClose:()=>ne(!1),onNewChat:()=>{E(""),ne(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{V(L)},onResumeSavedSession:K=>{if(!K.canResume||ce)return;const se=P(K);E(K.providerSessionId),R(K),je(K.providerSessionId),ne(!1),pe({type:K.providerType,workspaceId:se.workspaceId,workspacePath:se.workspacePath,useHome:se.useHome,resumeSessionId:K.providerSessionId}).finally(()=>{je(xe=>xe===K.providerSessionId?null:xe)})}})]})}const bi=[{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 Qb({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:m,initialWorkspacePath:d,sendDaemonCommand:h}){var p;const[f,j]=o.useState(u);o.useEffect(()=>{j(u)},[u]);const N=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:bi.map(x=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${f===x.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>j(x.id),children:[s.jsx("span",{children:x.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${f===x.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:N[x.id]})]},x.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(p=bi.find(x=>x.id===f))==null?void 0:p.helper})]}),f==="ide"&&s.jsx(zn,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d}),f==="cli"&&s.jsx(zn,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d}),f==="acp"&&s.jsx(zn,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d})]})}function Zb({onNicknameSynced:e}={}){var je,ae,fe,oe,te,ee,X,J,de;const{id:t}=od(),r=Is(),n=ga(),{sendCommand:a}=wt(),i=ir(),c=Oc(),l=xc(),u=l.ides||[],m=l.initialLoaded??!0,d=u.find(D=>D.id===t&&D.type==="adhdev-daemon"),h=u.some(D=>D.type==="adhdev-daemon"),[f,j]=o.useState("workspace"),[N,p]=o.useState("ide"),x=o.useRef(null),[y,g]=o.useState(null),C=o.useRef("__home__"),[I,v]=o.useState("__home__"),[T,S]=o.useState(!1),k=o.useRef(null);o.useEffect(()=>{!t||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||i(t,{minFreshMs:3e4}).catch(()=>{})},[i,d,t]),o.useEffect(()=>{if(!t||!d||f!=="overview")return;const D=d.machine;(typeof(D==null?void 0:D.cpus)!="number"||typeof(D==null?void 0:D.totalMem)!="number"||typeof(D==null?void 0:D.arch)!="string"||typeof(D==null?void 0:D.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[f,c,d,t]),Sp(t&&f==="overview"?[t]:[],{enabled:f==="overview",intervalMs:Rm});const b=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},B=qx({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:k});o.useEffect(()=>it.onToast(ie=>{l.setToasts(we=>{if(we.some(Te=>Te.message===ie.message&&ie.timestamp-Te.timestamp<3e3))return we;const Ae={id:ie.id,message:ie.message,type:ie.type,timestamp:ie.timestamp,targetKey:ie.targetKey,actions:ie.actions};return[...we.slice(-4),Ae]});const Q=ie.duration||5e3;setTimeout(()=>l.setToasts(we=>we.filter(Ne=>Ne.id!==ie.id)),Q)}),[l]);const L=(d==null?void 0:d.availableProviders)||[],_={};for(const D of L)_[D.type]=D.icon;const H=D=>_[D]||"",F=d?{id:d.id,hostname:qi(d,{fallbackId:d.id}),platform:((je=d.machine)==null?void 0:je.platform)||"unknown",arch:((ae=d.machine)==null?void 0:ae.arch)||"",cpus:((fe=d.machine)==null?void 0:fe.cpus)||0,totalMem:((oe=d.machine)==null?void 0:oe.totalMem)||0,freeMem:(te=d.machine)==null?void 0:te.freeMem,availableMem:(ee=d.machine)==null?void 0:ee.availableMem,loadavg:(X=d.machine)==null?void 0:X.loadavg,uptime:(J=d.machine)==null?void 0:J.uptime,release:((de=d.machine)==null?void 0:de.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,O=u.filter(D=>D.daemonId===t&&D.type!=="adhdev-daemon").filter(D=>!tr(D)&&!gs(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,version:D.version||"",instanceId:D.instanceId||"",status:D.status,workspace:D.workspace||null,terminals:D.terminals||0,aiAgents:Eu(D.aiAgents||(D.agents||[]).map(ie=>({id:ie.name,name:ie.name,status:ie.status,version:ie.version}))),activeChat:D.activeChat||null,chats:D.chats||[],childSessions:D.childSessions||[],cdpConnected:D.cdpConnected||!1,daemonId:t})),M=u.filter(D=>D.daemonId===t&&tr(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,cliName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,mode:D.mode,runtimeKey:D.runtimeKey,runtimeDisplayName:D.runtimeDisplayName,runtimeWorkspaceLabel:D.runtimeWorkspaceLabel,runtimeWriteOwner:D.runtimeWriteOwner||null,runtimeAttachedClients:D.runtimeAttachedClients||[],daemonId:t})),A=u.filter(D=>D.daemonId===t&&gs(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,acpName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,daemonId:t})),U=d?Mt(d,{fallbackId:t}):"",$="workspace",E=n.state,z=E==null?void 0:E.initialMachineTab,Y=E==null?void 0:E.initialWorkspaceCategory,ve=E==null?void 0:E.initialWorkspaceId,re=E==null?void 0:E.initialWorkspacePath,ye=z==="ides"||z==="clis"||z==="acps"?"workspace":z||$,le=z==="ides"?"ide":z==="clis"?"cli":z==="acps"?"acp":Y,be=[...O.map(D=>{var ie,Q,we,Ne,Ae;return{id:`ide:${D.type}:${D.workspace||""}`,label:((ie=D.activeChat)==null?void 0:ie.title)||D.type,kind:"ide",providerType:D.type,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Ae=(Ne=(we=(Q=D.activeChat)==null?void 0:Q.messages)==null?void 0:we.at)==null?void 0:Ne.call(we,-1))==null?void 0:Ae.timestamp)||0}}),...M.map(D=>{var ie,Q,we,Ne,Ae;return{id:`cli:${D.type}:${D.workspace||""}`,label:((ie=D.activeChat)==null?void 0:ie.title)||D.cliName,kind:"cli",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Ae=(Ne=(we=(Q=D.activeChat)==null?void 0:Q.messages)==null?void 0:we.at)==null?void 0:Ne.call(we,-1))==null?void 0:Ae.timestamp)||0}}),...A.map(D=>{var ie,Q,we,Ne,Ae;return{id:`acp:${D.type}:${D.workspace||""}`,label:((ie=D.activeChat)==null?void 0:ie.title)||D.acpName,kind:"acp",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:cs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Ae=(Ne=(we=(Q=D.activeChat)==null?void 0:Q.messages)==null?void 0:we.at)==null?void 0:Ne.call(we,-1))==null?void 0:Ae.timestamp)||0}})].sort((D,ie)=>(ie.lastLaunchedAt||0)-(D.lastLaunchedAt||0)),ge=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(D=>({id:D.id,label:D.title||D.providerName||D.providerType,kind:D.kind,providerType:D.providerType,providerSessionId:D.providerSessionId,subtitle:cs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace,summaryMetadata:D.summaryMetadata,lastLaunchedAt:D.lastLaunchedAt})):be,G=o.useMemo(()=>{var ie;const D=((ie=l.connectionStates)==null?void 0:ie[t||""])||void 0;return u.filter(Q=>Q.daemonId===t&&Q.type!=="adhdev-daemon").flatMap(Q=>Ha(Q,{connectionStates:t&&D?{[t]:D}:void 0,defaultConnectionState:D})).filter(Q=>!(Q.transport==="pty"&&Q.mode==="terminal")).sort((Q,we)=>na(we)-na(Q))},[u,l.connectionStates,t]),ne=o.useCallback(D=>{const ie=Ra(D);ie&&r(zt(ie))},[r]),q=o.useCallback(()=>{x.current&&(S(!0),x.current().finally(()=>{x.current=null,S(!1),g(null)}))},[]),ue=o.useCallback(D=>{if(!F)return;const{options:ie,selectedKey:Q}=ns({machine:F,currentWorkspacePath:D.workspace}),we=async()=>{p(D.kind),j("workspace")};x.current=async()=>{const Ne=ie.find(Ue=>Ue.key===C.current),Ae=(Ne==null?void 0:Ne.workspacePath)??null,Te=(Ne==null?void 0:Ne.workspaceId)??null;if(D.kind==="ide"&&D.providerType){await B.handleLaunchIde(D.providerType,Ae?{workspace:Ae}:void 0);return}if((D.kind==="cli"||D.kind==="acp")&&D.providerType){await B.runLaunchCliCore({cliType:D.providerType,dir:Te?void 0:Ae||"",workspaceId:Te||void 0,model:D.kind==="acp"&&Xi(D.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:D.providerSessionId});return}await we()},C.current=Q,v(Q),g({title:D.kind==="ide"?es("restart-ide",D.label):D.providerSessionId?Ka(D.label):es("start-fresh",D.label),description:D.kind==="ide"?ts("restart-ide"):D.providerSessionId?Oa():ts("start-fresh"),confirmLabel:D.kind==="ide"?Cs("restart-ide"):D.providerSessionId?zr(!0):Cs("start-fresh"),busyLabel:D.kind==="ide"?Ms("restart-ide"):D.providerSessionId?$a(!0):Ms("start-fresh"),workspaceOptions:ie,details:[{label:"Mode",value:D.kind.toUpperCase()},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]})},[B,F]);if(o.useEffect(()=>{j(ye)},[$,ye,t]),o.useEffect(()=>{le&&p(le)},[le,t]),!F)return m?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:b,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const ce=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(St,{size:14})," Workspace"]}),count:O.length+M.length+A.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(is,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xr,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx($d,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Pd,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:b,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[B.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:B.nicknameInput,onChange:D=>B.setNicknameInput(D.target.value),onKeyDown:D=>{D.key==="Enter"&&B.handleSaveNickname(),D.key==="Escape"&&B.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:B.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>B.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{B.setEditingNickname(!0),B.setNicknameInput(F.machineNickname||"")},title:"Click to set nickname",children:U}),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:[F.platform," · ",F.arch]}),s.jsxs("span",{children:[F.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),F.p2p.available&&s.jsxs("span",{children:["P2P ",F.p2p.state==="connected"?"connected":F.p2p.state]}),F.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:F.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ce.map(D=>s.jsxs("button",{onClick:()=>j(D.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===D.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[D.label,D.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===D.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:D.count})]},D.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[f==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(qb,{machineEntry:d,providers:L,recentLaunches:ge,currentConversations:G,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:ue,onOpenConversation:ne}),s.jsx(Qb,{machine:F,machineId:t,providers:L,ideSessions:O,cliSessions:M,acpSessions:A,actions:B,getIcon:H,initialCategory:N,initialWorkspaceId:ve,initialWorkspacePath:re,sendDaemonCommand:a})]}),f==="providers"&&s.jsx(nb,{machineId:t,providers:L,sendDaemonCommand:a}),f==="overview"&&s.jsx(Yx,{machineId:t,machine:F,ideSessions:O,cliSessions:M,acpSessions:A,actions:B,sendDaemonCommand:a}),f==="session-host"&&s.jsx(Vb,{machineId:t,cliSessions:M,sendDaemonCommand:a}),f==="logs"&&s.jsx(Kb,{machineId:t,sendDaemonCommand:a})]})})}),B.launchPick&&F&&s.jsx(Gb,{machine:F,launchPick:B.launchPick,actions:B}),y&&s.jsx(Ja,{title:y.title,description:y.description,details:y.details,workspaceOptions:y.workspaceOptions,selectedWorkspaceKey:I,onWorkspaceChange:D=>{C.current=D,v(D)},confirmLabel:y.confirmLabel,busyLabel:y.busyLabel,busy:T,onConfirm:q,onCancel:()=>{x.current=null,g(null)}}),s.jsx(Cc,{toasts:l.toasts||[],onDismiss:D=>l.setToasts(ie=>ie.filter(Q=>Q.id!==D)),onClickToast:D=>{D.targetKey&&r(zt(D.targetKey))}}),s.jsx("style",{children:`
|
|
76
|
+
`)}function Tb(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Mb(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Ib({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:i,quickFilter:c,searchQuery:l,daemonLoading:u,traceLoading:m,daemonFetchError:d,traceFetchError:h}){const f=ab(n,i),j=cb(e,l),N=ub(t,l),p=mb(f,l),x=fb(a,l),y=Tb(j,c),g=c==="all"?N:[],C=Mb(p,c),I=c==="issues"?[]:x,v=pb({daemonLogs:j,daemonRawLines:N,trace:p,webEvents:x}),M=jb({daemonLogs:y,daemonRawLines:g,trace:C,webEvents:I}),S=Sb(M),k=bb({daemonLoading:u,traceLoading:m,daemonFetchError:d,traceFetchError:h,daemonLogKind:r,daemonLogsCount:j.length,daemonRawLineCount:N.length,traceCount:p.length,webEventCount:x.length});return{filteredDaemonLogs:j,filteredDaemonRawLines:N,filteredTraceEntries:p,filteredWebEvents:x,visibleDaemonLogs:y,visibleDaemonRawLines:g,visibleTraceEntries:C,visibleWebEvents:I,quickFilterCounts:v,diagnosticEvents:M,diagnosticsSummary:S,sourceStates:k}}function Ab(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function vl(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function pa(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 Kn(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 eo(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function Lb({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${pa(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:vl(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:eo(e.source)}),e.category&&e.stage&&s.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&s.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&s.jsxs("span",{children:["ix=",e.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function Rb({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:c,onCopyVisible:l,onToggleAutoRefresh:u,onRefresh:m,onClear:d}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(h=>s.jsx("button",{type:"button",onClick:()=>a(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),s.jsx("input",{value:r,onChange:h=>i(h.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:l,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:u,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:d,className:"machine-btn",children:"Clear"})]})]})}function _b({logLevel:e,traceCategory:t,onLogLevelChange:r,onTraceCategoryChange:n}){return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>s.jsxs("button",{onClick:()=>r(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:rb.map(a=>s.jsx("button",{onClick:()=>n(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function Pb({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:i,daemonFetchError:c,traceFetchError:l}){var d,h;const u=((d=e.latestIssue)==null?void 0:d.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",m=c||l?"danger":i?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Kn(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:n.trim()?`Filtered by “${n.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Kn(u)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[eo(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:vl(e.latestIssue.ts)})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Kn(m)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:c||l?"Needs attention":i?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",Ab(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(f=>s.jsxs("div",{children:[f.label,": ",f.status]},f.id))})]})]})}function Db({patterns:e}){return e.length===0?null:s.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[s.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",eo(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function Eb({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:i,visibleTraceEntries:c,visibleWebEvents:l,quickFilter:u,searchQuery:m}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,timeline:!d.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(d=>s.jsx(Lb,{event:d},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,daemon:!d.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${i.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&i.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&i.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:u==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&i.map((d,h)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:d},`raw-${h}`)),e.daemonLogKind!=="text"&&a.map((d,h)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${pa(d.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(d.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:d.level==="error"?"ERR":d.level==="warn"?"WRN":d.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:d.message})]},`log-${h}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,trace:!d.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&c.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),c.map(d=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${pa(d.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.level.toUpperCase()}),s.jsxs("span",{children:[d.category,".",d.stage]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Ms(d.payload,360)||"No payload"})]},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,web:!d.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[l.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),l.map(d=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.kind}),d.topic&&s.jsxs("span",{children:["topic=",d.topic]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Ms(d.payload,360)||"No payload"})]},d.id))]})]})]})}function $b({machineId:e,sendDaemonCommand:t}){const r=xb({machineId:e,sendDaemonCommand:t}),[n,a]=o.useState("info"),[i,c]=o.useState(""),[l,u]=o.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=o.useRef(null),d=o.useRef(!1),h=o.useMemo(()=>Ib({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:i,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,i,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);o.useEffect(()=>{if(r.autoRefresh&&h.diagnosticEvents.length>0){const N=d.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:N}),d.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const f=o.useCallback(async()=>{var p;const N=hb({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!N.trim()){it.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(N)),it.showToast("Copied visible logs to clipboard.","success")}catch(x){it.showToast(x instanceof Error?x.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),j=o.useCallback(async()=>{var p;const N=Cb({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(N)),it.showToast("Copied diagnostic bundle to clipboard.","success")}catch(x){it.showToast(x instanceof Error?x.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(Rb,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:i,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{j()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>r.setAutoRefresh(N=>!N),onRefresh:r.refresh,onClear:r.clear}),s.jsx(_b,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(Pb,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:i,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(Db,{patterns:h.diagnosticsSummary.repeatedPatterns}),s.jsx(Eb,{streams:r,sectionsOpen:l,setSectionsOpen:u,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:i}),s.jsx("div",{ref:m})]})}function Bb(e){return e.diagnostics?{label:"Managed",toneClass:"bg-green-500/[0.08] text-green-500"}:e.loading||e.refreshing?{label:"Checking…",toneClass:"bg-sky-500/[0.08] text-sky-400"}:e.error?{label:"Diagnostics issue",toneClass:"bg-amber-500/[0.08] text-amber-400"}:{label:"Unavailable",toneClass:"bg-red-500/[0.08] text-red-400"}}function wl(e){const t=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return t?t==="auto_resumed"?"restored after restart":t==="resume_failed"?"restore failed":t==="host_restart_interrupted"?"host restart interrupted":t==="orphan_snapshot"?"snapshot recovered":t.replace(/_/g," "):null}function Kb(e){var a;const t=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=wl((i==null?void 0:i.meta)||void 0),u=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?t.push(i):(c==="stopped"||c==="failed")&&(u||l)?r.push(i):n.push(i)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function Ob(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function On(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 Wn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Hn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function hi(e){if(!e)return"unknown";const t=Date.now()-e,r=Math.max(0,Math.round(t/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function Wb(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Hb(e){switch(e){case"running":return"bg-green-500/[0.08] text-green-500";case"starting":return"bg-sky-500/[0.08] text-sky-400";case"stopping":return"bg-orange-500/[0.08] text-orange-400";case"interrupted":return"bg-amber-500/[0.08] text-amber-400";case"failed":return"bg-red-500/[0.08] text-red-500";default:return"bg-[#ffffff0a] text-text-muted"}}function Fb(e){var r;const t=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const i=`${n.providerType}::${n.workspace}::${a}`;t.set(i,(t.get(i)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function Ub({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),m=kp(e,{enabled:!!e,includeSessions:!0,limit:To,intervalMs:Pm}),d=m.diagnostics,h=m.loading,f=m.applyDiagnostics,j=o.useMemo(()=>Bb({diagnostics:d,loading:h,refreshing:l,error:n}),[d,h,l,n]),N=o.useMemo(()=>new Map(t.map(L=>[L.sessionId||L.id,L])),[t]),p=o.useCallback(async()=>{if(e){u(!0);try{const L=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:To}),_=Wn(L);if(!(_!=null&&_.success))throw new Error((_==null?void 0:_.error)||"Could not load hosted runtime diagnostics");f(_.diagnostics||_.result||null),a("")}catch(L){const _=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";a(_)}finally{u(!1)}}},[f,e,r]);o.useEffect(()=>{!e||d||h||l||p()},[d,h,e,p,l]);const x=o.useCallback(async(L,_)=>{const H=`${L}:${_.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${_.displayName}?
|
|
77
|
+
This will terminate the hosted runtime.`))){c(H);try{const F=await r(e,L,{sessionId:_.sessionId}),O=Wn(F);if(!(O!=null&&O.success))throw new Error((O==null?void 0:O.error)||"Session host action failed");const T=L==="session_host_resume_session"?"resumed":L==="session_host_restart_session"?"restarted":"stopped";it.showToast(`Session host ${T}: ${_.displayName}`,"success"),await p()}catch(F){const O=F instanceof Error?F.message:"Session host action failed";it.showToast(O,"warning"),a(O)}finally{c(F=>F===H?null:F)}}},[e,p,r]),y=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
78
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const _=await r(e,"session_host_prune_duplicate_sessions",{}),H=Wn(_);if(!(H!=null&&H.success))throw new Error((H==null?void 0:H.error)||"Duplicate prune failed");const F=H.result||{},O=Array.isArray(F.prunedSessionIds)?F.prunedSessionIds.length:0,T=typeof F.duplicateGroupCount=="number"?F.duplicateGroupCount:0;it.showToast(`Pruned ${O} duplicate runtime(s) across ${T} group(s)`,"success"),await p()}catch(_){const H=_ instanceof Error?_.message:"Duplicate prune failed";it.showToast(H,"warning"),a(H)}finally{c(_=>_==="session_host_prune_duplicate_sessions"?null:_)}}},[e,p,r]),g=o.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((L,_)=>(_.lastActivityAt||0)-(L.lastActivityAt||0)),[d==null?void 0:d.sessions]),C=o.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:Kb(g),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,g]),I=C.liveRuntimes,v=C.recoverySnapshots,M=C.inactiveRecords,S=o.useMemo(()=>Fb(I),[I]),k=o.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),b=o.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[d==null?void 0:d.recentLogs]),B=(L,_)=>{var z;const H=i===`session_host_resume_session:${L.sessionId}`,F=i===`session_host_restart_session:${L.sessionId}`,O=i===`session_host_stop_session:${L.sessionId}`,T=wl(L.meta),A=N.get(L.sessionId),U=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,$=_==="recovery"?"Recover":"Resume",E=Ob(_);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:L.displayName||(A==null?void 0:A.cliName)||L.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Hb(L.lifecycle)}`,children:L.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:L.workspaceLabel||(A==null?void 0:A.runtimeWorkspaceLabel)||L.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:L.runtimeKey}),L.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",L.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((z=L.writeOwner)==null?void 0:z.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Wb(L.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(Ai,{size:11})," ",U]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",hi(L.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[_==="recovery"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_resume_session",L)},children:H?`${$}ing…`:$}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{x("session_host_restart_session",L)},children:F?"Restarting…":"Restart"}),_==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{x("session_host_stop_session",L)},children:O?"Stopping…":"Stop"})]})]})},L.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(is,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:If()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[S>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${S})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${j.toneClass}`,children:j.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||l,children:[s.jsx(nr,{size:13}),h||l?"Refreshing…":"Refresh"]})]})]}),n&&!d&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(Zs,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:v.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:hi(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Hn(d.hostStartedAt)})]})]}),b&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(Zs,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:b.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Hn(b.timestamp),b.sessionId?` · ${b.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(ja,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:On("live")}),I.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:I.map(L=>B(L,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(is,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:On("recovery")}),v.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:v.map(L=>B(L,"recovery"))})]}),M.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:On("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:M.map(L=>B(L,"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"}),k.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:k.map(L=>{var H;const _=g.find(F=>F.sessionId===L.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:(_==null?void 0:_.displayName)||((H=N.get(L.sessionId))==null?void 0:H.cliName)||L.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[L.action,L.lifecycle?` · ${L.lifecycle}`:"",L.detail?` · ${L.detail}`:"",L.error?` · ${L.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${L.success===!1?"text-red-300":"text-text-secondary"}`,children:Hn(L.timestamp)})]},`${L.sessionId}:${L.timestamp}:${L.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function zb({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function Fn({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 Un({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function Vb({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),d=qs(e,"0.9.46");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(Fn,{icon:s.jsx(Wt,{size:13}),children:"Current Chats"}),s.jsx(Un,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const f=na(h);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(h),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:at(h)}),f>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Qr(f)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ls(h)})]},h.tabKey)})})})]}),u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Fn,{icon:s.jsx(Di,{size:13}),children:"Recent Launches"}),s.jsx(Un,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:f,updatedLabel:j}=sl(h);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(h),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:h.label}),j&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:j})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:f})]},h.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Fn,{icon:s.jsx(Zs,{size:13}),children:"Daemon Update"}),s.jsx(Un,{className:"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:d?"Daemon update required":"Version mismatch detected"}),s.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:d?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(nr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Gb(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function qb({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:i,onCustomPathChange:c,onOpenBrowseDialog:l}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,onChange:u=>{const m=u.target.value;if(i(m),m==="__custom__"&&a){l();return}m!=="__custom__"&&c("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(e.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(u=>s.jsxs("option",{value:u.id,children:[u.id===e.defaultWorkspaceId?"⭐ ":"",en(u.path,u.label)]},u.id)),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),t==="__custom__"&&(a?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:l,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:u=>c(u.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:t==="__custom__"?r?s.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:t===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const Yb={ide:{label:"IDE",plural:"IDEs",accent:"border-blue-500/[0.12]"},cli:{label:"CLI",plural:"CLIs",accent:"border-violet-500/[0.12]"},acp:{label:"ACP Agent",plural:"ACP agents",accent:"border-emerald-500/[0.12]"}};function Nr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function zn({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:m}){const d=Is(),{handleLaunchIde:h,handleStopCli:f,handleRestartIde:j,handleStopIde:N,handleDetectIdes:p,launchingIde:x,launchingAgentType:y,addLog:g}=c,[C,I]=o.useState(null),v=o.useCallback(K=>{K&&d(zt(K))},[d]),M=Yb[e],S=e==="ide",k=e==="acp",b=o.useMemo(()=>n.filter(K=>us(K,e)),[e,n]),B=o.useMemo(()=>new Map(b.map(K=>[K.type,K.displayName||K.type])),[b]),[L,_]=o.useState(""),[H,F]=o.useState(""),[O,T]=o.useState([]),[A,U]=o.useState(""),[$,E]=o.useState(""),[z,Y]=o.useState([]),[ve,re]=o.useState(!1),[ye,le]=o.useState(!1),[be,ge]=o.useState(""),[G,ne]=o.useState(!1),[q,ue]=o.useState(()=>ht()),[ce,je]=o.useState(null),[ae,fe]=o.useState(m?"__custom__":u||t.defaultWorkspaceId||""),[oe,te]=o.useState(m||""),[ee,X]=o.useState([]),[J,de]=o.useState(!1),[D,ie]=o.useState(""),[Q,we]=o.useState([]),[Ne,Ae]=o.useState(!1),[Me,Ue]=o.useState(""),We=o.useRef(null),[Ke,Ge]=o.useState(null),Ze=o.useRef("__home__"),[Je,Ye]=o.useState("__home__"),[mt,pt]=o.useState(!1),dt=o.useRef(0),Ce=ee.filter(K=>!a.some(se=>se.type===K&&bt(se.status)!=="stopped")),He=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!ae&&fe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(m){fe("__custom__"),te(m);return}u&&(fe(u),te(""))},[u,m]),o.useEffect(()=>{S||L&&(b.some(K=>K.type===L)||(_(""),E("")))},[b,S,L]);const Xe=(()=>{if(ae==="__custom__")return oe.trim();if(!ae)return"";const K=(t.workspaces||[]).find(se=>se.id===ae);return(K==null?void 0:K.path)||""})(),ot=o.useCallback(K=>{const se=He.current[K];se&&(clearTimeout(se),delete He.current[K]),X(xe=>xe.includes(K)?xe.filter(Pe=>Pe!==K):xe)},[]),ft=o.useRef(new Set),W=o.useCallback(async K=>{if(l){Ae(!0),Ue("");try{const se=await an(l,r,K);ie(se.path),te(se.path),we(se.directories)}catch(se){Ue(se instanceof Error?se.message:"Could not load folder")}finally{Ae(!1)}}},[r,l]),w=o.useCallback(()=>{if(!l)return;fe("__custom__"),de(!0);const K=a.map(xe=>xe.workspace),se=nn(t.platform,rn(oe.trim(),Xe,m,K,t.defaultWorkspacePath,(t.workspaces||[]).map(xe=>xe.path)));W(se)},[oe,m,W,t.defaultWorkspacePath,t.platform,t.workspaces,a,Xe,l]),R=o.useCallback(K=>{const se=String(K.workspace||"").trim();if(!se)return;const xe=(t.workspaces||[]).find(Pe=>Nr(Pe.path)===Nr(se));if(xe){fe(xe.id),te("");return}fe("__custom__"),te(se)},[t.workspaces]),P=o.useCallback(K=>{const se=String(K.workspace||"").trim();if(!se)return{workspaceId:null,workspacePath:"",useHome:!0};const xe=(t.workspaces||[]).find(Pe=>Nr(Pe.path)===Nr(se));return xe?{workspaceId:xe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:se,useHome:!1}},[t.workspaces]),V=o.useCallback(async K=>{if(!l||!K||e!=="cli"){Y([]),re(!1),le(!1),ge("");return}const se=dt.current+1;dt.current=se,re(!0),ge("");try{const xe=await l(r,"list_saved_sessions",{providerType:K,kind:"cli",limit:30});if(dt.current!==se)return;const Pe=(xe==null?void 0:xe.result)??xe;Y(Array.isArray(Pe==null?void 0:Pe.sessions)?Pe.sessions:[])}catch(xe){if(dt.current!==se)return;Y([]),ge(xe instanceof Error?xe.message:"Could not load saved sessions")}finally{dt.current===se&&(re(!1),le(!0))}},[e,r,l]),Z=o.useMemo(()=>{if(e!=="cli"||!L)return null;const K=B.get(L)||L;return{routeId:r,daemonId:r,providerSessionId:$||void 0,transport:"pty",mode:"chat",agentName:K,agentType:L,status:"idle",title:K,messages:[],ideType:L,workspaceName:Xe,displayPrimary:K,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${L}`}},[e,r,B,Xe,$,L]),me=o.useCallback(K=>{if(e==="ide"||!K){T([]);return}T(xl(r,K))},[e,r]);o.useEffect(()=>{dt.current+=1,E(""),me(L),le(!1),Y([]),ge(""),re(!1)},[e,me,V,L]);const he=o.useMemo(()=>z.find(K=>K.providerSessionId===$)||null,[z,$]);o.useEffect(()=>{if(!$)return;const K=z.find(se=>se.providerSessionId===$);K!=null&&K.canResume||E("")},[z,$]);const Se=o.useCallback((K,se)=>{We.current=se,Ze.current=K.selectedWorkspaceKey||"__home__",Ye(K.selectedWorkspaceKey||"__home__"),Ge(K)},[]),Re=o.useCallback(()=>{We.current&&(pt(!0),We.current().finally(()=>{We.current=null,pt(!1),Ge(null)}))},[]),ke=o.useCallback(K=>{if(!K)return;X(xe=>xe.includes(K)?xe:[...xe,K]);const se=He.current[K];se&&clearTimeout(se),He.current[K]=setTimeout(()=>{X(xe=>xe.includes(K)?xe.filter(Pe=>Pe!==K):xe),delete He.current[K]},2e4)},[]);o.useEffect(()=>{for(const se of a)bt(se.status)!=="stopped"&&(ee.includes(se.type)&&!ft.current.has(se.type)&&(ft.current.add(se.type),g("info",`${B.get(se.type)||se.type} launched`,!0)),ot(se.type));const K=new Set(a.filter(se=>bt(se.status)!=="stopped").map(se=>se.type));ft.current.forEach(se=>{!ee.includes(se)&&!K.has(se)&&ft.current.delete(se)})},[g,ot,a,ee,B]),o.useEffect(()=>()=>{Object.values(He.current).forEach(clearTimeout),He.current={}},[]);const[Ee,$e]=o.useState({}),[Be,Ie]=o.useState(null);o.useEffect(()=>{if(!S||!r||!l)return;(async()=>{try{const se=await l(r,"get_ide_extensions",{}),xe=(se==null?void 0:se.result)||se;xe!=null&&xe.success&&(xe!=null&&xe.ideExtensions)&&$e(xe.ideExtensions)}catch{}})()},[S,r,l]);const qe=K=>S?rt(K.type):e==="cli"?K.cliName:K.acpName,ct=S?t.detectedIdes||[]:[],pe=o.useCallback(async K=>{const se=(K==null?void 0:K.type)||L,xe=(K==null?void 0:K.workspacePath)??Xe;if(S){await h(se,xe?{workspace:xe}:void 0)&&ke(se);return}const Pe=await c.runLaunchCliCore({cliType:se,dir:K!=null&&K.workspaceId?void 0:xe||void 0,workspaceId:(K==null?void 0:K.workspaceId)||void 0,useHome:(K==null?void 0:K.useHome)||!(K!=null&&K.workspaceId)&&!xe,argsStr:(K==null?void 0:K.argsStr)??(H||void 0),model:(K==null?void 0:K.model)??(k&&A||void 0),resumeSessionId:(K==null?void 0:K.resumeSessionId)||!k&&e==="cli"&&se===L&&$||void 0});if(Pe.success||Pe.pending){const Te=(K==null?void 0:K.argsStr)??H;!S&&(Te!=null&&Te.trim())&&(bl(r,se,Te),me(se)),ke(se),Pe.success&&Pe.sessionId&&v(Pe.sessionId)}},[c,h,k,S,H,A,me,ke,r,v,Xe,$,L]),Le=kc(S?"ide":k?"acp":"cli",!S&&!k&&!!$),et=Sc(S?"ide":k?"acp":"cli",!S&&!k&&!!$),nt=()=>{var Te;const K=S?rt(L):B.get(L)||L,se=!S&&!k&&!!$,{options:xe,selectedKey:Pe}=ns({machine:t,currentWorkspaceId:ae&&ae!=="__custom__"?ae:null,currentWorkspacePath:Xe});Se({title:se?Ka(K):es("start-fresh",K),description:se?Oa():ts("start-fresh"),confirmLabel:Le,busyLabel:et,workspaceOptions:xe,selectedWorkspaceKey:Pe,details:[{label:"Mode",value:M.label},{label:"Provider",value:K},...!S&&e==="cli"&&$?[{label:"Resume",value:((Te=z.find(_e=>_e.providerSessionId===$))==null?void 0:Te.title)||$}]:[],...!S&&H.trim()?[{label:"Arguments",value:H.trim()}]:[],...k&&A.trim()?[{label:"Model",value:A.trim()}]:[]]},async()=>{const _e=xe.find(tt=>tt.key===Ze.current);_e!=null&&_e.workspaceId?(fe(_e.workspaceId),te("")):_e!=null&&_e.workspacePath?(fe("__custom__"),te(_e.workspacePath)):(fe(""),te("")),await pe({workspaceId:(_e==null?void 0:_e.workspaceId)??null,workspacePath:(_e==null?void 0:_e.workspacePath)??"",useHome:!(_e!=null&&_e.workspaceId)&&!(_e!=null&&_e.workspacePath)})})},Oe=K=>{S?N(K):f(K.type,K.workspace,K.id)},Mt=o.useCallback(async(K,se,xe=!1)=>{if(K.mode===se){xe&&K.sessionId&&v(K.sessionId);return}if(!l||!K.sessionId){xe&&K.sessionId&&v(K.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:K.sessionId,cliType:K.type,mode:se}),xe&&v(K.sessionId)}catch(Pe){const Te=Uc(Pe);Fc(Pe)?console.warn(Te?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Pe instanceof Error?Pe.message:String(Pe)):console.error("Failed to switch CLI view mode:",Pe)}},[r,v,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${M.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",M.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:S?ct.length>0?ct.map(K=>{const se=a.find(tt=>(tt.type||"").toLowerCase()===(K.type||"").toLowerCase()&&bt(tt.status)!=="stopped"),xe=K.running||!!se,Pe=!!se&&se.cdpConnected,Te=ee.includes(K.type||K.id||""),_e=L===(K.type||"");return s.jsxs("button",{onClick:()=>{if(Pe&&se){const tt=se.sessionId;tt?d(zt(tt),{state:{openRemoteForTabKey:tt}}):d("/dashboard",{state:{openRemoteForTabKey:se.id}});return}Te||_(tt=>tt===(K.type||"")?"":K.type||"")},disabled:!!x||Te,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Pe?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":_e?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:x&&x!==K.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(K.type)}),xe&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Pe?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:K.name||rt(K.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Pe?"text-green-400":Te?"text-orange-400":_e?"text-accent-primary":"text-text-muted"}`,children:Pe?"Open Session":Te?"Starting...":_e?"Configure":"Select"})]})]},K.type)}):s.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",s.jsxs("button",{onClick:p,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[s.jsx(Dd,{size:14})," Scan System"]})]}):b.length>0?b.map(K=>{const se=L===K.type,xe=ee.includes(K.type),Te=!!a.find(_e=>_e.type===K.type&&bt(_e.status)!=="stopped");return s.jsxs("button",{onClick:()=>_(_e=>_e===K.type?"":K.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${se?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:K.icon}),Te&&s.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:K.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${xe?"text-orange-400":se?"text-accent-primary":"text-text-muted"}`,children:xe?"Starting...":se?"Configure":"Select"})]})]},K.type)}):s.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),L&&(S?ct.find(K=>K.type===L):b.find(K=>K.type===L))&&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:S?rt(L):B.get(L)||L})]}),s.jsx(qb,{machine:t,selectedWorkspace:ae,resolvedWorkspacePath:Xe,customPath:oe,canBrowse:!!l,onWorkspaceChange:fe,onCustomPathChange:te,onOpenBrowseDialog:w}),!S&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!k&&e==="cli"&&s.jsx(yl,{busy:!!y||!!x||ee.includes(L),savedSessionsLoading:ve,savedSessionsError:be,selectedSession:he,onRefresh:()=>void V(L),onOpenHistory:()=>{L&&(ne(!0),gl({hasLoadedInitialResults:ye,isLoading:ve})&&V(L))},onClearSelection:()=>E("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[k&&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:A,onChange:K=>U(K.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),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:H,onChange:K=>F(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"}),O.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:O.map(K=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>F(K),title:K,children:K},K))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:nt,disabled:!!y||!!x||ee.includes(L),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:y===L||x===L?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ee.filter(K=>!a.some(se=>se.type===K&&bt(se.status)!=="stopped")).length,")"]}),a.length===0&&Ce.length===0?s.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",M.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ce.map(K=>s.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(K)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:S?rt(K):B.get(K)||K}),s.jsx("div",{className:"text-[11px] text-text-muted",children:y===K?"Launching process...":"Waiting for process and session to register..."})]})]}),s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${K}`)),a.map(K=>{const se=S?K:null,xe=!S&&!k?K:null,Pe=bt(K.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(K.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[qe(K),(se==null?void 0:se.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",se.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[s.jsx("span",{children:K.workspace||"—"}),(xe==null?void 0:xe.mode)&&s.jsx("span",{className:xe.mode==="chat"?"text-violet-400":"text-text-secondary",children:xe.mode==="chat"?"Chat view":"Terminal view"})]}),xe&&(xe.runtimeKey||xe.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[xe.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 ",xe.runtimeKey]}),s.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Te;(Te=navigator.clipboard)==null||Te.writeText(`adhdev attach ${xe.runtimeKey}`),I(xe.runtimeKey||null),window.setTimeout(()=>{I(_e=>_e===xe.runtimeKey?null:_e)},1200)},children:C===xe.runtimeKey?"Copied":"Copy"})]}),xe.runtimeWriteOwner&&s.jsx("span",{style:{color:xe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:xe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Gb(xe.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Pe==="stopped"?"bg-red-500/[0.08] text-red-500":Pe==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Pe}),S&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Te=K.sessionId;if(Te){d(zt(Te),{state:{openRemoteForTabKey:Te}});return}d("/dashboard",{state:{openRemoteForTabKey:K.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:s.jsx(St,{size:13})}),s.jsx("button",{onClick:()=>{const Te=K.workspace||"",{options:_e,selectedKey:tt}=ns({machine:t,currentWorkspacePath:Te});Se({title:es("restart-ide",rt(K.type)),description:ts("restart-ide"),confirmLabel:Cs("restart-ide"),busyLabel:Ts("restart-ide"),workspaceOptions:_e,selectedWorkspaceKey:tt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:rt(K.type)}]},async()=>{const yt=_e.find(Ht=>Ht.key===Ze.current),ut=(yt==null?void 0:yt.workspacePath)??"";if(ut&&ut!==Te){await pe({type:K.type,workspacePath:ut});return}await j(K)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:s.jsx(nr,{size:14})})]}),k&&s.jsx("button",{onClick:()=>{const Te=K.sessionId;Te&&v(Te)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!K.sessionId,children:s.jsx(Wt,{size:14})}),xe&&Pe!=="stopped"&&s.jsxs(s.Fragment,{children:[xe.mode&&s.jsx(Ea,{mode:xe.mode,onChange:Te=>void Mt(xe,Te,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Te=K.sessionId;Te&&v(Te)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!K.sessionId,children:xe.mode==="chat"?s.jsx(Wt,{size:14}):s.jsx(St,{size:13})})]}),Pe==="stopped"?s.jsx("button",{onClick:()=>{const Te=K.workspace||"",_e=S?rt(K.type):qe(K),{options:tt,selectedKey:yt}=ns({machine:t,currentWorkspacePath:Te});Se({title:es("restart-stopped",_e),description:ts("restart-stopped"),confirmLabel:Cs("restart-stopped"),busyLabel:Ts("restart-stopped"),workspaceOptions:tt,selectedWorkspaceKey:yt,details:[{label:"Mode",value:M.label},{label:"Provider",value:_e}]},async()=>{const ut=tt.find(Ht=>Ht.key===Ze.current);await pe({type:K.type,workspaceId:(ut==null?void 0:ut.workspaceId)??null,workspacePath:(ut==null?void 0:ut.workspacePath)??"",useHome:!(ut!=null&&ut.workspaceId)&&!(ut!=null&&ut.workspacePath)})})},disabled:ee.includes(K.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:ee.includes(K.type)?"⏳":s.jsx(ka,{size:14})}):s.jsx("button",{onClick:()=>Oe(K),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:s.jsx(vt,{size:14})})]})]}),se&&se.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:se.aiAgents.map(Te=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Vi(Te.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Te.name," · ",bt(Te.status)]},Te.id))}),se&&(Ee[se.type]||[]).length>0&&l&&s.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[s.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(Ee[se.type]||[]).map(Te=>s.jsxs("button",{disabled:Be===`${se.type}.${Te.type}`,onClick:async()=>{const _e=`${se.type}.${Te.type}`;Ie(_e);try{await l(r,"set_ide_extension",{ideType:se.type,extensionType:Te.type,enabled:!Te.enabled}),$e(tt=>({...tt,[se.type]:(tt[se.type]||[]).map(yt=>yt.type===Te.type?{...yt,enabled:!yt.enabled}:yt)}))}catch(tt){console.error("Extension toggle failed:",tt)}finally{Ie(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Te.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Te.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Te.name,s.jsx("span",{className:"text-[9px] font-normal",children:Te.enabled?"ON":"OFF"})]},Te.type))})]})]},K.id)})]}),J&&l&&s.jsx(cn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:D,directories:Q,busy:Ne,error:Me,confirmLabel:"Use this folder",onClose:()=>de(!1),onNavigate:K=>{W(K)},onConfirm:K=>{te(K),fe("__custom__"),de(!1)}}),Ke&&s.jsx(Ja,{title:Ke.title,description:Ke.description,details:Ke.details,workspaceOptions:Ke.workspaceOptions,selectedWorkspaceKey:Je,onWorkspaceChange:K=>{Ze.current=K,Ye(K)},confirmLabel:Ke.confirmLabel,busyLabel:Ke.busyLabel,busy:mt,onConfirm:Re,onCancel:()=>{We.current=null,Ge(null)}}),G&&Z&&s.jsx(Wa,{activeConv:Z,ides:[],isCreatingChat:!1,isRefreshingHistory:ve,savedSessions:z,isSavedSessionsLoading:ve,isResumingSavedSessionId:ce,savedHistoryFilters:q,onSavedHistoryFiltersChange:ue,onClose:()=>ne(!1),onNewChat:()=>{E(""),ne(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{V(L)},onResumeSavedSession:K=>{if(!K.canResume||ce)return;const se=P(K);E(K.providerSessionId),R(K),je(K.providerSessionId),ne(!1),pe({type:K.providerType,workspaceId:se.workspaceId,workspacePath:se.workspacePath,useHome:se.useHome,resumeSessionId:K.providerSessionId}).finally(()=>{je(xe=>xe===K.providerSessionId?null:xe)})}})]})}const xi=[{id:"ide",label:"IDE",helper:"Open a graphical workspace and attach CDP"},{id:"cli",label:"CLI",helper:"Launch a terminal-first workspace on this machine"},{id:"acp",label:"ACP",helper:"Launch an ACP-backed workspace on this machine"}];function Xb({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:m,initialWorkspacePath:d,sendDaemonCommand:h}){var p;const[f,j]=o.useState(u);o.useEffect(()=>{j(u)},[u]);const N=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:xi.map(x=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${f===x.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>j(x.id),children:[s.jsx("span",{children:x.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${f===x.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:N[x.id]})]},x.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(p=xi.find(x=>x.id===f))==null?void 0:p.helper})]}),f==="ide"&&s.jsx(zn,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d}),f==="cli"&&s.jsx(zn,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d}),f==="acp"&&s.jsx(zn,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d})]})}function Jb({onNicknameSynced:e}={}){var je,ae,fe,oe,te,ee,X,J,de;const{id:t}=ad(),r=Is(),n=ga(),{sendCommand:a}=wt(),i=ir(),c=Kc(),l=hc(),u=l.ides||[],m=l.initialLoaded??!0,d=u.find(D=>D.id===t&&D.type==="adhdev-daemon"),h=u.some(D=>D.type==="adhdev-daemon"),[f,j]=o.useState("workspace"),[N,p]=o.useState("ide"),x=o.useRef(null),[y,g]=o.useState(null),C=o.useRef("__home__"),[I,v]=o.useState("__home__"),[M,S]=o.useState(!1),k=o.useRef(null);o.useEffect(()=>{!t||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||i(t,{minFreshMs:3e4}).catch(()=>{})},[i,d,t]),o.useEffect(()=>{if(!t||!d||f!=="overview")return;const D=d.machine;(typeof(D==null?void 0:D.cpus)!="number"||typeof(D==null?void 0:D.totalMem)!="number"||typeof(D==null?void 0:D.arch)!="string"||typeof(D==null?void 0:D.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[f,c,d,t]),jp(t&&f==="overview"?[t]:[],{enabled:f==="overview",intervalMs:Am});const b=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},B=Vx({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:k});o.useEffect(()=>it.onToast(ie=>{l.setToasts(we=>{if(we.some(Me=>Me.message===ie.message&&ie.timestamp-Me.timestamp<3e3))return we;const Ae={id:ie.id,message:ie.message,type:ie.type,timestamp:ie.timestamp,targetKey:ie.targetKey,actions:ie.actions};return[...we.slice(-4),Ae]});const Q=ie.duration||5e3;setTimeout(()=>l.setToasts(we=>we.filter(Ne=>Ne.id!==ie.id)),Q)}),[l]);const L=(d==null?void 0:d.availableProviders)||[],_={};for(const D of L)_[D.type]=D.icon;const H=D=>_[D]||"",F=d?{id:d.id,hostname:Gi(d,{fallbackId:d.id}),platform:((je=d.machine)==null?void 0:je.platform)||"unknown",arch:((ae=d.machine)==null?void 0:ae.arch)||"",cpus:((fe=d.machine)==null?void 0:fe.cpus)||0,totalMem:((oe=d.machine)==null?void 0:oe.totalMem)||0,freeMem:(te=d.machine)==null?void 0:te.freeMem,availableMem:(ee=d.machine)==null?void 0:ee.availableMem,loadavg:(X=d.machine)==null?void 0:X.loadavg,uptime:(J=d.machine)==null?void 0:J.uptime,release:((de=d.machine)==null?void 0:de.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,O=u.filter(D=>D.daemonId===t&&D.type!=="adhdev-daemon").filter(D=>!tr(D)&&!gs(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,version:D.version||"",instanceId:D.instanceId||"",status:D.status,workspace:D.workspace||null,terminals:D.terminals||0,aiAgents:Du(D.aiAgents||(D.agents||[]).map(ie=>({id:ie.name,name:ie.name,status:ie.status,version:ie.version}))),activeChat:D.activeChat||null,chats:D.chats||[],childSessions:D.childSessions||[],cdpConnected:D.cdpConnected||!1,daemonId:t})),T=u.filter(D=>D.daemonId===t&&tr(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,cliName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,mode:D.mode,runtimeKey:D.runtimeKey,runtimeDisplayName:D.runtimeDisplayName,runtimeWorkspaceLabel:D.runtimeWorkspaceLabel,runtimeWriteOwner:D.runtimeWriteOwner||null,runtimeAttachedClients:D.runtimeAttachedClients||[],daemonId:t})),A=u.filter(D=>D.daemonId===t&&gs(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,acpName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,daemonId:t})),U=d?Tt(d,{fallbackId:t}):"",$="workspace",E=n.state,z=E==null?void 0:E.initialMachineTab,Y=E==null?void 0:E.initialWorkspaceCategory,ve=E==null?void 0:E.initialWorkspaceId,re=E==null?void 0:E.initialWorkspacePath,ye=z==="ides"||z==="clis"||z==="acps"?"workspace":z||$,le=z==="ides"?"ide":z==="clis"?"cli":z==="acps"?"acp":Y,be=[...O.map(D=>{var ie,Q,we,Ne,Ae;return{id:`ide:${D.type}:${D.workspace||""}`,label:((ie=D.activeChat)==null?void 0:ie.title)||D.type,kind:"ide",providerType:D.type,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Ae=(Ne=(we=(Q=D.activeChat)==null?void 0:Q.messages)==null?void 0:we.at)==null?void 0:Ne.call(we,-1))==null?void 0:Ae.timestamp)||0}}),...T.map(D=>{var ie,Q,we,Ne,Ae;return{id:`cli:${D.type}:${D.workspace||""}`,label:((ie=D.activeChat)==null?void 0:ie.title)||D.cliName,kind:"cli",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Ae=(Ne=(we=(Q=D.activeChat)==null?void 0:Q.messages)==null?void 0:we.at)==null?void 0:Ne.call(we,-1))==null?void 0:Ae.timestamp)||0}}),...A.map(D=>{var ie,Q,we,Ne,Ae;return{id:`acp:${D.type}:${D.workspace||""}`,label:((ie=D.activeChat)==null?void 0:ie.title)||D.acpName,kind:"acp",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:cs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Ae=(Ne=(we=(Q=D.activeChat)==null?void 0:Q.messages)==null?void 0:we.at)==null?void 0:Ne.call(we,-1))==null?void 0:Ae.timestamp)||0}})].sort((D,ie)=>(ie.lastLaunchedAt||0)-(D.lastLaunchedAt||0)),ge=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(D=>({id:D.id,label:D.title||D.providerName||D.providerType,kind:D.kind,providerType:D.providerType,providerSessionId:D.providerSessionId,subtitle:cs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace,summaryMetadata:D.summaryMetadata,lastLaunchedAt:D.lastLaunchedAt})):be,G=o.useMemo(()=>{var ie;const D=((ie=l.connectionStates)==null?void 0:ie[t||""])||void 0;return u.filter(Q=>Q.daemonId===t&&Q.type!=="adhdev-daemon").flatMap(Q=>Ha(Q,{connectionStates:t&&D?{[t]:D}:void 0,defaultConnectionState:D})).filter(Q=>!(Q.transport==="pty"&&Q.mode==="terminal")).sort((Q,we)=>na(we)-na(Q))},[u,l.connectionStates,t]),ne=o.useCallback(D=>{const ie=Ra(D);ie&&r(zt(ie))},[r]),q=o.useCallback(()=>{x.current&&(S(!0),x.current().finally(()=>{x.current=null,S(!1),g(null)}))},[]),ue=o.useCallback(D=>{if(!F)return;const{options:ie,selectedKey:Q}=ns({machine:F,currentWorkspacePath:D.workspace}),we=async()=>{p(D.kind),j("workspace")};x.current=async()=>{const Ne=ie.find(Ue=>Ue.key===C.current),Ae=(Ne==null?void 0:Ne.workspacePath)??null,Me=(Ne==null?void 0:Ne.workspaceId)??null;if(D.kind==="ide"&&D.providerType){await B.handleLaunchIde(D.providerType,Ae?{workspace:Ae}:void 0);return}if((D.kind==="cli"||D.kind==="acp")&&D.providerType){await B.runLaunchCliCore({cliType:D.providerType,dir:Me?void 0:Ae||"",workspaceId:Me||void 0,model:D.kind==="acp"&&Yi(D.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:D.providerSessionId});return}await we()},C.current=Q,v(Q),g({title:D.kind==="ide"?es("restart-ide",D.label):D.providerSessionId?Ka(D.label):es("start-fresh",D.label),description:D.kind==="ide"?ts("restart-ide"):D.providerSessionId?Oa():ts("start-fresh"),confirmLabel:D.kind==="ide"?Cs("restart-ide"):D.providerSessionId?zr(!0):Cs("start-fresh"),busyLabel:D.kind==="ide"?Ts("restart-ide"):D.providerSessionId?$a(!0):Ts("start-fresh"),workspaceOptions:ie,details:[{label:"Mode",value:D.kind.toUpperCase()},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]})},[B,F]);if(o.useEffect(()=>{j(ye)},[$,ye,t]),o.useEffect(()=>{le&&p(le)},[le,t]),!F)return m?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:b,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const ce=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(St,{size:14})," Workspace"]}),count:O.length+T.length+A.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(is,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xr,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ed,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_d,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:b,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[B.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:B.nicknameInput,onChange:D=>B.setNicknameInput(D.target.value),onKeyDown:D=>{D.key==="Enter"&&B.handleSaveNickname(),D.key==="Escape"&&B.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:B.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>B.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{B.setEditingNickname(!0),B.setNicknameInput(F.machineNickname||"")},title:"Click to set nickname",children:U}),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:[F.platform," · ",F.arch]}),s.jsxs("span",{children:[F.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),F.p2p.available&&s.jsxs("span",{children:["P2P ",F.p2p.state==="connected"?"connected":F.p2p.state]}),F.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:F.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ce.map(D=>s.jsxs("button",{onClick:()=>j(D.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===D.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[D.label,D.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===D.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:D.count})]},D.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[f==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(Vb,{machineEntry:d,providers:L,recentLaunches:ge,currentConversations:G,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:ue,onOpenConversation:ne}),s.jsx(Xb,{machine:F,machineId:t,providers:L,ideSessions:O,cliSessions:T,acpSessions:A,actions:B,getIcon:H,initialCategory:N,initialWorkspaceId:ve,initialWorkspacePath:re,sendDaemonCommand:a})]}),f==="providers"&&s.jsx(sb,{machineId:t,providers:L,sendDaemonCommand:a}),f==="overview"&&s.jsx(Gx,{machineId:t,machine:F,ideSessions:O,cliSessions:T,acpSessions:A,actions:B,sendDaemonCommand:a}),f==="session-host"&&s.jsx(Ub,{machineId:t,cliSessions:T,sendDaemonCommand:a}),f==="logs"&&s.jsx($b,{machineId:t,sendDaemonCommand:a})]})})}),B.launchPick&&F&&s.jsx(zb,{machine:F,launchPick:B.launchPick,actions:B}),y&&s.jsx(Ja,{title:y.title,description:y.description,details:y.details,workspaceOptions:y.workspaceOptions,selectedWorkspaceKey:I,onWorkspaceChange:D=>{C.current=D,v(D)},confirmLabel:y.confirmLabel,busyLabel:y.busyLabel,busy:M,onConfirm:q,onCancel:()=>{x.current=null,g(null)}}),s.jsx(Nc,{toasts:l.toasts||[],onDismiss:D=>l.setToasts(ie=>ie.filter(Q=>Q.id!==D)),onClickToast:D=>{D.targetKey&&r(zt(D.targetKey))}}),s.jsx("style",{children:`
|
|
79
79
|
@keyframes toast-in {
|
|
80
80
|
from { opacity: 0; transform: translateX(40px); }
|
|
81
81
|
to { opacity: 1; transform: translateX(0); }
|
|
82
82
|
}
|
|
83
|
-
`})]})}function to(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function eg(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=to();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Pt(e,t){return await fetch(eg(e),{credentials:"same-origin",...t})}function kl(){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 tg{constructor(){ze(this,"adapters",new Map);ze(this,"states",new Map);ze(this,"runtimeListeners",new Map);ze(this,"screenshotCallbacks",new Map);ze(this,"statusCallbacks",new Set)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r)}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,i,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:i,rows:c})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const i=await Pt(`${a.pathname}${a.search}`);if(!i.ok){let l=`Runtime snapshot unavailable (${i.status})`;try{const u=await i.json();u!=null&&u.error&&(l=u.error)}catch{}return{success:!1,error:l}}const c=await i.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof c.seq=="number"?c.seq:0,text:typeof c.text=="string"?c.text:"",truncated:!!c.truncated,cols:typeof c.cols=="number"?c.cols:void 0,rows:typeof c.rows=="number"?c.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Bt=new tg;function sg(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=to();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Cr=sg(),gi=3e3,rg=3e4;let Lt=null,ng=0;const Yr=new Map;let Yt=null,Xs=null;function yi(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Ws(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function ag(e){return e==="connected"?"connected":e}async function Dr(e,t,r){const n=Ic(e,r||{}),a=Lt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++ng}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{Yr.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);Yr.set(i,{resolve:m=>{clearTimeout(u),c(m)},reject:m=>{clearTimeout(u),l(m)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function ha(e,t){const r=Lt;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function og(e,t,r){const n=Lt;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 ig{constructor(t){ze(this,"daemonId");ze(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Lt==null?void 0:Lt.readyState)===WebSocket.OPEN}get connectionState(){return(Lt==null?void 0:Lt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Dr(this.daemonId,t,r)}async sendInput(t,r){return Dr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Yt&&(clearInterval(Yt),Yt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Dr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Bt.emitScreenshot(this.daemonId,a)}}catch{}};r(),Yt=setInterval(r,2e3)}stopScreenshots(t){Yt&&(clearInterval(Yt),Yt=null)}}let Ct=null;function cg(e){return(!Ct||Ct.daemonId!==e)&&(Ct=new ig(e)),Ct}function lg({children:e}){const t=o.useRef(Qs()),r=Qs();t.current=r;const{setUserName:n}=os(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((p,x)=>{l(p),Xs==null||Xs(p,x)},[]),m=o.useRef(null),d=o.useRef(),h=o.useRef(gi),f=o.useRef(!0),j=o.useRef(!1),N=o.useRef("initial_connect");return o.useEffect(()=>{f.current=!0,j.current=!1;function p(){var g,C;if(!f.current||((g=m.current)==null?void 0:g.readyState)===WebSocket.OPEN||((C=m.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Cr}...`),Ws("connect_attempt",{url:Cr,reason:N.current,delayMs:h.current});let y;try{y=new WebSocket(Cr)}catch(I){console.error("[Standalone WS] Failed to create WebSocket:",I),x();return}m.current=y,y.onopen=()=>{if(!f.current){y.close();return}u("connected"),h.current=gi,Ws("open",{url:Cr,reason:N.current}),Vt.resubscribeAll({sendData:ha}),console.log("[Standalone WS] Connected")},Lt=y,y.onmessage=I=>{var v,T;try{const S=JSON.parse(I.data);if((S.type==="command_result"||S.type==="error")&&S.requestId){const k=Yr.get(S.requestId);k&&(Yr.delete(S.requestId),S.type==="error"?k.reject(new Error(((v=S.data)==null?void 0:v.message)||"Command failed")):k.resolve(S.data));return}if(S.type==="session_output"){const k=S.sessionId||S.cliId||S.cliType;k&&Bt.emitSessionOutput(k,typeof S.data=="string"?S.data:"",typeof S.seq=="number"?S.seq:void 0);return}if(S.type==="runtime_snapshot"){Bt.emitRuntimeSnapshot(S.sessionId,typeof S.text=="string"?S.text:"",typeof S.seq=="number"?S.seq:0,!!S.truncated,typeof S.cols=="number"?S.cols:void 0,typeof S.rows=="number"?S.rows:void 0);return}if(S.type==="topic_update"){const k=S.update;k&&Vt.publish(k);return}if(S.type==="status"||S.type==="initial_state"){const k=S.data;if(!k)return;const{injectEntries:b,markLoaded:B,getIdes:L}=t.current,_=k.instanceId||"standalone",H=L().find(M=>M.id===_),F=cg(_);Bt.register(_,F),Bt.setState(_,"connected"),u("connected",_),Bt.emitStatus(_,k);const O=Fr(k,{daemonId:_,existingDaemon:H,existingEntries:L()});yi("ws_status",{type:S.type,daemonId:_,sessions:(k.sessions||[]).map(M=>({id:M.id,parentId:M.parentId,providerType:M.providerType,kind:M.kind,transport:M.transport,unread:M.unread,inboxBucket:M.inboxBucket,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,title:M.title})),recentLaunches:(k.recentLaunches||[]).map(M=>({id:M.id,providerType:M.providerType,kind:M.kind,workspace:M.workspace,lastLaunchedAt:M.lastLaunchedAt}))}),yi("entries",{daemonId:_,entries:O.filter(M=>M.type!=="adhdev-daemon").map(M=>({id:M.id,type:M.type,unread:M.unread,inboxBucket:M.inboxBucket,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,sessionId:M.sessionId}))}),O.length>0&&b(O,{authoritativeDaemonIds:[_]}),B(),c.current!==_&&((T=i.current)==null||T.call(i),c.current=_,i.current=Vt.subscribe({sendData:ha},_,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${_}`,params:{includeSessions:!0}},M=>{if(M.topic!=="daemon.metadata")return;const A=t.current.getIdes(),U=A.find(E=>E.id===_),$=Fr(M.status,{daemonId:_,existingDaemon:U,existingEntries:A,timestamp:M.timestamp});$.length>0&&t.current.injectEntries($,{authoritativeDaemonIds:[_]}),M.userName&&a.current&&a.current(M.userName)}))}}catch(S){console.error("[Standalone WS] Parse error:",S)}},y.onclose=I=>{f.current&&(Ct==null||Ct.stopScreenshots(),Ct&&Bt.setState(Ct.daemonId,"disconnected"),u("disconnected"),m.current=null,N.current=`close:${I.code}${I.wasClean?":clean":":unclean"}`,Ws("close",{code:I.code,reason:I.reason||"",wasClean:I.wasClean}),x())},y.onerror=I=>{j.current||!f.current||(N.current="error",Ws("error",{message:I instanceof Event?"event":String(I),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",I))}}function x(){if(!f.current)return;clearTimeout(d.current);const y=h.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),Ws("schedule_reconnect",{reason:N.current,delayMs:y}),d.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,rg),p()},y)}return p(),()=>{var y;f.current=!1,j.current=!0,(y=i.current)==null||y.call(i),i.current=null,c.current=null,clearTimeout(d.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Lt=null),Ct&&(Ct.stopScreenshots(),Bt.unregister(Ct.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function dg({children:e}){const[t,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Xs=(c,l)=>{r(c),l&&a(l)},()=>{Xs=null}),[]);const i=o.useMemo(()=>{const c=t==="connected",l=ag(t),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:t,isConnected:c,connectionStates:u}},[t,n]);return s.jsx(Sd,{connectionOverrides:i,children:s.jsx(lg,{children:e})})}const Sl="adhdev_standalone_font_preferences",as={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},un=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],rr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],ug=new Set(un.map(e=>e.id)),mg=new Set(rr.map(e=>e.id));function Et(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Er("chat",t.chat),code:Er("code",t.code),terminal:Er("terminal",t.terminal)}}function Er(e,t){const r=as[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?ug:mg).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function $r(e,t){var a;const r=Er(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?un:rr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function fg(e){const t=Et(e),r=$r("chat",t.chat),n=$r("code",t.code),a=$r("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Jt(e,t=document.documentElement){const r=Et(e),n=fg(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function xa(e){const t=Et(e);try{localStorage.setItem(Sl,JSON.stringify(t))}catch{}return t}function pg(){try{const e=localStorage.getItem(Sl);if(e)return Et(JSON.parse(e))}catch{}return as}function hg(){return Jt(pg())}function Hs(e,t){var n;const r=e==="chat"?un:rr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const xg=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Ai,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(is,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(Xr,{}),label:"Settings"}];function bg({children:e}){const t=Is(),r=ga(),n=o.useMemo(()=>xg.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(Ri,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(_i,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Xf,{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.44"]}),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 gg=[{icon:s.jsx(is,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Wt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Pi,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(St,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(er,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Ri,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],yg=[{icon:s.jsx(Kd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Ai,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Jr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(_d,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Li,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Dd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],vg=[{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 wg(){return s.jsxs(_c,{icon:s.jsx(_i,{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.44"]}),children:[s.jsx(kt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),s.jsx(kt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:gg.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(kt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Ac.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Rc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Lc.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(kt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:yg.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(kt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:vg.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(Dc,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(Yd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Vn(e,t,r){return{...e,[t]:r}}function Gn({surface:e,title:t,description:r,value:n,options:a,onChange:i}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>i({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:$r(e,n)})]})]})]})}function jg({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:u}){const m=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Gn,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:un,onChange:d=>i(Vn(e,"chat",d))}),s.jsx(Gn,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:rr,onChange:d=>i(Vn(e,"code",d))}),s.jsx(Gn,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:rr,onChange:d=>i(Vn(e,"terminal",d))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Hs("chat",e.chat.preset)," · Code: ",Hs("code",e.code.preset)," · Terminal: ",Hs("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Hs("chat",as.chat.preset)," / ",Hs("code",as.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:c,disabled:r||!m,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:l,disabled:r||!m,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick:u,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function kg(){const{ides:e}=os(),t=e.find(G=>G.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=wt(),{userName:a}=os(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[m,d]=o.useState(null),[h,f]=o.useState(as),[j,N]=o.useState(!1),[p,x]=o.useState(""),[y,g]=o.useState(""),[C,I]=o.useState("127.0.0.1"),[v,T]=o.useState(""),[S,k]=o.useState(""),[b,B]=o.useState(""),[L,_]=o.useState(""),[H,F]=o.useState(""),[O,M]=o.useState(!1),A=async()=>{const ne=await(await Pt("/auth/session")).json();u(ne)},U=async()=>{const ne=await(await Pt("/api/v1/standalone/preferences")).json();d(ne),I(ne.standaloneBindHost);const q=Et(ne.standaloneFontPreferences);f(q),Jt(q),xa(q)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([A(),U()]).catch(G=>{_(G instanceof Error?G.message:String(G))})},[]),o.useEffect(()=>{Jt(h)},[h]);const $=G=>{const ne=G.target.value.trim();t!=null&&t.id&&ne!==a&&n(t.id,"set_user_name",{userName:ne}).catch(console.error)},[E,z]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),Y=G=>{z(G);try{localStorage.setItem("adhdev_sound",G?"1":"0")}catch{}},ve=async()=>{x(""),g(""),N(!0);try{const G=Et(h),ne=await Pt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:G})}),q=await ne.json();if(!ne.ok)throw new Error((q==null?void 0:q.error)||"Failed to save standalone font preferences");const ue=Et(q.standaloneFontPreferences);d(q),f(ue),Jt(ue),xa(ue),g("Standalone chat fonts saved for this self-hosted dashboard.")}catch(G){x(G instanceof Error?G.message:String(G))}finally{N(!1)}},re=()=>{const G=Et(m==null?void 0:m.standaloneFontPreferences);x(""),g(""),f(G),Jt(G)},ye=()=>{x(""),g(""),f(as),Jt(as)},le=async()=>{_(""),F(""),M(!0);try{const G=await Pt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),ne=await G.json();if(!G.ok)throw new Error((ne==null?void 0:ne.error)||"Failed to save standalone network preference");d(ne),I(ne.standaloneBindHost),F(ne.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(G){_(G instanceof Error?G.message:String(G))}finally{M(!1)}},be=async()=>{if(_(""),F(""),S.trim().length<4){_("Password must be at least 4 characters.");return}if(S!==b){_("New password and confirmation do not match.");return}M(!0);try{const G=await Pt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:S})}),ne=await G.json();if(!G.ok)throw new Error((ne==null?void 0:ne.error)||"Failed to save password");u(ne),await U(),T(""),k(""),B(""),F(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),kl()}catch(G){_(G instanceof Error?G.message:String(G))}finally{M(!1)}},ge=async()=>{_(""),F(""),M(!0);try{const G=await Pt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),ne=await G.json();if(!G.ok)throw new Error((ne==null?void 0:ne.error)||"Failed to clear password");u(ne),await U(),T(""),k(""),B(""),F("Standalone password disabled.")}catch(G){_(G instanceof Error?G.message:String(G))}finally{M(!1)}};return s.jsxs(_c,{icon:s.jsx(Xr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(gr,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&s.jsx(gr,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(kt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.44"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(kt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="127.0.0.1",onChange:()=>I("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:C==="0.0.0.0",onChange:()=>I("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:()=>{le()},disabled:O,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:O?"Saving…":"Save default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(kt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),L&&s.jsx(gr,{variant:"error",children:L}),H&&s.jsx(gr,{variant:"success",children:H}),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:v,onChange:G=>T(G.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:S,onChange:G=>k(G.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:b,onChange:G=>B(G.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{be()},disabled:O,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:O?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ge()},disabled:O,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),s.jsx(kt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(G=>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 ${G.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:G.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:G.type})]},G.type))})}),s.jsx(kt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(ap,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(kt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(lp,{})]}),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(bp,{})]}),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(jg,{value:h,savedValue:Et(m==null?void 0:m.standaloneFontPreferences),saving:j,error:p,notice:y,onChange:f,onSave:()=>{ve()},onResetToSaved:re,onResetToDefaults:ye})]}),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(vp,{})]})]})}),s.jsx(kt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(sp,{}),s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(qd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:Y})]})}),s.jsx(kt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Rd,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:i,onChange:G=>c(G.target.value),onBlur:$,onKeyDown:G=>{G.key==="Enter"&&G.currentTarget.blur()}})]})})})]})}qf();hp();hg();const Sg=Mi({baseUrl:"",getToken:to});function Ng({children:e}){const[t,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[m,d]=o.useState(!1),h=async()=>{a(!0),u("");try{const N=await(await Pt("/auth/session")).json();r(N)}catch(j){u(j instanceof Error?j.message:String(j))}finally{a(!1)}};o.useEffect(()=>{h()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let j=!1;return(async()=>{try{const N=await Pt("/api/v1/standalone/preferences");if(!N.ok)return;const p=await N.json();if(j)return;const x=Et(p.standaloneFontPreferences);Jt(x),xa(x)}catch{}})(),()=>{j=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const f=async j=>{j.preventDefault(),d(!0),u("");try{const N=await Pt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),p=await N.json();if(!N.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),kl()}catch(N){u(N instanceof Error?N.message:String(N))}finally{d(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:f,children:[s.jsx("input",{type:"password",value:i,onChange:j=>c(j.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:m||!i,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:m?"Signing in…":"Unlock dashboard"})]}):s.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&s.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function vi(){const{ides:e,initialLoaded:t}=os();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx(Xn,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Xn,{to:"/dashboard",replace:!0})}function Cg(){const e=o.useMemo(()=>({sendCommand:Dr,sendData:ha,sendPtyInput:og}),[]);return s.jsx(id,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Md,{client:Sg,children:s.jsx(Ng,{children:s.jsx(dg,{children:s.jsx(Id,{value:e,children:s.jsx(bg,{children:s.jsxs(cd,{children:[s.jsx(Gt,{path:"/dashboard",element:s.jsx(Gx,{})}),s.jsx(Gt,{path:"/machine",element:s.jsx(vi,{})}),s.jsx(Gt,{path:"/machines/:id",element:s.jsx(Zb,{})}),s.jsx(Gt,{path:"/machines",element:s.jsx(vi,{})}),s.jsx(Gt,{path:"/about",element:s.jsx(wg,{})}),s.jsx(Gt,{path:"/settings",element:s.jsx(kg,{})}),s.jsx(Gt,{path:"*",element:s.jsx(Xn,{to:"/dashboard",replace:!0})})]})})})})})})})}ff({connectionManager:Bt});ld(document.getElementById("root")).render(s.jsx(Cg,{}));
|
|
83
|
+
`})]})}function to(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Qb(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=to();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Pt(e,t){return await fetch(Qb(e),{credentials:"same-origin",...t})}function jl(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class Zb{constructor(){ze(this,"adapters",new Map);ze(this,"states",new Map);ze(this,"runtimeListeners",new Map);ze(this,"screenshotCallbacks",new Map);ze(this,"statusCallbacks",new Set)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r)}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,i,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:i,rows:c})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const i=await Pt(`${a.pathname}${a.search}`);if(!i.ok){let l=`Runtime snapshot unavailable (${i.status})`;try{const u=await i.json();u!=null&&u.error&&(l=u.error)}catch{}return{success:!1,error:l}}const c=await i.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof c.seq=="number"?c.seq:0,text:typeof c.text=="string"?c.text:"",truncated:!!c.truncated,cols:typeof c.cols=="number"?c.cols:void 0,rows:typeof c.rows=="number"?c.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Bt=new Zb;function eg(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=to();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Cr=eg(),bi=3e3,tg=3e4;let Lt=null,sg=0;const Yr=new Map;let Yt=null,Xs=null;function gi(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Ws(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function rg(e){return e==="connected"?"connected":e}async function Dr(e,t,r){const n=Mc(e,r||{}),a=Lt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++sg}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{Yr.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);Yr.set(i,{resolve:m=>{clearTimeout(u),c(m)},reject:m=>{clearTimeout(u),l(m)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function ha(e,t){const r=Lt;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function ng(e,t,r){const n=Lt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Mc(e,{sessionId:t,targetSessionId:t,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class ag{constructor(t){ze(this,"daemonId");ze(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Lt==null?void 0:Lt.readyState)===WebSocket.OPEN}get connectionState(){return(Lt==null?void 0:Lt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Dr(this.daemonId,t,r)}async sendInput(t,r){return Dr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Yt&&(clearInterval(Yt),Yt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Dr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Bt.emitScreenshot(this.daemonId,a)}}catch{}};r(),Yt=setInterval(r,2e3)}stopScreenshots(t){Yt&&(clearInterval(Yt),Yt=null)}}let Ct=null;function og(e){return(!Ct||Ct.daemonId!==e)&&(Ct=new ag(e)),Ct}function ig({children:e}){const t=o.useRef(Qs()),r=Qs();t.current=r;const{setUserName:n}=os(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((p,x)=>{l(p),Xs==null||Xs(p,x)},[]),m=o.useRef(null),d=o.useRef(),h=o.useRef(bi),f=o.useRef(!0),j=o.useRef(!1),N=o.useRef("initial_connect");return o.useEffect(()=>{f.current=!0,j.current=!1;function p(){var g,C;if(!f.current||((g=m.current)==null?void 0:g.readyState)===WebSocket.OPEN||((C=m.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Cr}...`),Ws("connect_attempt",{url:Cr,reason:N.current,delayMs:h.current});let y;try{y=new WebSocket(Cr)}catch(I){console.error("[Standalone WS] Failed to create WebSocket:",I),x();return}m.current=y,y.onopen=()=>{if(!f.current){y.close();return}u("connected"),h.current=bi,Ws("open",{url:Cr,reason:N.current}),Vt.resubscribeAll({sendData:ha}),console.log("[Standalone WS] Connected")},Lt=y,y.onmessage=I=>{var v,M;try{const S=JSON.parse(I.data);if((S.type==="command_result"||S.type==="error")&&S.requestId){const k=Yr.get(S.requestId);k&&(Yr.delete(S.requestId),S.type==="error"?k.reject(new Error(((v=S.data)==null?void 0:v.message)||"Command failed")):k.resolve(S.data));return}if(S.type==="session_output"){const k=S.sessionId||S.cliId||S.cliType;k&&Bt.emitSessionOutput(k,typeof S.data=="string"?S.data:"",typeof S.seq=="number"?S.seq:void 0);return}if(S.type==="runtime_snapshot"){Bt.emitRuntimeSnapshot(S.sessionId,typeof S.text=="string"?S.text:"",typeof S.seq=="number"?S.seq:0,!!S.truncated,typeof S.cols=="number"?S.cols:void 0,typeof S.rows=="number"?S.rows:void 0);return}if(S.type==="topic_update"){const k=S.update;k&&Vt.publish(k);return}if(S.type==="status"||S.type==="initial_state"){const k=S.data;if(!k)return;const{injectEntries:b,markLoaded:B,getIdes:L}=t.current,_=k.instanceId||"standalone",H=L().find(T=>T.id===_),F=og(_);Bt.register(_,F),Bt.setState(_,"connected"),u("connected",_),Bt.emitStatus(_,k);const O=Fr(k,{daemonId:_,existingDaemon:H,existingEntries:L()});gi("ws_status",{type:S.type,daemonId:_,sessions:(k.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:(k.recentLaunches||[]).map(T=>({id:T.id,providerType:T.providerType,kind:T.kind,workspace:T.workspace,lastLaunchedAt:T.lastLaunchedAt}))}),gi("entries",{daemonId:_,entries:O.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}))}),O.length>0&&b(O,{authoritativeDaemonIds:[_]}),B(),c.current!==_&&((M=i.current)==null||M.call(i),c.current=_,i.current=Vt.subscribe({sendData:ha},_,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${_}`,params:{includeSessions:!0}},T=>{if(T.topic!=="daemon.metadata")return;const A=t.current.getIdes(),U=A.find(E=>E.id===_),$=Fr(T.status,{daemonId:_,existingDaemon:U,existingEntries:A,timestamp:T.timestamp});$.length>0&&t.current.injectEntries($,{authoritativeDaemonIds:[_]}),T.userName&&a.current&&a.current(T.userName)}))}}catch(S){console.error("[Standalone WS] Parse error:",S)}},y.onclose=I=>{f.current&&(Ct==null||Ct.stopScreenshots(),Ct&&Bt.setState(Ct.daemonId,"disconnected"),u("disconnected"),m.current=null,N.current=`close:${I.code}${I.wasClean?":clean":":unclean"}`,Ws("close",{code:I.code,reason:I.reason||"",wasClean:I.wasClean}),x())},y.onerror=I=>{j.current||!f.current||(N.current="error",Ws("error",{message:I instanceof Event?"event":String(I),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",I))}}function x(){if(!f.current)return;clearTimeout(d.current);const y=h.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),Ws("schedule_reconnect",{reason:N.current,delayMs:y}),d.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,tg),p()},y)}return p(),()=>{var y;f.current=!1,j.current=!0,(y=i.current)==null||y.call(i),i.current=null,c.current=null,clearTimeout(d.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Lt=null),Ct&&(Ct.stopScreenshots(),Bt.unregister(Ct.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function cg({children:e}){const[t,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Xs=(c,l)=>{r(c),l&&a(l)},()=>{Xs=null}),[]);const i=o.useMemo(()=>{const c=t==="connected",l=rg(t),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:t,isConnected:c,connectionStates:u}},[t,n]);return s.jsx(kd,{connectionOverrides:i,children:s.jsx(ig,{children:e})})}const kl="adhdev_standalone_font_preferences",as={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},un=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],rr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],lg=new Set(un.map(e=>e.id)),dg=new Set(rr.map(e=>e.id));function Et(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Er("chat",t.chat),code:Er("code",t.code),terminal:Er("terminal",t.terminal)}}function Er(e,t){const r=as[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?lg:dg).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function $r(e,t){var a;const r=Er(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?un:rr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function ug(e){const t=Et(e),r=$r("chat",t.chat),n=$r("code",t.code),a=$r("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Jt(e,t=document.documentElement){const r=Et(e),n=ug(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function xa(e){const t=Et(e);try{localStorage.setItem(kl,JSON.stringify(t))}catch{}return t}function mg(){try{const e=localStorage.getItem(kl);if(e)return Et(JSON.parse(e))}catch{}return as}function fg(){return Jt(mg())}function Hs(e,t){var n;const r=e==="chat"?un:rr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const pg=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Ii,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(is,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(Xr,{}),label:"Settings"}];function hg({children:e}){const t=Is(),r=ga(),n=o.useMemo(()=>pg.map(i=>({...i,active:r.pathname.startsWith(i.path),onSelect:()=>t(i.path)})),[r.pathname,t]),a=o.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Li,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Ri,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(qf,{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.46"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:i?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const xg=[{icon:s.jsx(is,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Wt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(_i,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(St,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(er,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Li,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],bg=[{icon:s.jsx(Bd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Ii,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Jr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Rd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Ai,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Pd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],gg=[{feature:"Agent chat relay",selfhost:!0,cloud:!0},{feature:"Live IDE screenshots",selfhost:!0,cloud:!0},{feature:"Remote IDE control",selfhost:!0,cloud:!0},{feature:"Multi-IDE monitoring",selfhost:!0,cloud:!0},{feature:"Extension and CLI agents",selfhost:!0,cloud:!0},{feature:"Access from any network",selfhost:!1,cloud:!0},{feature:"WebRTC P2P streaming",selfhost:!1,cloud:!0},{feature:"Mobile push notifications",selfhost:!1,cloud:!0},{feature:"REST API and webhooks",selfhost:!1,cloud:!0},{feature:"Team collaboration",selfhost:!1,cloud:!0},{feature:"Multi-machine burrows",selfhost:!1,cloud:!0},{feature:"SSO, RBAC, audit logs",selfhost:!1,cloud:!0}];function yg(){return s.jsxs(Rc,{icon:s.jsx(Ri,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.46"]}),children:[s.jsx(kt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),s.jsx(kt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:xg.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(kt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Ic.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Lc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Ac.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(kt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:bg.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(kt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:gg.map((e,t)=>s.jsxs("tr",{className:t%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),s.jsx(Pc,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(qd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Vn(e,t,r){return{...e,[t]:r}}function Gn({surface:e,title:t,description:r,value:n,options:a,onChange:i}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>i({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:$r(e,n)})]})]})]})}function vg({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:u}){const m=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Gn,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:un,onChange:d=>i(Vn(e,"chat",d))}),s.jsx(Gn,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:rr,onChange:d=>i(Vn(e,"code",d))}),s.jsx(Gn,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:rr,onChange:d=>i(Vn(e,"terminal",d))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Hs("chat",e.chat.preset)," · Code: ",Hs("code",e.code.preset)," · Terminal: ",Hs("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Hs("chat",as.chat.preset)," / ",Hs("code",as.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:c,disabled:r||!m,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:l,disabled:r||!m,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick:u,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function wg(){const{ides:e}=os(),t=e.find(G=>G.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=wt(),{userName:a}=os(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[m,d]=o.useState(null),[h,f]=o.useState(as),[j,N]=o.useState(!1),[p,x]=o.useState(""),[y,g]=o.useState(""),[C,I]=o.useState("127.0.0.1"),[v,M]=o.useState(""),[S,k]=o.useState(""),[b,B]=o.useState(""),[L,_]=o.useState(""),[H,F]=o.useState(""),[O,T]=o.useState(!1),A=async()=>{const ne=await(await Pt("/auth/session")).json();u(ne)},U=async()=>{const ne=await(await Pt("/api/v1/standalone/preferences")).json();d(ne),I(ne.standaloneBindHost);const q=Et(ne.standaloneFontPreferences);f(q),Jt(q),xa(q)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([A(),U()]).catch(G=>{_(G instanceof Error?G.message:String(G))})},[]),o.useEffect(()=>{Jt(h)},[h]);const $=G=>{const ne=G.target.value.trim();t!=null&&t.id&&ne!==a&&n(t.id,"set_user_name",{userName:ne}).catch(console.error)},[E,z]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),Y=G=>{z(G);try{localStorage.setItem("adhdev_sound",G?"1":"0")}catch{}},ve=async()=>{x(""),g(""),N(!0);try{const G=Et(h),ne=await Pt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:G})}),q=await ne.json();if(!ne.ok)throw new Error((q==null?void 0:q.error)||"Failed to save standalone font preferences");const ue=Et(q.standaloneFontPreferences);d(q),f(ue),Jt(ue),xa(ue),g("Standalone chat fonts saved for this self-hosted dashboard.")}catch(G){x(G instanceof Error?G.message:String(G))}finally{N(!1)}},re=()=>{const G=Et(m==null?void 0:m.standaloneFontPreferences);x(""),g(""),f(G),Jt(G)},ye=()=>{x(""),g(""),f(as),Jt(as)},le=async()=>{_(""),F(""),T(!0);try{const G=await Pt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),ne=await G.json();if(!G.ok)throw new Error((ne==null?void 0:ne.error)||"Failed to save standalone network preference");d(ne),I(ne.standaloneBindHost),F(ne.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(G){_(G instanceof Error?G.message:String(G))}finally{T(!1)}},be=async()=>{if(_(""),F(""),S.trim().length<4){_("Password must be at least 4 characters.");return}if(S!==b){_("New password and confirmation do not match.");return}T(!0);try{const G=await Pt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:S})}),ne=await G.json();if(!G.ok)throw new Error((ne==null?void 0:ne.error)||"Failed to save password");u(ne),await U(),M(""),k(""),B(""),F(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),jl()}catch(G){_(G instanceof Error?G.message:String(G))}finally{T(!1)}},ge=async()=>{_(""),F(""),T(!0);try{const G=await Pt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),ne=await G.json();if(!G.ok)throw new Error((ne==null?void 0:ne.error)||"Failed to clear password");u(ne),await U(),M(""),k(""),B(""),F("Standalone password disabled.")}catch(G){_(G instanceof Error?G.message:String(G))}finally{T(!1)}};return s.jsxs(Rc,{icon:s.jsx(Xr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(gr,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&s.jsx(gr,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(kt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.46"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(kt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="127.0.0.1",onChange:()=>I("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:C==="0.0.0.0",onChange:()=>I("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:()=>{le()},disabled:O,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:O?"Saving…":"Save default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(kt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),L&&s.jsx(gr,{variant:"error",children:L}),H&&s.jsx(gr,{variant:"success",children:H}),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:v,onChange:G=>M(G.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:S,onChange:G=>k(G.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:b,onChange:G=>B(G.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{be()},disabled:O,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:O?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ge()},disabled:O,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),s.jsx(kt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(G=>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 ${G.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:G.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:G.type})]},G.type))})}),s.jsx(kt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(rp,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(kt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(ip,{})]}),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(hp,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),s.jsx(vg,{value:h,savedValue:Et(m==null?void 0:m.standaloneFontPreferences),saving:j,error:p,notice:y,onChange:f,onSave:()=>{ve()},onResetToSaved:re,onResetToDefaults:ye})]}),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(gp,{})]})]})}),s.jsx(kt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(ep,{}),s.jsx(Xt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Gd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:Y})]})}),s.jsx(kt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Ld,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:i,onChange:G=>c(G.target.value),onBlur:$,onKeyDown:G=>{G.key==="Enter"&&G.currentTarget.blur()}})]})})})]})}Vf();fp();fg();const jg=Ci({baseUrl:"",getToken:to});function kg({children:e}){const[t,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[m,d]=o.useState(!1),h=async()=>{a(!0),u("");try{const N=await(await Pt("/auth/session")).json();r(N)}catch(j){u(j instanceof Error?j.message:String(j))}finally{a(!1)}};o.useEffect(()=>{h()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let j=!1;return(async()=>{try{const N=await Pt("/api/v1/standalone/preferences");if(!N.ok)return;const p=await N.json();if(j)return;const x=Et(p.standaloneFontPreferences);Jt(x),xa(x)}catch{}})(),()=>{j=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const f=async j=>{j.preventDefault(),d(!0),u("");try{const N=await Pt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),p=await N.json();if(!N.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),jl()}catch(N){u(N instanceof Error?N.message:String(N))}finally{d(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:f,children:[s.jsx("input",{type:"password",value:i,onChange:j=>c(j.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:m||!i,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:m?"Signing in…":"Unlock dashboard"})]}):s.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&s.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function yi(){const{ides:e,initialLoaded:t}=os();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx(Xn,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Xn,{to:"/dashboard",replace:!0})}function Sg(){const e=o.useMemo(()=>({sendCommand:Dr,sendData:ha,sendPtyInput:ng}),[]);return s.jsx(od,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Cd,{client:jg,children:s.jsx(kg,{children:s.jsx(cg,{children:s.jsx(Md,{value:e,children:s.jsx(hg,{children:s.jsxs(id,{children:[s.jsx(Gt,{path:"/dashboard",element:s.jsx(zx,{})}),s.jsx(Gt,{path:"/machine",element:s.jsx(yi,{})}),s.jsx(Gt,{path:"/machines/:id",element:s.jsx(Jb,{})}),s.jsx(Gt,{path:"/machines",element:s.jsx(yi,{})}),s.jsx(Gt,{path:"/about",element:s.jsx(yg,{})}),s.jsx(Gt,{path:"/settings",element:s.jsx(wg,{})}),s.jsx(Gt,{path:"*",element:s.jsx(Xn,{to:"/dashboard",replace:!0})})]})})})})})})})}uf({connectionManager:Bt});cd(document.getElementById("root")).render(s.jsx(Sg,{}));
|