@adhdev/daemon-standalone 0.9.82-rc.4 → 0.9.82-rc.6

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.
@@ -1,98 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-DCVDkSIp.js","assets/vendor-piMzuE8Y.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
- var hu=Object.defineProperty;var xu=(e,t,r)=>t in e?hu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Xe=(e,t,r)=>xu(e,typeof t!="symbol"?t+"":t,r);import{r as i,j as s,M as to,a as bu,b as gu,c as yu,R as wt,d as xr,t as vu,e as wu,u as Ws,D as ju,f as Aa,g as La,i as ku,h as Su,C as Nu,B as Cu,k as Iu,l as Tu,H as Zo,P as ei,m as so,n as Mu,o as Au,p as Lu,q as Ru,s as qt,N as Ra,v as _u}from"./vendor-piMzuE8Y.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 o of a)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(a){if(a.ep)return;a.ep=!0;const o=r(a);fetch(a.href,o)}})();function Pu(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(o=>!n.interactionId||o.interactionId===n.interactionId).filter(o=>!n.topic||o.topic===n.topic).filter(o=>!n.kind||o.kind===n.kind).slice(-a).map(o=>({...o,payload:o.payload?{...o.payload}:{}}))},clear(){r.splice(0,r.length)}}}const _s=Pu();function ti(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 Du(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function si(e){return Array.isArray(e)?[...e]:[]}function Tc(e,t){if(!e)return t??null;const r=Object.prototype.hasOwnProperty.call(e,"messages"),n=Object.prototype.hasOwnProperty.call(e,"activeModal");return t?{...t,...e,messages:r?si(e.messages):t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...r?{messages:si(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function or(e,t){const r=Du(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:Tc(e.activeChat,t==null?void 0:t.activeChat),controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel),settings:e.settings??(t==null?void 0:t.settings)}}function Mc(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 o=e.find(c=>c.id===a.id);return o?or(a,o):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(t.map(o=>o.id));for(const o of e)a.has(o.id)||n.push(o)}return n}function ri(e){return!!e&&typeof e=="object"&&"text"in e}function ro(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(o=>typeof o=="string"?o:ri(o)?String(o.text||""):"").join(r):ri(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Ps(e){return ro(e,{normalizeWhitespace:!0})}const Ac=i.createContext({ides:[],updateRouteChats:()=>{},initialLoaded:!1,toasts:[],setToasts:()=>{},wsStatus:"connected",isConnected:!0,connectionStates:{},connectionTransports:{},showReconnected:!1,userName:void 0,setUserName:()=>{},isP2PActive:!1,p2pStates:{},userRole:void 0,connectionRetryStatuses:void 0}),Lc=i.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function ni(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 Rc(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,o=t.serverVersion??e.serverVersion??r.serverVersion,c=t.versionMismatch===!0||e.versionMismatch===!0,l=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),o&&(n.serverVersion=o),d&&(n.versionUpdateReason=d),a&&o&&a===o?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||c&&a&&o&&a!==o)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function Eu(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 Fn(e){if(!e||typeof e!="object")return"";const t=e,r=Eu(Ps(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 $u(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=Fn(n);for(let o=0;o<a.length;o+=1)r^=a.charCodeAt(o),r=Math.imul(r,16777619)>>>0}return{count:e.length,hash:r.toString(16).padStart(8,"0"),first:Fn(e[0]),last:Fn(e[e.length-1])}}function _a(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Pa(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(_a(e)&&_a(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)Pa(e[l],t[l],r);return}const n=e,a=t,o=new Set([...Object.keys(n),...Object.keys(a)]);for(const c of o)c!=="messages"&&Pa(n[c],a[c],r)}function lr(e,t){return Array.isArray(e)?e.map(r=>lr(r,t)):!e||typeof e!="object"?e:_a(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?$u(a,t):lr(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,lr(n,t)]))}function Bu(e,t){try{const r=new WeakSet;return Pa(e,t,r),JSON.stringify(lr(e,r))===JSON.stringify(lr(t,r))}catch{return!1}}function Da(e,t,r){return Bu(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function _c(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Ou(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function ai(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,o=Mc(e.childSessions,t.childSessions,{preserveMissing:n}),c=Tc(t.activeChat,e.activeChat);return Rc(e,t,{...e,...t,chats:a,childSessions:o,activeChat:c,_lastUpdate:r})}function Ku(e,t,r){var a,o;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=Mc(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.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","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])Ou(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Fu(e,t,r,n){const a=Ku(e,t,n),o=Object.keys(a).length>0?Rc(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return Da(e,o,r)}function Wu(e){const t=new Set(e.map(o=>o.id)),r=new Set,n=new Set,a=new Set;for(const o of e){const c=_c(o);c&&r.add(c),c&&o.type!=="adhdev-daemon"&&n.add(c),c&&o.type==="adhdev-daemon"&&o._sessionListAuthoritative&&a.add(c)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function Hu(e,t,r,n,a,o){return!a.has(t)||!o.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function Uu(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function zu(e,t,r){var u,f;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(b=>({...b,_lastUpdate:n}));const o=new Map;for(const b of t)o.set(b.id,b);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:m}=Wu(e);for(const b of e){const v=o.get(b.id);if(!v){o.set(b.id,{...b,_lastUpdate:n});continue}const h=ni(b),p=ni(v),g=_c(b),y=!a.has(g);if(h>p){const S=ai(v,b,n,y);o.set(b.id,Da(v,S,n));continue}if(h<p){o.set(b.id,Fu(v,b,n,y));continue}const x=b.timestamp||n,C=v._lastUpdate||v.timestamp||0;if(x>=C){const S=ai(v,b,n,y);o.set(b.id,Da(v,S,n));continue}(u=b.chats)!=null&&u.length&&!((f=v.chats)!=null&&f.length)&&o.set(b.id,{...v,chats:b.chats})}for(const[b,v]of o){const h=v.daemonId||b.split(":")[0];if(!l.has(h))continue;if(a.has(h)&&m.has(h)&&!c.has(b)){o.delete(b);continue}const p=n-(v._lastUpdate||v.timestamp||0);Hu(v,h,p,c,a,d)&&o.delete(b)}for(const[b,v]of o){const h=v.daemonId||b.split(":")[0];if(Uu(v,h,l,d,o))continue;n-(v._lastUpdate||v.timestamp||0)>3e5&&v.status!=="online"&&o.delete(b)}return Array.from(o.values())}function Vu(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 Gu({children:e,connectionOverrides:t}){const[r,n]=i.useState([]),[a,o]=i.useState(!1),[c,l]=i.useState([]),[d,m]=i.useState(void 0),u=i.useRef(r);i.useEffect(()=>{u.current=r},[r]);const f=i.useCallback((y,x)=>{n(C=>{let S=!1;const w=C.map(M=>M.id!==y||M.chats===x?M:(S=!0,{...M,chats:x}));return S?w:C})},[]),b=i.useCallback((y,x)=>{n(C=>{const S=C.length===0?y:zu(y,C,x),w=!Vu(C,S);return w&&_s.record({kind:"dashboard.entries_applied",payload:{incoming:ti(y),next:ti(S)}}),w?S:C})},[]),v=i.useCallback(()=>o(!0),[]),h=i.useMemo(()=>({injectEntries:b,markLoaded:v,getIdes:()=>u.current}),[b,v]),p=t,g=i.useMemo(()=>({ides:r,updateRouteChats:f,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,connectionRetryStatuses:p==null?void 0:p.connectionRetryStatuses,userName:d,setUserName:m}),[r,f,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,p==null?void 0:p.connectionRetryStatuses,d]);return s.jsx(Lc.Provider,{value:h,children:s.jsx(Ac.Provider,{value:g,children:e})})}function es(){return i.useContext(Ac)}function br(){return i.useContext(Lc)}function Pc(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function o(l){const d=r==null?void 0:r(),m=a(l),u=l.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!l.startsWith("http")&&!t?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function c(l,d={}){const m={"Content-Type":"application/json",...d.headers||{}},u=r==null?void 0:r();u&&(m.Authorization=`Bearer ${u}`);const f=a(l),b=new AbortController,v=setTimeout(()=>b.abort(),15e3);try{const h=await fetch(f,{...d,headers:m,signal:b.signal});if(h.status===401)throw n==null||n(),new Error("Unauthorized");if(!h.ok){const p=await h.json().catch(()=>({error:h.statusText}));throw new Error(p.error||`API Error: ${h.status}`)}return h.json()}finally{clearTimeout(v)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,d,m={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),execTerminal:(l,d,m)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:m})}),sendAgentMessage:(l,d,m)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:m})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,d,m)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:m?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,d,m={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),getMuxEventsUrl:l=>o(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>o(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const qu=Pc({baseUrl:"http://localhost:3847"}),Yu=i.createContext(qu);function Xu({client:e,children:t}){return s.jsx(Yu.Provider,{value:e,children:t})}const Ju={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Dc=i.createContext(Ju);function Qu({value:e,children:t}){return s.jsx(Dc.Provider,{value:e,children:t})}function yt(){return i.useContext(Dc)}function Zu(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 em(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function tm(e){return e?Zu([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),em(e.content)]):""}const Ke={size:18};function Ec({size:e=Ke.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 no({size:e=Ke.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 Jt({size:e=Ke.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 $c({size:e=Ke.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 sm({size:e=Ke.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 rm({size:e=Ke.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 Bc({size:e=Ke.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 nm({size:e=Ke.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 Nn({size:e=Ke.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 Oc({size:e=Ke.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 am({size:e=Ke.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 zt({size:e=Ke.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 It({size:e=Ke.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 ao({size:e=Ke.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 om({size:e=Ke.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 xs({size:e=Ke.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 wr({size:e=Ke.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 gr({size:e=Ke.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 Ds({size:e=Ke.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 Is({size:e=Ke.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"5",r:"2"}),s.jsx("circle",{cx:"5",cy:"19",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),s.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),s.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function im({size:e=Ke.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:"12 2 2 7 12 12 22 7 12 2"}),s.jsx("polyline",{points:"2 12 12 17 22 12"}),s.jsx("polyline",{points:"2 17 12 22 22 17"})]})}function Kc({size:e=Ke.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 oo({size:e=Ke.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 Fc({size:e=Ke.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 cm({size:e=Ke.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 io({size:e=Ke.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 lm({size:e=Ke.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 co({size:e=Ke.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 Wc({size:e=Ke.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 gt({size:e=Ke.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 dm({size:e=Ke.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 um({size:e=Ke.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 mm({size:e=Ke.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 pm({size:e=Ke.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 Cn({size:e=Ke.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 fm({size:e=Ke.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 hm({size:e=Ke.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 xm({size:e=Ke.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 bm({size:e=Ke.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 gm({size:e=Ke.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 ym({size:e=Ke.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 vm({size:e=Ke.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 wm({size:e=Ke.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 jm({size:e=Ke.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 km({size:e=Ke.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 Sm({size:e=Ke.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 Nm({size:e=Ke.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 lo="adhdev_chat_activity_visible",oi=new Set(["hidden","debug","internal"]),ii=new Set(["visible","user","chat"]),Cm=new Set(["debug","trace","internal"]),Im=new Set(["tool_call","terminal_command","runtime_activity"]),Tm=new Set(["runtime_status","provider_chrome","control"]),Mm=new Set(["thought","tool","terminal"]);function Hc(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function ks(e){return typeof e=="string"?e.trim().toLowerCase():""}function Wn(e,t,r){return e[r]??(t==null?void 0:t[r])}function ci(e,t,r){const n=e;return r.some(a=>n[a]===!0||(t==null?void 0:t[a])===!0)}function Am(e,t){const r=ks(e.kind);return r||(t==="tool"?"tool":"standard")}function Hn(e,t,r){const n=Hc(e),a=typeof(n==null?void 0:n.label)=="string"?n.label.trim():"";return a||(t==="terminal"||r==="terminal_command"?"Terminal":t==="tool"||r==="tool_call"?"Tool":t==="thought"?"Thought":r==="runtime_activity"?"Runtime":"Activity")}function Lm(e){const t=e.content;return Array.isArray(t)&&t.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function uo(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=Hc(e),r=ks(e.role),n=Am(e,r),a=ks(Wn(e,t,"visibility")),o=ks(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),c=ks(Wn(e,t,"audience")),l=ks(Wn(e,t,"source")),d=oi.has(a)||oi.has(o)||Cm.has(c)||ci(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),m=ii.has(a)||ii.has(o)||c==="chat"||ci(e,t,["userFacing"]),u=Mm.has(n)||Im.has(l);if(d)return{surface:u?"activity":"internal",isUserFacing:!1,isActivityFacing:u,isInternal:!u,role:r,kind:n,label:Hn(e,n,l)};if(m)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:Hn(e,n,l)};if((r==="system"||n==="system")&&Lm(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(Tm.has(l)||r==="system"||n==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:r,kind:n,label:"Internal"};if(u)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:r,kind:n,label:Hn(e,n,l)};const f=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:f?"chat":"internal",isUserFacing:f,isActivityFacing:!1,isInternal:!f,role:r,kind:n,label:f?"Chat":"Internal"}}function Rm(e){return(Array.isArray(e)?e:[]).filter(t=>uo(t).isUserFacing)}function Uc(e){return(Array.isArray(e)?e:[]).filter(t=>uo(t).isActivityFacing)}function _m(e,t,r){return!r||t.length===0?e:[...e,...t].sort((n,a)=>{const o=Number(n.receivedAt??n.timestamp??0)||0,c=Number(a.receivedAt??a.timestamp??0)||0;if(o!==c)return o-c;const l=Number(n.index??0)||0,d=Number(a.index??0)||0;return l-d})}function li(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(lo))==="1"}catch{return!1}}function Pm(e,t=typeof localStorage<"u"?localStorage:void 0){try{t==null||t.setItem(lo,e?"1":"0")}catch{}}const zc=[bu,{singleTilde:!1}],Vc=[zc,gu,yu],Dm=[zc],mo=200,Em=80,di=650,Vs=new Map;function dn(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function $m(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}:${tm(n)}`}function Bm(e,t,r,n){return e||!t?!1:dn(r,n)}function Om({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=Em,bottomThresholdPx:a=mo}){const o=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:o>n,showBottom:Math.max(0,c-o-l)>a}}function Km(e){return Om({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function ir(e,t=mo){return!!e&&e.fromBottom>=t}function Fm(e,t){return dn(e,t)?!ir(e):!0}function Wm({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function Hm({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function Un(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function Gc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Um(e,t,r){return Number(e.receivedAt||r[un(e,t)]||0)||0}function qc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function zm(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function Gs(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 zn(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 Dr(e,t,r){return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2 text-sm",role:"note",children:[s.jsx("span",{className:"font-medium",children:e}),t?s.jsx("span",{className:"ml-1 break-all",children:t}):null,r?s.jsx("div",{className:"mt-1 opacity-80",style:{whiteSpace:"pre-wrap"},children:r}):null]})}function ui(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):qc(e)?s.jsx(to,{remarkPlugins:Vc,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function qs({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:ui(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=zn(r),o=r.alt||r.description||Gs(r.uri,"image");return a?s.jsx("img",{src:a,alt:o,className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):s.jsx("div",{children:Dr("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=zn(r);return a?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("audio",{controls:!0,src:a,className:"max-w-full"}),r.transcript?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:r.transcript}):null]},`audio-${n}`):s.jsx("div",{children:Dr("Audio",Gs(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=zn(r),o=r.title||r.name||r.alt||Gs(r.uri,"video"),c=[r.transcript,r.description,r.mimeType].filter(Boolean).join(`
3
- `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):Dr("Video",o,c),a&&c?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:c}):null]},`video-${n}`)}if(r.type==="resource_link"){const a=r.title||r.name||Gs(r.uri,"resource"),o=[r.description,r.mimeType].filter(Boolean).join(`
4
- `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:a}):Dr("Resource",a,o),r.uri&&o?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:o}):null]},`resource-link-${n}`)}if(r.type==="resource"&&r.resource){const a=Gs(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}),ui(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 un(e,t){const r=e,n=ro(e.content,{joiner:`
5
- `});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 Vm=i.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(to,{remarkPlugins:Dm,children:t.text}),s.jsx("span",{className:"action-time",children:Gc(t.timestamp)})]})},(e,t)=>e.log===t.log),Gm=i.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:c,onToggleTextExpanded:l}){var j,k,B;const d=(t.role||"").toLowerCase(),m=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),f=uo(t),b=zm(t.content)?t.content:null,v=!!(b!=null&&b.some(_=>_.type!=="text")),h=ro(t.content,{joiner:`
6
- `});if(f.isActivityFacing&&u!=="thought"&&u!=="tool"&&u!=="terminal"){const _=f.label||"Activity";return s.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[s.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[s.jsx("span",{className:"activity-dot"}),s.jsx("span",{children:_})]}),v&&b?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(qs,{parts:b,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:h})]})}if(u==="thought"){const _=typeof((j=t.meta)==null?void 0:j.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":f.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(mm,{size:13}),s.jsx("span",{children:_})]}),s.jsx("div",{className:"chat-msg-body",children:h})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":f.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),s.jsx("span",{className:"tool-label",children:"Tool"})]}),v&&b?s.jsx("div",{className:"tool-text w-full",children:s.jsx(qs,{parts:b,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:h})]});if(u==="terminal"){const _=(k=t.meta)!=null&&k.isRunning?"⏳":"✅",T=typeof((B=t.meta)==null?void 0:B.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":f.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:_}),s.jsx("span",{children:T})]}),v&&b?s.jsx("div",{className:"chat-msg-body",children:s.jsx(qs,{parts:b,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:h})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:v&&b?s.jsx(qs,{parts:b,renderAsPreformatted:!1}):h.slice(0,100)});const p=t.meta,y=(typeof(p==null?void 0:p.renderMode)=="string"?p.renderMode.trim():"")==="preformatted",x=h,C=!1,S=x,w=y,M=!w&&qc(S),L=["chat-message-row",m?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:L,children:(x||v||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${x||v?"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:Gc(r)})]}),(x||v)&&s.jsx("div",{className:"chat-markdown",children:v&&b?s.jsx(qs,{parts:b,renderAsPreformatted:w}):w?s.jsx("pre",{className:"chat-preformatted",children:S}):M?s.jsx(to,{remarkPlugins:Vc,children:S}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:S})}),C]})})},(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),qm=i.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:d={},lastMessageHash:m,showActivityMessages:u=!1,emptyState:f,onLoadMore:b,isLoadingMore:v,hasMoreHistory:h,hiddenLiveCount:p=0,loadError:g,scrollToBottomRequestNonce:y,isVisible:x=!0},C){const S=i.useRef(null),w=i.useRef(null),M=i.useRef(null),L=i.useRef(0),j=i.useRef(""),k=i.useRef(""),B=i.useRef(!1),_=i.useRef(null),T=i.useRef(!1),F=i.useRef(null),H=i.useRef(!1),[R,I]=i.useState(new Set),[N,K]=i.useState({showTop:!1,showBottom:!1}),P=i.useRef(!1),E=i.useRef(!1),U=i.useRef(x),ee=i.useRef(x),ye=i.useRef(null);ee.current=x;const le=()=>{const re=S.current;return re?re.scrollHeight-re.scrollTop-re.clientHeight<mo:!0},Q=i.useCallback(()=>{const re=S.current,G=re?Km(re):{showTop:!1,showBottom:!1};K(je=>je.showTop===G.showTop&&je.showBottom===G.showBottom?je:G)},[]),xe=i.useCallback((re="auto")=>{var je;const G=S.current;G&&(G.scrollTo({top:G.scrollHeight,behavior:re}),(je=G.ownerDocument.defaultView)==null||je.requestAnimationFrame(()=>Q()))},[Q]),we=i.useCallback((re="auto")=>{var je;const G=S.current;G&&(G.scrollTo({top:0,behavior:re}),(je=G.ownerDocument.defaultView)==null||je.requestAnimationFrame(()=>Q()))},[Q]),be=i.useCallback(()=>{var Ae;const re=S.current,G=(Ae=window.getSelection)==null?void 0:Ae.call(window);if(!re||!G||G.rangeCount===0||G.isCollapsed){H.current=!1;return}const je=G.anchorNode,ge=G.focusNode;H.current=!!(je&&ge&&re.contains(je)&&re.contains(ge))},[]),X=i.useMemo(()=>{const re=Rm(t),G=Uc(t);return _m(re,G,u)},[t,u]),ue=X.length===t.length?m:void 0,fe=$m(X,ue),ve=i.useCallback(()=>{const re=S.current;if(!re||!l||!ee.current)return;const G={top:re.scrollTop,fromBottom:Math.max(0,re.scrollHeight-re.scrollTop-re.clientHeight),messageFingerprint:fe};ye.current={contextKey:l,snapshot:G},Vs.set(l,G)},[l,fe]),pe=i.useCallback((re="auto")=>{_.current!=null&&cancelAnimationFrame(_.current),_.current=requestAnimationFrame(()=>{_.current=null,xe(re)})},[xe]),Se=i.useCallback(()=>{P.current=!1,T.current=!0,E.current=!0,F.current!=null&&window.clearTimeout(F.current),F.current=window.setTimeout(()=>{T.current=!1,F.current=null},di)},[]);i.useEffect(()=>{const re=!B.current,G=k.current!==l;if(k.current=l,re||G){B.current=!0;const ge=l?Vs.get(l):null,Ae=!!ge&&dn(ge,fe);P.current=Ae?ir(ge):!1,T.current=Fm(ge,fe),H.current||(Ae?requestAnimationFrame(()=>{const Me=S.current;Me&&(Un(Me,ge),P.current=ir(ge),Q(),E.current=!0)}):pe("auto")),L.current=X.length,j.current=fe;return}X.length>L.current;const je=fe!==j.current;Wm({hasSelection:H.current,userScrolledUp:P.current,hasChatContentChanged:je})&&pe("auto"),L.current=X.length,j.current=fe},[fe,l,X.length,pe,Q]),i.useEffect(()=>{y&&(Se(),H.current||pe("auto"))},[Se,pe,y]),i.useEffect(()=>{const re=U.current;re&&!x&&ve(),ee.current=x,U.current=x;const G=l?Vs.get(l):null;if(Bm(re,x,G,fe)){if(!G)return;P.current=ir(G),T.current=!1,H.current||requestAnimationFrame(()=>{const je=S.current;je&&(Un(je,G),Q())});return}},[x,l,fe,Se,ve,pe,Q]),i.useEffect(()=>()=>{const re=ye.current;re&&Vs.set(re.contextKey,re.snapshot),_.current!=null&&cancelAnimationFrame(_.current),F.current!=null&&window.clearTimeout(F.current)},[]),i.useEffect(()=>{const re=w.current,G=S.current;if(!re||!G)return;const je=()=>{F.current!=null&&window.clearTimeout(F.current),F.current=window.setTimeout(()=>{T.current=!1,F.current=null},di)},ge=new ResizeObserver(()=>{Q();const Ae=T.current;Hm({hasSelection:H.current,userScrolledUp:P.current,contextAutoScrollActive:Ae})&&(pe("auto"),Ae&&je())});return ge.observe(re),G!==re&&ge.observe(G),()=>{ge.disconnect(),F.current!=null&&(window.clearTimeout(F.current),F.current=null)}},[pe,l,Q]),i.useImperativeHandle(C,()=>({scrollToBottom:(re="smooth")=>{xe(re)}}),[xe]),i.useEffect(()=>{const re=S.current;if(!re)return;let G;const je=()=>{ve(),clearTimeout(G),G=setTimeout(()=>{P.current=!le(),Q()},50)};return re.addEventListener("scroll",je,{passive:!0}),()=>{re.removeEventListener("scroll",je),clearTimeout(G)}},[ve,Q]),i.useEffect(()=>(document.addEventListener("selectionchange",be),()=>document.removeEventListener("selectionchange",be)),[be]);const Z=i.useRef(0),de=i.useRef(!1);i.useEffect(()=>{const re=S.current;if(!re||!de.current||Z.current===0)return;const G=re.scrollHeight-Z.current;G>0&&(re.scrollTop=G),Q(),ve(),Z.current=0,de.current=!1},[X.length,ve,Q]),i.useEffect(()=>{if(E.current||!l)return;const re=Vs.get(l),G=S.current;if(!(!re||!G)){if(!dn(re,fe)){xe("auto"),E.current=!0;return}Un(G,re),P.current=ir(re),Q(),E.current=!0}},[l,fe,X.length,xe,Q]);const oe=()=>{const re=S.current;re&&(Z.current=re.scrollHeight),de.current=!0,b==null||b()},me=()=>{P.current=!0,we("smooth"),ve()},ie=()=>{Se(),xe("smooth"),ve()},D=i.useMemo(()=>{const re=X.map((Ae,Me)=>({type:"message",data:Ae,index:Me,ts:Um(Ae,Me,d)}));if(!r||r.length===0)return re;const G=[...r].sort((Ae,Me)=>Ae.timestamp-Me.timestamp).map((Ae,Me)=>({type:"action",data:Ae,index:Me,ts:Ae.timestamp})),je=[];let ge=0;for(const Ae of re){for(;ge<G.length&&Ae.ts>0&&G[ge].ts<Ae.ts;)je.push(G[ge++]);je.push(Ae)}for(;ge<G.length;)je.push(G[ge++]);return je},[X,r,d]),z=p>0||!!h,ce=p>0?`↑ Show ${Math.min(p,80)} earlier messages${p>80?` (${p} hidden)`:""}`:g?`↻ ${g}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:S,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:w,className:"chat-container-content",children:[v&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),z&&!v&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:oe,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${g&&p===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:ce})}),D.length===0&&!z&&(f||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),D.map(re=>{if(re.type==="action"){const Ne=re.data;return s.jsx(Vm,{log:Ne},`action-${re.index}`)}const G=re.data,je=re.index,ge=un(G,je),Ae=G.receivedAt||d[ge],Me=`${l}-${ge}`,O=R.has(Me);return s.jsx(Gm,{message:G,receivedAt:Ae,agentName:n,userName:a,isCliMode:o,isTextExpanded:O,onToggleTextExpanded:()=>I(Ne=>{const Re=new Set(Ne);return O?Re.delete(Me):Re.add(Me),Re})},`msg-${ge}`)}),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:M})]})}),(N.showTop||N.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[N.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:me,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),N.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:ie,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Ym=i.memo(qm,(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.showActivityMessages===t.showActivityMessages&&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),Xm="modulepreload",Jm=function(e){return"/"+e},mi={},Qm=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=Jm(d),d in mi)return;mi[d]=!0;const m=d.endsWith(".css"),u=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":Xm,m||(f.as="script"),f.crossOrigin="",f.href=d,l&&f.setAttribute("nonce",l),document.head.appendChild(f),m)return new Promise((b,v)=>{f.addEventListener("load",b),f.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(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"&&o(l.reason);return t().catch(o)})};let pi=!1;const Yc=i.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},c)=>{const l=i.useRef(null),[d,m]=i.useState(null),u=i.useRef([]),f=i.useRef(!1),b=i.useRef(!1),v=i.useRef(!1),h=i.useRef(!1),p=()=>{const g=l.current;if(g){f.current&&(g.clear(),f.current=!1);for(const y of u.current)g.write(y.data,y.onProcessed);u.current=[],b.current&&(g.fit(),b.current=!1),v.current&&(g.bumpResize(),v.current=!1),h.current&&(g.scrollToTop(),h.current=!1)}};return i.useImperativeHandle(c,()=>({write:(g,y)=>{l.current?l.current.write(g,y):u.current.push({data:g,onProcessed:y})},clear:()=>{l.current?l.current.clear():(u.current=[],f.current=!0)},reset:()=>{l.current&&typeof l.current.reset=="function"?l.current.reset():(u.current=[],f.current=!0)},resize:(g,y)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(g,y)},fit:()=>{l.current?l.current.fit():b.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():v.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():h.current=!0},getSelection:()=>{var g,y;return((y=(g=l.current)==null?void 0:g.getSelection)==null?void 0:y.call(g))||""},getVisibleText:()=>{var g,y;return((y=(g=l.current)==null?void 0:g.getVisibleText)==null?void 0:y.call(g))||""}}),[]),i.useEffect(()=>{d&&p()},[d]),i.useEffect(()=>{let g=!1;return Qm(()=>import("./terminal-DCVDkSIp.js"),__vite__mapDeps([0,1,2])).then(y=>{pi||(pi=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),g||m(()=>y.GhosttyTerminalView)}).catch(y=>{console.error("[CliTerminal] failed to load terminal renderer",y)}),()=>{g=!0}},[]),d?s.jsx(d,{ref:l,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:o,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"}})});Yc.displayName="CliTerminal";function Er({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 fi({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:o=!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 o?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 Zm({cursorPos:e,viewportRef:t,imgRef:r}){var x;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(x=t.current)==null?void 0:x.getBoundingClientRect();if(!o)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,d=c/l,m=a.width/a.height;let u,f,b,v;d>m?(u=a.width,f=a.width/d,b=0,v=(a.height-f)/2):(f=a.height,u=a.height*d,b=(a.width-u)/2,v=0);const h=a.left-o.left+b+u*e.nx,p=a.top-o.top+v+f*e.ny,g=Math.max(8,Math.min(o.width-8,h)),y=Math.max(8,Math.min(o.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:g-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 ep({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:c,setImeText:l,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:f,mobileFillZoom:b,onZoomOut:v,onZoomReset:h,onZoomIn:p,transportType:g,screenshotUsage:y,lastActionStatus:x}){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),o(!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=>{d(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:()=>{o(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"})]}),u>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),g==="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"}),g==="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`}),x&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:x})]})]}),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: ",u<=(f?b:1)+.01?f?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:C=>{C.stopPropagation(),v()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:C=>{C.stopPropagation(),h()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:f?"FILL":"FIT"}),s.jsx("button",{onClick: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 tp({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 sp(){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 hi(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 jr(e,t){const r=i.useRef(null),n=i.useRef(0);i.useEffect(()=>{if(!sp())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,hi(l)]))}),r.current=t;return}const o=Object.keys({...a,...t}).filter(c=>!Object.is(a[c],t[c]));o.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:o,snapshot:Object.fromEntries(o.map(c=>[c,hi(t[c])]))}),r.current=t})}function rp({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:c,panXRef:l,panYRef:d,setPanX:m,setPanY:u,setZoom:f,lastWheelTimeRef:b,onAction:v,setLastActionStatus:h,spawnRippleFromNormalized:p,clampPan:g,isMobile:y,mobileFillZoom:x}){const[C,S]=i.useState(null),w=i.useRef(null),M=i.useRef(null),L=i.useRef(null),j=i.useRef(!1),k=i.useRef(null),B=i.useRef(0),_=i.useRef(null),T=i.useRef(1),F=i.useRef({x:0,y:0}),H=i.useRef(!1),R=i.useRef(n),I=i.useRef(v),N=30,K=550,P=18,E=60,U=400,ee=12,ye=()=>{if(w.current)return;const xe={nx:.5,ny:.5};w.current=xe,S(xe)};return i.useEffect(()=>{R.current=n,n==="mouse"&&ye()},[n]),i.useEffect(()=>{I.current=v},[v]),i.useEffect(()=>{const xe=e.current;if(!xe)return;const we=pe=>{if(!r.current)return null;const Se=r.current.getBoundingClientRect();return!Se.width||!Se.height?null:{nx:Math.max(0,Math.min(1,(pe.clientX-Se.left)/Se.width)),ny:Math.max(0,Math.min(1,(pe.clientY-Se.top)/Se.height))}},be=(pe,Se)=>{if(!r.current)return{dnx:0,dny:0};const Z=r.current,de=Z.getBoundingClientRect(),oe=Z.naturalWidth||de.width,me=Z.naturalHeight||de.height,ie=oe/me,D=de.width/de.height;let z,ce;return ie>D?(z=de.width,ce=de.width/ie):(ce=de.height,z=de.height*ie),{dnx:pe/z,dny:Se/ce}},X=(pe,Se,Z)=>{if(Z<=1.05)return;const de=-(pe-.5)*100,oe=-(Se-.5)*100,me=g(de,oe,Z);(Math.abs(me.x-l.current)>.1||Math.abs(me.y-d.current)>.1)&&(m(me.x),u(me.y),l.current=me.x,d.current=me.y)},ue=pe=>{const Se=t.current;if(Se&&pe.target instanceof Node&&Se.contains(pe.target))pe.preventDefault();else return;if(pe.touches.length===1){const Z=pe.touches[0];M.current={x:Z.clientX,y:Z.clientY,time:Date.now()},L.current={x:Z.clientX,y:Z.clientY},H.current||(j.current=!1),k.current=setTimeout(()=>{if(!j.current&&!H.current)if(j.current=!0,R.current==="mouse"){const de=w.current||{nx:.5,ny:.5};h("Right Click"),p(de.nx,de.ny,"right"),I.current("input_click",{...de,button:"right"}).catch(()=>{})}else{const de=we(Z);de&&(h("Right Click"),p(de.nx,de.ny,"right"),I.current("input_click",{...de,button:"right"}).catch(()=>{}))}},500);return}if(pe.touches.length===2){k.current&&clearTimeout(k.current),j.current=!0,H.current=!0;const Z=pe.touches[1].clientX-pe.touches[0].clientX,de=pe.touches[1].clientY-pe.touches[0].clientY;_.current=Math.sqrt(Z*Z+de*de),T.current=c.current,F.current={x:(pe.touches[0].clientX+pe.touches[1].clientX)/2,y:(pe.touches[0].clientY+pe.touches[1].clientY)/2}}},fe=pe=>{const Se=t.current;if(Se&&pe.target instanceof Node&&Se.contains(pe.target)&&pe.preventDefault(),pe.touches.length===1&&L.current){const Z=pe.touches[0],de=Z.clientX-L.current.x,oe=Z.clientY-L.current.y;if(!j.current&&M.current){const me=Z.clientX-M.current.x,ie=Z.clientY-M.current.y;Math.sqrt(me*me+ie*ie)>8&&(j.current=!0,k.current&&clearTimeout(k.current))}if(j.current)if(R.current==="mouse"){const me=be(de,oe),ie=w.current||{nx:.5,ny:.5},D=Math.max(0,Math.min(1,ie.nx+me.dnx)),z=Math.max(0,Math.min(1,ie.ny+me.dny));w.current={nx:D,ny:z},S({nx:D,ny:z}),h(`Cursor: ${Math.round(D*100)}%, ${Math.round(z*100)}%`),X(D,z,c.current);const ce=Date.now();ce-b.current>=30&&(b.current=ce,I.current("input_mouseMoved",{nx:D,ny:z}).catch(()=>{}))}else if(c.current>1){const me=t.current;if(me){const ie=me.clientWidth,D=me.clientHeight,z=l.current+de/ie*100,ce=d.current+oe/D*100,re=g(z,ce,c.current);m(re.x),u(re.y),l.current=re.x,d.current=re.y}}else{const me=we(Z);if(me){const ie=Date.now();ie-b.current>=40&&(b.current=ie,h("Scroll"),I.current("input_wheel",{nx:me.nx,ny:me.ny,deltaX:Math.round(-de*2.5),deltaY:Math.round(-oe*2.5)}).catch(()=>{}))}}L.current={x:Z.clientX,y:Z.clientY};return}if(pe.touches.length===2&&_.current!==null){const Z=pe.touches[1].clientX-pe.touches[0].clientX,de=pe.touches[1].clientY-pe.touches[0].clientY,me=Math.sqrt(Z*Z+de*de)/_.current,ie=(pe.touches[0].clientX+pe.touches[1].clientX)/2,D=(pe.touches[0].clientY+pe.touches[1].clientY)/2,z=ie-F.current.x,ce=D-F.current.y,re=Math.abs(me-1)>.03;if(R.current==="mouse"){if(re){const G=Math.max(o,Math.min(5,T.current*me));f(G),c.current=G}else if(Math.abs(z)>2||Math.abs(ce)>2){const G=w.current||{nx:.5,ny:.5},je=Date.now();je-b.current>=30&&(b.current=je,h("Scroll"),I.current("input_wheel",{nx:G.nx,ny:G.ny,deltaX:Math.round(-z*3),deltaY:Math.round(-ce*3)}).catch(()=>{}))}}else{const G=Math.max(o,Math.min(5,T.current*me));f(G),c.current=G;const je=t.current;if(je&&G>1){const ge=je.clientWidth,Ae=je.clientHeight,Me=l.current+z/ge*100,O=d.current+ce/Ae*100,Ne=g(Me,O,G);m(Ne.x),u(Ne.y),l.current=Ne.x,d.current=Ne.y}}F.current={x:ie,y:D}}},ve=pe=>{var Se;if(k.current&&clearTimeout(k.current),_.current=null,pe.touches.length===1&&H.current){const Z=pe.touches[0];M.current={x:Z.clientX,y:Z.clientY,time:Date.now()},L.current={x:Z.clientX,y:Z.clientY},j.current=!0;return}if(pe.touches.length===0){if(H.current){H.current=!1,j.current=!1;return}if(pe.changedTouches.length===1){const Z=pe.changedTouches[0],de=Date.now(),oe=de-(((Se=M.current)==null?void 0:Se.time)||0),me=M.current?Z.clientX-M.current.x:0,ie=M.current?Z.clientY-M.current.y:0,D=Math.sqrt(me*me+ie*ie);if(R.current==="mouse"){if(oe<N||oe>K||D>P){j.current=!1;return}const z=w.current||we(Z);z&&(h(`Click: ${Math.round(z.nx*100)}%, ${Math.round(z.ny*100)}%`),p(z.nx,z.ny,"left"),I.current("input_click",{...z}).catch(()=>{}))}else{if(j.current){j.current=!1;return}if(oe<E||oe>U||D>ee){j.current=!1;return}const z=we(Z);if(!z)return;de-B.current<300?(h("Double tap"),p(z.nx,z.ny,"double"),I.current("input_click",{...z,clickCount:2}).catch(()=>{}),B.current=0):(h(`Tap: ${Math.round(z.nx*100)}%, ${Math.round(z.ny*100)}%`),p(z.nx,z.ny,"left"),I.current("input_click",{...z}).catch(()=>{}),B.current=de)}}j.current=!1}};return xe.addEventListener("touchstart",ue,{passive:!1}),xe.addEventListener("touchmove",fe,{passive:!1}),xe.addEventListener("touchend",ve,{passive:!1}),()=>{xe.removeEventListener("touchstart",ue),xe.removeEventListener("touchmove",fe),xe.removeEventListener("touchend",ve),k.current&&clearTimeout(k.current)}},[e,t,r,o,c,l,d,m,u,f,b,h,p,g]),{cursorPos:C,cursorPosRef:w,handleToggleInputMode:()=>{a(xe=>{const we=xe==="touch"?"mouse":"touch";return we==="mouse"&&ye(),we})},handleZoomReset:()=>{const xe=y?x:1;f(xe),c.current=xe,m(0),u(0),l.current=0,d.current=0}}}function Xc({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const c=i.useRef(null),l=i.useRef(null),d=i.useRef(null),[m,u]=i.useState(null),[f,b]=i.useState(""),[,v]=i.useState(!1),[h,p]=i.useState([]),g=i.useRef(0),[y,x]=i.useState(!1),[C,S]=i.useState(!1),w=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[M,L]=i.useState(w?"mouse":"touch"),[j,k]=i.useState(1),B=i.useRef(!1),[_,T]=i.useState(1),[F,H]=i.useState(0),[R,I]=i.useState(0);jr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:M,zoom:_,panX:F,panY:R,isMenuOpen:y,isImeOpen:C});const N=i.useRef(0),K=i.useRef(_),P=i.useRef(F),E=i.useRef(R);i.useEffect(()=>{K.current=_},[_]),i.useEffect(()=>{P.current=F},[F]),i.useEffect(()=>{E.current=R},[R]),i.useEffect(()=>{var oe;(oe=c.current)==null||oe.focus()},[]);const U=r==="connected",ee=n,ye=U?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",le=U?"The remote stream is warming up":"Waiting for the remote stream to catch up";i.useEffect(()=>{if(!w||B.current||!ee)return;const oe=d.current,me=l.current;if(!oe||!me)return;const ie=()=>{const D=me.clientWidth,z=me.clientHeight,ce=oe.naturalWidth,re=oe.naturalHeight;if(!ce||!re||!D||!z)return;const G=Math.min(D/ce,z/re),ge=Math.max(D/ce,z/re)/G;ge>1.01&&(k(ge),T(ge),K.current=ge),B.current=!0};oe.complete&&oe.naturalWidth?ie():oe.addEventListener("load",ie,{once:!0})},[ee,w]);const Q=.5;i.useEffect(()=>{_<=Q&&(H(0),I(0))},[_,Q]);const xe=(oe,me,ie)=>{if(ie<=Q)return{x:0,y:0};const D=(ie-1)/(2*ie)*100,z=(ie-1)/(2*ie)*100;return{x:Math.max(-D,Math.min(D,oe)),y:Math.max(-z,Math.min(z,me))}},we=(oe,me)=>{if(!d.current)return null;const ie=d.current.getBoundingClientRect();return!ie.width||!ie.height?null:{nx:Math.max(0,Math.min(1,(oe-ie.left)/ie.width)),ny:Math.max(0,Math.min(1,(me-ie.top)/ie.height))}},be=(oe,me,ie)=>{const D=l.current;if(!D)return;const z=D.getBoundingClientRect(),ce=++g.current;p(re=>[...re,{id:ce,x:oe-z.left,y:me-z.top,type:ie}]),setTimeout(()=>p(re=>re.filter(G=>G.id!==ce)),600)},X=(oe,me,ie)=>{const D=d.current,z=l.current;if(!D||!z)return;const ce=D.getBoundingClientRect(),re=z.getBoundingClientRect(),G=D.naturalWidth||ce.width,je=D.naturalHeight||ce.height,ge=G/je,Ae=ce.width/ce.height;let Me,O,Ne,Re;ge>Ae?(Me=ce.width,O=ce.width/ge,Ne=0,Re=(ce.height-O)/2):(O=ce.height,Me=ce.height*ge,Ne=(ce.width-Me)/2,Re=0);const Fe=ce.left-re.left+Ne+Me*oe,He=ce.top-re.top+Re+O*me,Ge=++g.current;p(qe=>[...qe,{id:Ge,x:Fe,y:He,type:ie}]),setTimeout(()=>p(qe=>qe.filter(et=>et.id!==Ge)),600)},ue=async oe=>{var ie;const me=we(oe.clientX,oe.clientY);if(me){u(`Click: ${Math.round(me.nx*100)}%, ${Math.round(me.ny*100)}%`),be(oe.clientX,oe.clientY,"left"),(ie=c.current)==null||ie.focus();try{const D=await e("input_click",{nx:me.nx,ny:me.ny});D!=null&&D.success||t(`❌ Click failed: ${D==null?void 0:D.error}`)}catch(D){t(`❌ Click error: ${D.message||D}`)}}},fe=async(oe,me,ie,D=0)=>{try{await e("input_key",{type:ie?"char":"keyDown",key:oe,code:me,text:ie?oe:void 0,unmodifiedText:ie?oe:void 0,modifiers:D})}catch(z){t(`❌ Key error: ${z.message||z}`)}},ve=async oe=>{if(oe.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(oe.key)&&oe.preventDefault();let ie=0;oe.altKey&&(ie|=1),oe.ctrlKey&&(ie|=2),oe.metaKey&&(ie|=4),oe.shiftKey&&(ie|=8),u(`Key: ${oe.key}`),await fe(oe.key,oe.code,oe.key.length===1,ie)},pe=async oe=>{if(oe.key==="Enter"){if(oe.nativeEvent.isComposing)return;if(f){const me=f;b(""),u(`IME Sent: ${me}`);try{const ie=await e("input_type",{text:me});ie!=null&&ie.success||t(`❌ IME error: ${ie==null?void 0:ie.error}`)}catch(ie){t(`❌ IME error: ${ie.message}`)}}else u("Key: Enter"),await fe("Enter","Enter",!1)}};i.useEffect(()=>{const oe=c.current;if(!oe)return;const me=ie=>{var D;if((D=d.current)!=null&&D.contains(ie.target)){ie.preventDefault();const z=Date.now();if(z-N.current<40)return;N.current=z;const ce=we(ie.clientX,ie.clientY);if(!ce)return;u(`Scroll: ${Math.round(ie.deltaY)}`),e("input_wheel",{nx:ce.nx,ny:ce.ny,deltaX:Math.round(ie.deltaX),deltaY:Math.round(ie.deltaY)}).catch(()=>{})}};return oe.addEventListener("wheel",me,{passive:!1}),()=>oe.removeEventListener("wheel",me)},[e]);const{cursorPos:Se,handleToggleInputMode:Z,handleZoomReset:de}=rp({containerRef:c,viewportRef:l,imgRef:d,inputMode:M,setInputMode:L,minZoom:Q,zoomRef:K,panXRef:P,panYRef:E,setPanX:H,setPanY:I,setZoom:T,lastWheelTimeRef:N,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:X,clampPan:xe,isMobile:w,mobileFillZoom:j});return s.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ve,onContextMenu:oe=>oe.preventDefault(),onFocus:()=>v(!0),onBlur:()=>v(!1),tabIndex:0,children:[s.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[ee?s.jsx("img",{ref:d,src:ee,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${_}) translate(${F}%, ${R}%)`,transformOrigin:"center center",cursor:M==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ue,onContextMenu:oe=>oe.preventDefault(),onDragStart:oe=>oe.preventDefault()}):s.jsx(tp,{waitingLabel:ye,waitingHint:le,transportType:o}),M==="mouse"&&ee&&s.jsx(Zm,{cursorPos:Se,viewportRef:l,imgRef:d}),h.map(oe=>{const ie={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(${ie}, 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(${ie}, 0.9)`,boxShadow:`0 0 12px rgba(${ie}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},oe.id)})]}),s.jsx(ep,{inputMode:M,onToggleInputMode:Z,isImeOpen:C,setIsImeOpen:S,isMenuOpen:y,setIsMenuOpen:x,imeText:f,setImeText:b,handleImeSubmit:pe,isConnActive:U,zoom:_,isMobile:w,mobileFillZoom:j,onZoomOut:()=>T(oe=>Math.max(.5,oe-.25)),onZoomReset:de,onZoomIn:()=>T(oe=>Math.min(5,oe+.25)),transportType:o,screenshotUsage:a,lastActionStatus:m}),s.jsx("style",{children:`
7
- @keyframes slideUp {
8
- from { opacity: 0; transform: translateY(6px); }
9
- to { opacity: 1; transform: translateY(0); }
10
- }
11
- @keyframes slideUpSidebar {
12
- from { opacity: 0; transform: translateY(6px); }
13
- to { opacity: 1; transform: translateY(0); }
14
- }
15
- @keyframes click-ripple-ring {
16
- 0% { transform: scale(0.3); opacity: 1; }
17
- 100% { transform: scale(2.2); opacity: 0; }
18
- }
19
- @keyframes click-ripple-dot {
20
- 0% { transform: scale(1); opacity: 0.9; }
21
- 50% { transform: scale(1.8); opacity: 0.6; }
22
- 100% { transform: scale(0.5); opacity: 0; }
23
- }
24
- @keyframes remote-float {
25
- 0% { transform: translateY(0px); }
26
- 50% { transform: translateY(-7px); }
27
- 100% { transform: translateY(0px); }
28
- }
29
- `})]})}function In(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,o=Date.now()-e,c=Math.floor(o/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const d=Math.floor(l/60);if(d<24)return`${d}h${r}`;const m=Math.floor(d/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const Jc=e=>In(e);function np(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 Hs(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 ap(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...np(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 mn(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 Tn(e,t,r){const n=mn(e,t),a=Hs(e),o=a.isReconnecting,c=a.isConnecting,l=a.isGenerating,d=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,u=n.inboxBucket==="working"||l,b=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:b,requiresAction:m,isWorking:u,isReconnecting:o,isConnecting:c,isGenerating:l,isWaiting:d,inboxBucket:m?"needs_attention":u?"working":b?"task_complete":"idle"}}function op(e,t,r){return Tn(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Qc({activeConv:e,onModalButton:t}){const[r,n]=i.useState(null);if(i.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Hs(e).isWaiting||!e.modalButtons)return null;const o=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(gr,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,d)=>{const m=c(l).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(m),f=/^(reject|deny|delete|remove|abort)/.test(m),b=r===l,v=r!==null;return s.jsx("button",{onClick:()=>o(l),disabled:v,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":f?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${v&&!b?"opacity-40":"opacity-100"} ${v?"cursor-not-allowed":"cursor-pointer"}`,style:u?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:f?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:b?"⏳ ...":c(l)},d)})})]})]})}const po="adhdev_controls_bar_visible",Ea="adhdev:controlsbarvisibilitychange";function Vn(e){if(!e)return!1;try{return e.getItem(po)==="1"}catch{return!1}}function ip(e,t){if(t)try{t.setItem(po,e?"1":"0")}catch{}}function cp(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Ea,{detail:{visible:e}}))}function fo(){const[e,t]=i.useState(()=>typeof window>"u"?!1:Vn(window.localStorage)),r=i.useRef(e),n=i.useCallback((c,l=!0)=>{r.current=c,t(c),typeof window<"u"&&ip(c,window.localStorage),l&&cp(c)},[]);i.useEffect(()=>{const c=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:Vn(window.localStorage);r.current=u,t(u)},l=d=>{if(d.key!==po)return;const m=Vn(window.localStorage);r.current=m,t(m)};return window.addEventListener(Ea,c),window.addEventListener("storage",l),()=>{window.removeEventListener(Ea,c),window.removeEventListener("storage",l)}},[]);const a=i.useCallback(c=>{n(c)},[n]),o=i.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}var lp=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function dp(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function xt(e,t){if(dp(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":lp.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 pn(e){return xt(e)==="generating"}function xi(e,t){return xt(e,t)==="waiting_approval"}function ot(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function up(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),o=r%24;return`${a}d ${o}h`}function Gn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Mn(e,t){const r=typeof t=="string"?t.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),o=a.split(/[\\/]/).filter(Boolean);return o[o.length-1]||a}function mp(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 pp(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function fp(e){return mp(e.trim().replace(/\.local$/i,""))}function hp(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function Zc(e,t={}){var a,o;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(o=e.system)==null?void 0:o.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!pp(c));if(r&&r!=="Unknown")return fp(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Ct(e,t={}){return hp(e)||Zc(e,t)}function el(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 tl(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(o=>String((o==null?void 0:o.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function bs(e,t){return el(e).join(" · ")}function yr(e){return e.transport==="pty"}function As(e){return e.transport==="acp"}function xp(e,t){var r,n;return(r=t==null?void 0:t.providerLabels)!=null&&r[e]?t.providerLabels[e]:(n=t==null?void 0:t.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:ot(e)}function bi(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),c=ot(r||"").trim().toLowerCase();return n===a||n===o||n===c}function bp(e,t=[],r=[]){var d,m,u,f;const n=xt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(n==="waiting_approval")return"waiting_approval";if(n==="generating")return"generating";const a=t.find(b=>xi(b.status,{activeModal:b.activeModal})||pn(b.status));if(a)return xt(a.status,{activeModal:a.activeModal});const o=r.find(b=>xi(b.status,{activeModal:b.activeModal})||pn(b.status));if(o)return xt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const c=xt((d=t[0])==null?void 0:d.status,{activeModal:(m=t[0])==null?void 0:m.activeModal});if(c!=="idle")return c;const l=xt((u=r[0])==null?void 0:u.status,{activeModal:(f=r[0])==null?void 0:f.activeModal});return l!=="idle"?l:"idle"}function gp(e){return xt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function yp(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,"-"),o=t.get(a),c=xt(n.status);if(!o){t.set(a,{...n,status:c});continue}const l=r.indexOf(o.status||"idle"),d=r.indexOf(c||"idle");d>=0&&(l<0||d<l)&&t.set(a,{...n,status:c})}return Array.from(t.values())}function vp(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 wp(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&&vp(t.receivedAt)||0}function jp(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function $a(e){return Math.max(jp(e),wp(e.activeChat))}function kp(e,t,r,n,a,o){const c=t-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(o)}function ho(e,t){return kp($a(e),$a(t),Ct(e,{fallbackId:e.id}),Ct(t,{fallbackId:t.id}),e.id,t.id)}const sl="adhdev_notification_prefs",gi={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Sp(){try{const e=localStorage.getItem(sl);if(e){const t=JSON.parse(e);return{...gi,...t}}}catch{}return{...gi}}function Np(e){try{localStorage.setItem(sl,JSON.stringify(e))}catch{}}let Wt=Sp(),Jr=[];function Cp(){Jr.forEach(e=>e())}function Ip(e){Wt={...Wt,...e},Np(Wt),Cp()}function Tp(){const[,e]=i.useState(0);i.useEffect(()=>{const r=()=>e(n=>n+1);return Jr.push(r),()=>{Jr=Jr.filter(n=>n!==r)}},[]);const t=i.useCallback(r=>{Ip(r)},[]);return[{...Wt},t]}function dr(e){if(!Wt.globalEnabled)return!1;switch(e){case"disconnect":return Wt.disconnectAlert;case"completion":return Wt.completionAlert;case"approval":return Wt.approvalAlert;case"browser":return Wt.browserNotifications;default:return!0}}const Mp={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function rl(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function nl(){return"Notification"in window&&Notification.permission==="granted"}let ts=null;function Ap(e){return e!==!1}async function Lp(){if(ts!==null)return ts;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ts=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ts=!!await e.pushManager.getSubscription(),ts):(ts=!1,!1)}catch{return ts=!1,!1}}function Ba(e,t,r){if(nl())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 Rp(e,t={}){const r={...Mp,...t},n=i.useRef(new Map),a=i.useRef(0),[o,c]=i.useState(null);i.useEffect(()=>{let d=!1;return Lp().then(m=>{d||c(m)}),()=>{d=!0}},[]);const l=i.useCallback((d,m,u)=>{const f=Date.now();f-a.current<r.throttleMs||(a.current=f,Ba(d,m,u))},[r.throttleMs]);i.useEffect(()=>{var d;if(!(!r.enabled||!nl())&&dr("browser")&&!Ap(o)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,xt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const u=n.current.get(m.id),f=xt(m.status,{activeModal:m.activeModal}),b=m.name||m.id;if(r.onApproval&&dr("approval")&&f==="waiting_approval"&&u!=="waiting_approval"){const v=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";l(`🔔 ${b} — Approval needed`,v.slice(0,120),`approval-${m.id}`)}r.onComplete&&dr("completion")&&pn(u)&&f==="idle"&&l(`✅ ${b} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&f==="error"&&u!=="error"&&l(`⚠️ ${b} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,f)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,l])}const _p=/^(run|approve|accept|yes|allow|always)/,Pp=/^(run|approve|accept|yes|allow|always|proceed|save)/,Dp=/^(reject|deny|delete|remove|abort|cancel|no)/;function xo(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Ep(e){const t=xo(e).toLowerCase();return _p.test(t)?"primary":Dp.test(t)?"danger":"default"}function $p(e){return Pp.test(xo(e).toLowerCase())?"approve":"reject"}function Bp(e){return e.map((t,r)=>({label:xo(t),variant:Ep(t),action:$p(t),button:t,buttonIndex:r}))}function Op(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Kp(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 Fp{constructor(){Xe(this,"dedupMap",new Map);Xe(this,"DEDUP_WINDOW_MS",5e3);Xe(this,"DEDUP_MAX_SIZE",50);Xe(this,"DEDUP_CLEANUP_AGE_MS",1e4);Xe(this,"toastCallbacks",[]);Xe(this,"statusEventCallbacks",[]);Xe(this,"resolveActionFn",null);Xe(this,"viewRequestRespondFn",null);Xe(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.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,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(o=>o.id===t.daemonId&&o.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 o=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(o)return o}}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 h;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=n||t.daemonId||"",c=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),l=`${o}:${t.event}:${c}`;if(this.isDuplicate(l))return;for(const p of this.statusEventCallbacks)p(t);const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(d==null?void 0:d.type)||"";let u=ot(m);const f=this.resolveOwningDaemon(t);if(f){const p=Ct(f,{fallbackId:f.id});p&&(u=!m||m==="adhdev-daemon"?p:`${p}/${u}`)}let b="",v="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";b=`✅ ${u} agent task completed${p}`,v="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(b=`⚡ ${u} approval needed`,v="warning",(h=t.modalButtons)!=null&&h.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const g=this.resolveActionFn,y=Bp(t.modalButtons).map(S=>({label:S.label,variant:S.variant,onClick:()=>{g(p,"resolve_action",{action:S.action,button:S.button,buttonIndex:S.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),x=Op(u,t.modalMessage,b),C=Date.now();this.emitToast({id:C,message:x,type:v,timestamp:C,targetKey:n||p,actions:y,duration:15e3}),b=""}}else if(t.event==="monitor:long_generating"){const p=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";b=`⚠️ ${u} agent is taking a long time${p}`,v="warning",dr("browser")&&!document.hasFocus()&&Ba(`⚠️ ${u} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const p=t.requesterName||"A team member",g=t.requestId,y=t.orgId;if(b=`👁️ ${p} wants to view your session`,v="warning",g&&y&&this.viewRequestRespondFn){const x=Date.now(),C=Kp(y,g,this.viewRequestRespondFn,(S,w)=>console.error(`[EventManager] ${S} view request failed:`,w));this.emitToast({id:x,message:b,type:v,timestamp:x,actions:C,duration:3e4}),b=""}dr("browser")&&!document.hasFocus()&&Ba("👁️ View Request",`${p} wants to view your session`,`view-request-${g}`)}else t.event==="team:view_request_approved"?(b="✅ View request approved",v="success"):t.event==="team:view_request_rejected"&&(b=`❌ ${t.targetName||"Team member"} declined your view request`,v="warning");if(b){const p=Date.now();this.emitToast({id:p,message:b,type:v,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const nt=new Fp,yi=new Map;function fn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ls(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function An(e){return fn(e)?fn(e.result)?e.result:e:null}function Wp(e){const t=An(e);return!t||!fn(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function $r(e){const t=An(e);return!t||!fn(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Ys(e){const t=An(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Br(e){const t=An(e);return!!t&&t.success===!1}function Hp(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";nt.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";nt.showToast(n.notification.body,a)}}}function Up(e,t){return e&&Ls(e.currentValue)?e.currentValue:t}function zp(e,t){return Ls(t)?Ls(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Vp(e,t){var o,c;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(Ls(l))return l}const n=(o=t.controlValues)==null?void 0:o[e];if(Ls(n))return n;const a=(c=t.defaultValues)==null?void 0:c[e];return Ls(a)?a:void 0}function Qr(e,t){return e.options||t[e.id]||[]}const Gp={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 qp(e,t,r){var n;return((n=Gp[t])==null?void 0:n.has(r.id))===!0}function bo(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!qp(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function qn(e,t){return{value:t}}function Yp(e,t,r){var a;return r?((a=Qr(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const Xp={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Jp({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:c}){const{sendCommand:l}=yt(),d=`${e}:${t||n}`,m=Xp[n]||"#94a3b8",[u,f]=i.useState({}),b=i.useRef({}),v=i.useRef(c);b.current=u,v.current=c;const h=i.useRef(0),p={};for(const N of o||[])N.defaultValue!==void 0&&(p[N.id]=N.defaultValue);const g={...p,...c||{},...Date.now()<h.current?u:{}};i.useEffect(()=>{c&&Date.now()>h.current&&f({})},[c]);const[y,x]=i.useState(yi.get(d)||{}),[C,S]=i.useState(null),[w,M]=i.useState(null),L=i.useCallback(async(N,K={})=>{const P={...K,...t&&{targetSessionId:t}};return await l(e,N,P)},[e,t,l]),j=i.useCallback(async(N,K={})=>{const P=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await L("invoke_provider_script",{...P,scriptName:N,...K})},[L,n,r,t]),k=i.useCallback((N,K,P)=>{const E=Up(P,K);f(U=>({...U,[N.id]:E})),Hp(P==null?void 0:P.effects)},[]),B=i.useCallback((N,K)=>{f(P=>{const E={...P};return K===void 0?delete E[N.id]:E[N.id]=K,E}),h.current=0},[]);if(!o||o.length===0)return null;const _=bo(o,{hostIdeType:r,providerType:n});if(_.length===0)return null;const T=async N=>{if(C===N.id){S(null);return}if(Qr(N,y).length>0){S(N.id);return}if(N.dynamic&&N.listScript){M(N.id);try{const P=await j(N.listScript,{}),E=Wp(P);if(!E){const ye=Ys(P);ye&&nt.showToast(ye,"warning");return}const U=E.options;x(ye=>{const le={...ye,[N.id]:U};return yi.set(d,le),le});const ee=Vp(N.id,{localOverrideUntil:h.current,localValues:b.current,controlValues:v.current,defaultValues:p});if(zp(ee,E.currentValue)){const ye=E.currentValue;f(le=>({...le,[N.id]:ye}))}S(N.id)}catch(P){const E=P instanceof Error?P.message:`Could not load ${N.label}`;nt.showToast(E,"warning")}finally{M(null)}}},F=async(N,K)=>{S(null);const P=(c==null?void 0:c[N.id])??p[N.id];f(E=>({...E,[N.id]:K})),h.current=Date.now()+5e3;try{if(!N.setScript)return;const E=await j(N.setScript,qn(N,K)),U=$r(E);if(U&&!U.ok||Br(E))throw new Error((U==null?void 0:U.error)||Ys(E)||`Could not update ${N.label}`);k(N,K,U)}catch(E){B(N,P);const U=E instanceof Error?E.message:`Could not update ${N.label}`;nt.showToast(U,"warning")}},H=async N=>{const K=Qr(N,y).map(le=>le.value);if(K.length===0)return;const P=String(g[N.id]||""),U=(K.indexOf(P)+1)%K.length,ee=K[U];if(typeof ee!="string")return;const ye=(c==null?void 0:c[N.id])??p[N.id];f(le=>({...le,[N.id]:ee})),h.current=Date.now()+5e3;try{if(!N.setScript)return;const le=await j(N.setScript,qn(N,ee)),Q=$r(le);if(Q&&!Q.ok||Br(le))throw new Error((Q==null?void 0:Q.error)||Ys(le)||`Could not update ${N.label}`);k(N,ee,Q)}catch(le){B(N,ye);const Q=le instanceof Error?le.message:`Could not update ${N.label}`;nt.showToast(Q,"warning")}},R=async N=>{const P=!g[N.id],E=(c==null?void 0:c[N.id])??p[N.id];f(U=>({...U,[N.id]:P})),h.current=Date.now()+5e3;try{if(!N.setScript)return;const U=await j(N.setScript,qn(N,P)),ee=$r(U);if(ee&&!ee.ok||Br(U))throw new Error((ee==null?void 0:ee.error)||Ys(U)||`Could not update ${N.label}`);k(N,P,ee)}catch(U){B(N,E);const ee=U instanceof Error?U.message:`Could not update ${N.label}`;nt.showToast(ee,"warning")}},I=async N=>{if(!N.invokeScript)return;if(N.confirmMessage){const P=[N.confirmTitle,N.confirmMessage,N.confirmLabel].filter(U=>typeof U=="string"&&U.trim().length>0);if(!window.confirm(P.join(`
30
-
31
- `)))return}const K=(c==null?void 0:c[N.id])??p[N.id];try{const P=await j(N.invokeScript),E=$r(P);if(E&&!E.ok||Br(P))throw new Error((E==null?void 0:E.error)||Ys(P)||`Could not run ${N.label}`);E&&k(N,K??!0,E)}catch(P){B(N,K);const E=P instanceof Error?P.message:`Could not run ${N.label}`;nt.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}),_.map(N=>{const K=String(g[N.id]||""),P=Yp(N,y,K),E=C===N.id,U=w===N.id,ee=Qr(N,y),ye="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(N.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${ye} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${m}55`:"var(--border-default)",background:E?`${m}10`:"var(--surface-tertiary)",color:K?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void T(N),title:N.label,children:[N.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:N.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:U?"Loading…":P||N.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),E&&ee.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>S(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:N.label}),ee.map(le=>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:le.value===K?`${m}14`:"transparent",color:le.value===K?"var(--text-primary)":"var(--text-secondary)",borderLeft:le.value===K?`2px solid ${m}`:"2px solid transparent"},title:le.description||le.label,onMouseEnter:Q=>{Q.currentTarget.style.background=`${m}10`},onMouseLeave:Q=>{Q.currentTarget.style.background=le.value===K?`${m}14`:"transparent"},onClick:()=>void F(N,le.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:le.label}),le.value===K&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},le.value))]})]})]},N.id);case"cycle":return s.jsxs("button",{type:"button",className:`${ye} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:K?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void H(N),title:`Click to cycle: ${ee.map(le=>le.label).join(" → ")}`,children:[N.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:N.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:P||N.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},N.id);case"toggle":return s.jsxs("button",{type:"button",className:`${ye} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:K?`${m}44`:"var(--border-default)",background:K?`${m}14`:"var(--surface-tertiary)",color:K?m:"var(--text-muted)"},onClick:()=>void R(N),"aria-pressed":!!K,children:[N.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:N.icon}),N.label]},N.id);case"action":return s.jsxs("button",{type:"button",className:`${ye} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void I(N),children:[N.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:N.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:N.resultDisplay==="inline"&&K?`${N.label}: ${K}`:N.label})]},N.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:K?"var(--text-primary)":"var(--text-muted)"},children:[N.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:N.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:K?`${N.label}: ${K}`:N.label})]},N.id);default:return null}})]})})}function Qp({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:c,controls:l,controlValues:d}){const{isVisible:m}=fo(),u=bo(l,{hostIdeType:a,providerType:o});return!e||t||u.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(Jp,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:c,controls:u,controlValues:d})})}const Xs=5,al=10*1024*1024;function Zp({hasDraft:e,isBusy:t=!1}){return!e||t}function ef(e){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(e)})}async function tf(e){if(e.size>al)return null;const t=await ef(e),r=t.indexOf(",");if(r<0)return null;const n=t.slice(r+1);return{mimeType:e.type||"image/png",data:n,name:e.name,previewUrl:t}}function sf(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const ol=i.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:c,isActive:l=!0,showControlsToggle:d=!1,animateVisibility:m=!0,onControlsToggle:u,messageInput:f}){const b=i.useRef(null),v=i.useRef(null),[h,p]=i.useState(""),[g,y]=i.useState([]),[x,C]=i.useState(null),[S,w]=i.useState(!1),M=i.useRef(!1),{isVisible:L,toggleVisibility:j}=fo(),k=sf(f),B=!!h.trim()||g.length>0;i.useEffect(()=>{p(""),y([]),C(null)},[t]),i.useEffect(()=>{var N;l&&((N=b.current)==null||N.focus({preventScroll:!0}))},[t,l]);const _=i.useCallback(async N=>{C(null);const K=Array.from(N).filter(le=>le.type.startsWith("image/"));if(K.length===0)return;const P=Xs-g.length;if(P<=0){C(`Max ${Xs} images`);return}const E=K.slice(0,P);if(E.filter(le=>le.size>al).length>0){C("Image too large (max 10 MB)");return}const ye=(await Promise.all(E.map(tf))).filter(le=>le!==null);y(le=>[...le,...ye])},[g.length]),T=i.useCallback(N=>{y(K=>K.filter((P,E)=>E!==N))},[]),F=i.useCallback(async()=>{const N=h.trim();if(!N&&g.length===0||a||M.current)return;M.current=!0;const K=g.length>0?[...g]:void 0;try{await c(N,K)!==!1&&(p(""),y([]),C(null))}finally{M.current=!1}},[h,g,a,c]),H=i.useCallback(N=>{k&&(N.preventDefault(),w(!0))},[k]),R=i.useCallback(()=>w(!1),[]),I=i.useCallback(N=>{k&&(N.preventDefault(),w(!1),N.dataTransfer.files.length>0&&_(N.dataTransfer.files))},[k,_]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":"",S?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?200:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,onDragOver:H,onDragLeave:R,onDrop:I,children:[g.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:g.map((N,K)=>s.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[s.jsx("img",{src:N.previewUrl,alt:N.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>T(K),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-[10px] leading-none","aria-label":`Remove ${N.name}`,children:"✕"})]},K))}),s.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[d&&s.jsx("button",{type:"button",onClick:()=>{j(),u==null||u()},"aria-label":L?"Hide controls":"Show controls","aria-pressed":L,title:L?"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"})]})}),k&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:v,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:N=>{N.target.files&&_(N.target.files),N.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var N;return(N=v.current)==null?void 0:N.click()},disabled:g.length>=Xs,title:g.length>=Xs?`Max ${Xs} images`:"Attach image",className:"h-10 w-8 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 disabled:opacity-40","aria-label":"Attach image",children:s.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("input",{ref:b,type:"text",placeholder:o||(k&&g.length>0?"Add a message (optional)...":`Send message to ${r}...`),value:h,onChange:N=>p(N.target.value),onPaste:N=>{if(k&&N.clipboardData.files.length>0&&Array.from(N.clipboardData.files).some(E=>E.type.startsWith("image/"))){N.preventDefault(),_(N.clipboardData.files);return}const K=N.clipboardData.getData("text");K&&p(P=>P+K),N.preventDefault()},onKeyDown:N=>{if(N.key==="Enter"){if(N.nativeEvent.isComposing){N.preventDefault();return}N.preventDefault(),F()}},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:()=>{F()},disabled:Zp({hasDraft:B,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${B&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:B&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":"Send message",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:B?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),(x||k&&S)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${x?"text-red-400":"text-[var(--accent-primary)]"}`,children:x||"Drop image here"}),o&&!x&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})}),st=e=>e.transport==="pty",Us=(e,t)=>st(e)?e.mode||"terminal":"chat",il=(e,t)=>st(e)&&Us(e)==="terminal",Ze=e=>e.transport==="acp",rf=180;function Qt(e){return e.streamSource!=="agent-stream"}function ws(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function cl(e){return e.machineName||""}function kr(e){return ws(e)}function Kt(e){return e.agentType||""}function hn(e){return e.hostIdeType||""}function go(e){return e.displayPrimary||e.agentName||"Agent"}function ll(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function nf(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function dl(e){const t=nf(e),r=Ps(t==null?void 0:t.content),n=Ps(e.lastMessagePreview);return r||n||""}function af(e,t=rf){const r=Ps(e);if(!r||t<=0)return"";const n=Array.from(r);return n.length<=t?r:`${n.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function of(e){return af(dl(e)||e.displaySecondary||"")}function ul(e){return[e.displaySecondary,cl(e)].filter(Boolean)}function Es(e){return e.agentName||ot(Kt(e))}function cf(e){var t,r;if(!Qt(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return ot(hn(e)||Kt(e))}function ml(e){return Qt(e)?e.sessionId:e.nativeSessionId}function vi(e){return Qt(e)?"native":e.tabKey}function lf(e){return e.sessionId}function df(e,t){if(t)return Qt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function uf(e,t){const r=Kt(e),n=Qt(e),a=st(e)||Ze(e),o=n?a?Es(e)||(t==null?void 0:t.cliName)||ot(hn(e)||r):t!=null&&t.type?ot(t.type):ot(hn(e)||r):Es(e);return{isNativeConversation:n,isCli:st(e),isAcp:Ze(e),isCliTerminal:il(e),providerType:r,displayLabel:o,targetEntry:df(e,t)}}function is(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:st(e)||Ze(e)?{agentType:Kt(e)}:e.streamSource==="agent-stream"?{agentType:Kt(e)}:t}function $s(e){return e?kr(e):""}function Js(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function yo(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function mf(e){const t=e instanceof Error?e.message:String(e||""),r=t.toLowerCase();return r.includes("still processing the previous prompt")?"Wait for the current reply to finish before sending another message.":r.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":r.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":r.includes("not running")?"Runtime is not available right now.":t||"Unable to send message right now."}function pl(){return"select_session"}function pf(){return"open_panel"}function ff({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function hf(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function wi(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function xn(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function vo(e){return e instanceof Error?e.message:String(e||"")}function ji(e){const t=vo(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function ki(e,t){const r=vo(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function xf(e,t,r){const n=is(r);if(!t||t.length===0)return{message:e,...n};const a=t.map(o=>({type:"image",mimeType:o.mimeType,data:o.data,alt:o.name}));return e&&a.push({type:"text",text:e}),{message:e,input:{parts:a,textFallback:e},...n}}function Ln({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=i.useState(!1),[c,l]=i.useState(!1),[d,m]=i.useState(null),u=i.useRef(!1),f=i.useRef(null);i.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const b=i.useCallback(async(g,y)=>{if(!t||u.current)return!1;const x=g.trim(),C=yo(t);if(ff({hasMessage:!!x,blockedMessage:C,sendInFlight:u.current}))return C&&m(C),!1;const S=Date.now(),w={tabKey:t.tabKey,message:x,timestamp:S};if(hf(f.current,w))return m(null),!0;u.current=!0,l(!0),m(null),f.current=w;try{const M=$s(t);if(!M)return f.current=wi(f.current,w),m("Unable to send message right now."),!1;const L=await e(M,"send_chat",xf(x,y,t)),j=xn(L);if(j!=null&&j.deduplicated)return m(null),!0;if((j==null?void 0:j.sent)===!1)throw new Error((j==null?void 0:j.error)||"Send failed");if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Send failed");return m(null),!0}catch(M){const L=vo(M);return L.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",L):console.warn("Send blocked/failed",M),f.current=wi(f.current,w),m(mf(M)),!1}finally{u.current=!1,l(!1)}},[t,e]),v=i.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(g){console.error("Relaunch failed",g)}},[t,e]),h=i.useCallback(async g=>{if(t)try{const x=(t.modalButtons||[]).indexOf(g),C=g.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(C),w=$s(t);if(!w)return;const M=await e(w,"resolve_action",{button:g,action:S?"approve":"reject",...x>=0&&{buttonIndex:x},...is(t)}),L=xn(M);L.success||r(j=>[...j,{routeId:t.tabKey,text:ki(g,L==null?void 0:L.error),timestamp:Date.now()}])}catch(y){ji(y)||console.error("[ModalButton] Error:",y),r(x=>[...x,{routeId:t.tabKey,text:ji(y)?ki(g,y):`❌ **${g}** error`,timestamp:Date.now()}])}},[t,e,r]),p=i.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,pf(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(g){console.error("Focus agent failed",g)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:b,handleRelaunch:v,handleModalButton:h,handleFocusAgent:p}}const bf=10,gf=8e3,yf=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function vf(e){return e.replace(/(Authorization\s*:\s*Bearer\s+)[^\s'"`]+/gi,"$1[REDACTED:bearer]").replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]{12,}=*/gi,"$1[REDACTED:bearer]").replace(/\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]{20,}\b/g,"[REDACTED:github-token]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:api-key]").replace(/\b(?:adk|adm)_[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:adhdev-token]").replace(/((?:api[_-]?key|token|secret|password|passwd|client[_-]?secret)\s*[:=]\s*)[^\s,'"`}&]+/gi,"$1[REDACTED:secret]").replace(/([?&](?:api[_-]?key|token|secret|password|client_secret)=)[^&#\s]+/gi,"$1[REDACTED:secret]")}function Oa(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(yf.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=vf(e);return n.length>8e3?`${n.slice(0,8e3)}…[truncated ${n.length-8e3} chars]`:n}if(typeof e!="object")return String(e);if(r>=6)return"[MaxDepth]";if(Array.isArray(e)){const n=e.slice(-20).map(a=>Oa(a,t,r+1));return e.length>20?[{truncatedBefore:e.length-20},...n]:n}return Object.fromEntries(Object.entries(e).slice(0,80).map(([n,a])=>[n,Oa(a,n,r+1)]))}function Qs(e,t){return Array.isArray(e)?e.slice(-t):[]}function wf(e,t=Date.now()){const r=e&&t-e.firstAt<=gf,n=r?e.count+1:1;return n>=bf?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function fl(e){var n,a;const{activeConv:t}=e,r={version:1,createdAt:new Date(e.now??Date.now()).toISOString(),url:e.locationHref??(typeof window<"u"?window.location.href:void 0),activeConversation:{routeId:t.routeId,tabKey:t.tabKey,sessionId:t.sessionId,providerSessionId:t.providerSessionId,transport:t.transport,agentName:t.agentName,agentType:t.agentType,hostIdeType:t.hostIdeType,status:t.status,connectionState:t.connectionState,title:t.title,workspaceName:t.workspaceName,displayPrimary:t.displayPrimary,displaySecondary:t.displaySecondary,streamSource:t.streamSource,lastMessageHash:t.lastMessageHash},messageCounts:{live:((n=e.chatTailState.liveMessages)==null?void 0:n.length)??t.messages.length,activeConversation:t.messages.length,visible:e.visibleMessages.length,history:((a=e.chatTailState.historyMessages)==null?void 0:a.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:Qs(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:Qs(t.messages,10),visibleMessagesTail:Qs(e.visibleMessages,5),historyMessagesTail:Qs(e.chatTailState.historyMessages,5),actionLogsTail:Qs(e.actionLogs.filter(o=>o.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{hasLiveSnapshot:!!e.chatTailState.hasLiveSnapshot,hasMoreHistory:!!e.chatTailState.hasMoreHistory,historyError:e.chatTailState.historyError||null},ui:e.ui,browser:typeof navigator<"u"?{userAgent:navigator.userAgent,language:navigator.language,online:navigator.onLine}:null};return Oa(r)}function hl(e,t={}){const r=e&&typeof e=="object"?e:{},n=t.locatorCopyStatus??(t.locatorCopied===!1?"failed":"copied"),a=n==="copied"?"locator copied":n==="manual"?"locator shown for manual copy":"locator copy failed";return r.delivery==="daemon_file"?`Chat debug signal sent${typeof r.bundleId=="string"&&r.bundleId.trim()?` (${r.bundleId})`:""}; saved on daemon, ${a}.`:`Chat debug signal sent; ${a}.`}async function xl(e){var t;if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.writeText)&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(e),"copied"}catch(r){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",r)}if(typeof document<"u"&&document.body){let r=null;try{if(r=document.createElement("textarea"),r.value=e,r.setAttribute("readonly","true"),r.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(r),r.focus(),r.select(),document.execCommand("copy"))return"copied"}catch{}finally{r==null||r.remove()}}if(typeof window<"u"&&typeof window.prompt=="function")try{return window.prompt("Copy ADHDev chat debug locator:",e),"manual"}catch{}return"failed"}function bl(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const r=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&r.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&r.push("","warnings:",...t.warnings.map(n=>`- ${String(n)}`)),r.join(`
32
- `)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
33
-
34
- \`\`\`json
35
- ${JSON.stringify(t.bundle,null,2)}
36
- \`\`\``:`# ADHDev Chat Debug Bundle
37
-
38
- \`\`\`json
39
- ${JSON.stringify(t,null,2)}
40
- \`\`\``}function Yn(e,t){return`${e}:${t}`}function jf(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Zs(e,t){jf()&&console.debug(`[subscription-manager] ${e}`,t)}class kf{constructor(){Xe(this,"active",new Map);Xe(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var u;const c=Yn(n.topic,n.key),l=this.active.get(c);let d=!0;if(l)l.handlers.add(a),l.lastUpdate&&a(l.lastUpdate);else{const f={daemonId:r,request:n,handlers:new Set([a])};this.active.set(c,f),Zs("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(c,t,o.retryIntervalMs)}const m=()=>{var v;this.clearRetry(c);const f=this.active.get(c);if(!f||(f.handlers.delete(a),f.handlers.size>0))return;this.active.delete(c);const b={type:"unsubscribe",topic:n.topic,key:n.key};Zs("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(v=t.sendData)==null||v.call(t,r,b)};return m.initialSendAccepted=d,m}publish(t){const r=Yn(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,_s.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),_s.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=Yn(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;Zs("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(o=>o.daemonId===t);Zs("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(o=>({topic:o.request.topic,key:o.request.key}))});for(const o of n)(a=r.sendData)==null||a.call(r,o.daemonId,o.request)}scheduleRetry(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var l;this.retryTimers.delete(t);const o=this.active.get(t);if(!o)return;const c=((l=r.sendData)==null?void 0:l.call(r,o.daemonId,o.request))??!1;Zs("subscribe_retry",{id:t,accepted:c,topic:o.request.topic,key:o.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 Ut=new kf;function Sf(e,t){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===t&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker,settings:n.settings});for(const o of n.childSessions||[]){if(!(o!=null&&o.id))continue;const c=r.get(o.id)||{};r.set(o.id,{...c,...o})}}return r}function Nf(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 Xn(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function Cf(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function If(e){Cf()&&console.debug("[dashboard-conversations] statusPayloadToEntries",e.map(t=>({id:t.id,daemonId:t.daemonId,sessionId:t.sessionId,instanceId:t.instanceId,providerSessionId:t.providerSessionId,transport:t.transport,type:t.type})))}function bn(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:c}=t,l=c||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:m,childrenByParent:u}=Nf(d),f=Sf(o,n),b=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,v=m.filter(g=>g.kind==="workspace"&&g.transport==="cdp-page"),h=m.filter(g=>g.kind==="agent"&&g.transport==="pty"),p=m.filter(g=>g.kind==="agent"&&g.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...b&&{machine:b,platform:b.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:v.some(g=>!!g.cdpConnected)});for(const g of v){const y=f.get(g.id),x=or(g,y),C=(u.get(g.id)||[]).map(S=>or(S,f.get(S.id)));r.push({id:`${n}:ide:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,status:x.cdpConnected?"online":"detected",daemonId:n,instanceId:Xn(n,g.id),workspace:x.workspace,terminals:0,childSessions:C,agents:C.map(S=>({id:S.id,name:S.providerName||S.providerType,type:S.providerType,status:S.status})),activeChat:x.activeChat,chats:[],cdpConnected:x.cdpConnected,...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:l})}for(const g of h){const y=f.get(g.id),x=or(g,y);r.push({id:`${n}:cli:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:n,instanceId:Xn(n,g.id),cliName:x.providerName||x.providerType,mode:x.mode||(y==null?void 0:y.mode)||"terminal",workspace:x.workspace||"",activeChat:x.activeChat,...x.resume!==void 0&&{resume:x.resume},...x.runtimeKey!==void 0&&{runtimeKey:x.runtimeKey},...x.runtimeDisplayName!==void 0&&{runtimeDisplayName:x.runtimeDisplayName},...x.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:x.runtimeWorkspaceLabel},...x.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:x.runtimeWriteOwner},...x.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:x.runtimeAttachedClients},...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:l,_isCli:!0})}for(const g of p){const y=f.get(g.id),x=or(g,y);r.push({id:`${n}:acp:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:n,instanceId:Xn(n,g.id),cliName:x.providerName||x.providerType,mode:"chat",workspace:x.workspace||"",activeChat:x.activeChat,...x.runtimeKey!==void 0&&{runtimeKey:x.runtimeKey},...x.runtimeDisplayName!==void 0&&{runtimeDisplayName:x.runtimeDisplayName},...x.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:x.runtimeWorkspaceLabel},...x.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:x.runtimeWriteOwner},...x.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:x.runtimeAttachedClients},...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:l,_isAcp:!0})}return If(r),r}const Tf=15e3,Mf=15e3,Af=6e4,Lf=1200,Si=12,Rf=8e3,_f=4e3,Jn=new Map,Qn=new Map,Or=new Set,ur=new Map;function Pf(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 Ni(e,t){const r=ur.get(e);!r||r.size===0||(ur.delete(e),r.forEach(n=>n(t)))}function Df(e,t){return new Promise(r=>{const n=ur.get(e)||new Set;ur.set(e,n);const a=c=>{clearTimeout(o),n.delete(a),n.size===0&&ur.delete(e),r(c)},o=setTimeout(()=>a(!1),t);n.add(a)})}function Sr(){const{sendCommand:e,sendData:t}=yt(),{injectEntries:r,getIdes:n}=br();return i.useCallback(async(a,o)=>{if(!a)return;const c=(o==null?void 0:o.minFreshMs)??Af,l=Qn.get(a)||0;if(!(o!=null&&o.force)&&Or.has(a)&&l>0||!(o!=null&&o.force)&&l>0&&Date.now()-l<c)return;const d=Jn.get(a);if(d)return d;const m=(async()=>{if(t&&!Or.has(a)){const p=Ut.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},g=>{const y=n(),x=y.find(S=>S.id===a),C=bn(g.status,{daemonId:a,existingDaemon:x,existingEntries:y,timestamp:g.timestamp});C.length>0&&r(C),Qn.set(a,Date.now()),Ni(a,!0)});if(p.initialSendAccepted?Or.add(a):Or.delete(a),!(o!=null&&o.force)&&p.initialSendAccepted&&await Df(a,Lf))return}const u=await e(a,"get_status_metadata"),f=Pf(u);if(!f)return;const b=n(),v=b.find(p=>p.id===a),h=bn(f,{daemonId:a,existingDaemon:v,existingEntries:b,timestamp:f.timestamp||Date.now()});h.length>0&&r(h,{authoritativeDaemonIds:[a]}),Qn.set(a,Date.now()),Ni(a,!0)})().finally(()=>{Jn.delete(a)});return Jn.set(a,m),m},[n,r,e,t])}function Ef(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const $f=60,Bf=50;function gl(e={}){return e.isCliLike?Bf:$f}function Of(e={}){return gl(e)}function St(e){return(typeof e=="string"?e.trim():"")||void 0}function Ht(e,t){const r=St(t);return r?`${e}:${r}`:void 0}function Xt(e,t,r){const n=Ht(t,r),a=St(r);n&&e.push(n),a&&e.push(a)}function Ts(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function yl(e){return St(e.providerSessionId)||St(e.sessionId)||St(e.tabKey)||St(e.routeId)}function wo(e){return Ts([St(e.providerSessionId),St(e.sessionId)])}function Rs(e){const t=[];return Xt(t,"provider",e.providerSessionId),Xt(t,"session",e.sessionId),Xt(t,"tab",e.tabKey),Xt(t,"route",e.routeId),Ts(t)}function Kf(e){const t=[];return St(e.providerSessionId)?(Xt(t,"provider",e.providerSessionId),Ts(t)):St(e.sessionId)?(Xt(t,"session",e.sessionId),Ts(t)):St(e.tabKey)?(Xt(t,"tab",e.tabKey),Ts(t)):St(e.routeId)?(Xt(t,"route",e.routeId),Ts(t)):[]}function jo(e){return Ht("provider",e.providerSessionId)||Ht("session",e.sessionId)||Ht("tab",e.tabKey)||Ht("route",e.routeId)||"unknown:"}function Nr(e){return wo(e)[0]}function Ff(e){const t=St(e.providerSessionId),r=St(e.sessionId),n=St(e.tabKey),a=St(e.routeId),o=[Ht("provider",t),Ht("session",r),Ht("tab",n),Ht("route",a)].filter(d=>typeof d=="string"),c=Rs({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=jo({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:yl({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:Nr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:c}}function Ka(e,t){const r=Ff(e);return Kf(t).some(n=>r.lookupKeys.includes(n))}const Cr=60,Wf=1e3,ko=12e4,Hf=new Set(["generating","waiting_approval","starting","streaming","working"]),Ci=new Map;function vl(e,t){return`${e}::${t}`}function Fa(e=Cr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:Uf([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Uf(e,t=Cr){return{tailLimit:t}}function Ii(e,t){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}class zf{constructor(t){Xe(this,"manager");Xe(this,"sendData");Xe(this,"daemonId");Xe(this,"sessionId");Xe(this,"historySessionId");Xe(this,"subscriptionKey");Xe(this,"fallbackRecentCount");Xe(this,"snapshot");Xe(this,"transportSubscription",null);Xe(this,"listeners",new Set);Xe(this,"retainCount",0);Xe(this,"loadHistoryPromise",null);Xe(this,"pendingDisconnectTimer",null);this.manager=t.manager||Ut,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.snapshot=Fa(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.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount)),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}}getSnapshot(){return this.snapshot}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=this.snapshot.hasLiveSnapshot,a=n?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),o=await t({offset:this.snapshot.historyOffset,excludeRecentCount:a}),c=Array.isArray(o.messages)?o.messages:[],l=!n&&c.length===0&&o.hasMore!==!0&&this.fallbackRecentCount>0;this.snapshot={...this.snapshot,historyMessages:[...c,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+c.length,hasMoreHistory:l?!0:o.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:Wf}))}disconnect(){var t;(t=this.transportSubscription)==null||t.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return;const r=Array.isArray(t.messages)?t.messages:[],n={tailLimit:this.snapshot.cursor.tailLimit};Ii(this.snapshot.liveMessages)===Ii(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,hasLiveSnapshot:!0,cursor:n},this.emit())}}function wl(e){const t=vl(e.daemonId,e.sessionId),r=Ci.get(t);if(r)return r.updateOptions(e),r;const n=new zf(e);return Ci.set(t,n),n}function Vf(e,t){return{...e,loadHistoryPage:t}}function Gf(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function qf(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Hf.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??ko)),o=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return o>0?n-o<=a:Array.isArray(e.messages)&&e.messages.length>0}function Yf(e=ko){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Xf(e,t={}){const r=new Set,n=[];for(const a of e){if(!qf(a,t))continue;const o=kr(a),c=a.sessionId||"";if(!o||!c)continue;const l=vl(o,c);if(r.has(l))continue;r.add(l);const d=Nr(a);n.push({daemonId:o,sessionId:c,historySessionId:d||c,subscriptionKey:`daemon:${o}:session:${c}`})}return n.sort(Gf),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Jf(e,t){const{sendData:r,sendCommand:n}=yt(),a=(t==null?void 0:t.enabled)!==!1,o=kr(e),c=e.sessionId||"",l=Nr(e)||c,d=`daemon:${o}:session:${c}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??Cr),u=i.useMemo(()=>!a||!o||!c?null:wl({daemonId:o,sessionId:c,historySessionId:l,subscriptionKey:d,sendData:r,tailLimit:m,fallbackRecentCount:e.messages.length}),[e.messages.length,o,a,l,r,c,d,m]),[f,b]=i.useState(()=>(u==null?void 0:u.getSnapshot())||Fa(m));i.useEffect(()=>{if(!u){b(Fa(m));return}u.retain(),b(u.getSnapshot());const h=u.subscribe(p=>{b(p)});return()=>{h(),u.release()}},[u,m]);const v=i.useCallback(async()=>{!u||!o||!c||await u.loadHistoryPage(async({offset:h,excludeRecentCount:p})=>{const g=e.agentType,y=await n(o,"chat_history",{agentType:g,offset:h,limit:30,targetSessionId:c,historySessionId:l,excludeRecentCount:p}),x=y&&typeof y=="object"&&"result"in y?y.result||{}:y||{};return{messages:Array.isArray(x.messages)?x.messages:[],hasMore:x.hasMore===!0}})},[e.agentType,u,o,l,n,c]);return i.useMemo(()=>Vf(f,v),[v,f])}function Qf(e,t){const{sendData:r}=yt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??Cr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??ko)),c=Yf(o),[l,d]=i.useState(0);i.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(f=>f+1)},c);return()=>{clearInterval(u)}},[e.length,n,c]);const m=i.useMemo(()=>Xf(e,{recentActivityMs:o}),[e,o,l]);i.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(f=>wl({...f,sendData:r,tailLimit:a}));return u.forEach(f=>{f.retain()}),()=>{u.forEach(f=>f.release())}},[m.signature,n,r,a])}function Zf(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Ti(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const r=String(e.kind||"standard").toLowerCase();return r===""||r==="standard"}function eh(e,t){if(e.length===0)return[];if(t.some(Ti))return[];const r=[],n=new Set;for(let a=e.length-1;a>=0&&r.length<2;a-=1){const o=e[a];if(!o||!Ti(o))continue;const c=String(o.role||"").toLowerCase();n.has(c)||(n.add(c),r.unshift(o))}return r}function th(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),o=a>0?r.slice(0,a):[],c=a>0?r.slice(-n):r,l=eh(o,c),d=l.length>0?[...l,...c]:c;return t.length===0?d:[...t,...d]}function sh(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function rh(e){return sh(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function nh(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function ah(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function oh(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function jl(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function kl(e){const t=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return t||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function ih(e){return jl(e)?!1:e.inboxBucket==="task_complete"&&kl(e).length>0}function Mi(e){return e.branch||"detached HEAD"}function ch(e){if(e.error)return`${Mi(e)} · Git error: ${e.error}`;const t=[Mi(e)];return e.changedFiles>0?t.push(nh(e.changedFiles,"file")+" changed"):e.dirty||t.push("clean"),e.ahead>0&&t.push(`ahead ${e.ahead}`),e.behind>0&&t.push(`behind ${e.behind}`),e.hasConflicts&&t.push("conflicts"),t.join(" · ")}function lh(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${ch(t)}`}function dh(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function uh(e,t={}){if(t.enabled===!1)return[];if(!oh(e))return[];const r=jl(e)?"working":ih(e)?"complete":null;if(!r)return[];const n=r==="complete"?kl(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${ah(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:lh(r,e.git),timestamp:dh(e,e.git),meta:{source:"git-system-bubble",phase:r,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const mh=60;function Wa({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:o,isFocusingAgent:c,actionLogs:l,userName:d,scrollToBottomRequestNonce:m,isInputActive:u=!0,isVisible:f=!0}){var Se,Z,de,oe,me,ie,D;const b=i.useRef(new Map),v=i.useRef(void 0),h=Sr(),{sendCommand:p}=yt(),{isVisible:g}=fo();jr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const y=wt.useMemo(()=>Hs(e),[e.status,e.connectionState]),x=i.useMemo(()=>uf(e,t),[e,t]),C=i.useMemo(()=>{var z;return bo((z=x.targetEntry)==null?void 0:z.providerControls,{hostIdeType:e.hostIdeType,providerType:x.providerType})},[e.hostIdeType,x.providerType,(Se=x.targetEntry)==null?void 0:Se.providerControls]),S=gl({isCliLike:x.isCli||x.isAcp}),w=Of({isCliLike:x.isCli||x.isAcp}),M=Jf(e,{enabled:f&&!!e.sessionId,tailLimit:w}),[L,j]=i.useState(S),[k,B]=i.useState(()=>li()),_=e.tabKey,T=M.historyMessages,F=M.hasMoreHistory,H=M.historyError,R=Zf(e,M),I=Uc(R).length;i.useEffect(()=>{j(S)},[S,_]);const N=Math.max(0,R.length-L),K=go(e),P=kr(e),E=rh(e),U=yo(e),ee=a||U,ye=!!U,[le,Q]=i.useState(!1);i.useEffect(()=>{const z=x.targetEntry;P&&(!z||z.providerControls===void 0||z.controlValues===void 0)&&h(P,{minFreshMs:3e4}).catch(()=>{})},[P,x.isAcp,(Z=x.targetEntry)==null?void 0:Z.providerControls,(de=x.targetEntry)==null?void 0:de.controlValues,h]);const xe=i.useCallback(async()=>{if(!le){if(R.length>L){j(z=>Math.min(R.length,z+mh));return}Q(!0);try{await M.loadHistoryPage()}finally{Q(!1)}}},[M,le,R.length,L]),{allMessages:we,receivedAtMap:be}=i.useMemo(()=>{const z=th({historyMessages:T,liveMessages:R,visibleLiveCount:L}),ce=uh(e),re=ce.length>0?[...z,...ce]:z,G={};return re.forEach((je,ge)=>{const Ae=`${e.tabKey}:${un(je,ge)}`;let Me=Ef(je)||b.current.get(Ae)||0;Me||(Me=Date.now(),b.current.set(Ae,Me)),G[un(je,ge)]=Me}),{allMessages:re,receivedAtMap:G}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,N,T,R,L]),X=i.useMemo(()=>l.filter(z=>z.routeId===e.tabKey).sort((z,ce)=>z.timestamp-ce.timestamp),[l,e.tabKey]),ue=i.useCallback(async()=>{var ge,Ae;if(!P)return;const z=fl({activeConv:e,visibleMessages:we,actionLogs:l,controls:(ge=x.targetEntry)==null?void 0:ge.providerControls,controlValues:(Ae=x.targetEntry)==null?void 0:Ae.controlValues,visibleBarControlCount:C.length,chatTailState:{liveMessages:M.liveMessages,hasLiveSnapshot:M.hasLiveSnapshot,hasMoreHistory:F,historyError:H,historyMessages:T},ui:{controlsVisible:g,visibleLiveCount:L,activityVisible:k,activityCount:I,hiddenLiveCount:N,isInputActive:u,isVisible:f}}),ce=await p(P,"get_chat_debug_bundle",{agentType:x.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:z}),re=xn(ce),G=bl(re),je=await xl(G);je==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),nt.showToast(hl(re,{locatorCopyStatus:je}),je==="failed"?"warning":"success")},[e,l,I,we,g,M.hasLiveSnapshot,M.liveMessages,x.providerType,(oe=x.targetEntry)==null?void 0:oe.controlValues,(me=x.targetEntry)==null?void 0:me.providerControls,P,F,N,T,u,f,H,p,k,C.length,L]),fe=i.useCallback(()=>{B(z=>{const ce=!z;return Pm(ce),ce})},[]);i.useEffect(()=>{const z=ce=>{ce.key===lo&&B(li())};return window.addEventListener("storage",z),()=>window.removeEventListener("storage",z)},[]);const ve=i.useCallback(()=>{const z=wf(v.current);v.current=z.state,z.shouldCollect&&ue().catch(ce=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",ce),nt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[ue]),pe=i.useMemo(()=>{if(R.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((y.isGenerating||e.status==="streaming")&&Q(!1),e.status==="not_monitored"&&E)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(Ds,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:o,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xs,{size:14})," Open ",K," 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"&&E)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(Kc,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:o,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xs,{size:14})," Open ",K," 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"&&!le)return!F&&T.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"No messages yet"})]}):s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,E,o,F,T.length,c,le,R.length,K,y.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[s.jsx("div",{className:"chat-activity-toggle-bar",children:s.jsxs("button",{type:"button",className:`chat-activity-toggle ${k?"chat-activity-toggle-active":""}`,onClick:fe,"aria-pressed":k,title:"Show tool, terminal, and runtime activity rows",children:[s.jsx("span",{className:"chat-activity-toggle-dot"}),"Activity",I>0&&s.jsx("span",{className:"chat-activity-toggle-count",children:I})]})}),s.jsx(Ym,{messages:we,actionLogs:X,agentName:Es(e)||K||"Agent",userName:d,isCliMode:x.isCli||x.isAcp,isWorking:y.isGenerating,contextKey:e.tabKey,receivedAtMap:be,lastMessageHash:e.lastMessageHash,showActivityMessages:k,onLoadMore:xe,isLoadingMore:le,hasMoreHistory:F,hiddenLiveCount:N,loadError:H??void 0,emptyState:pe,scrollToBottomRequestNonce:m,isVisible:f}),s.jsx(Qp,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:x.providerType,displayLabel:x.displayLabel,controls:(ie=x.targetEntry)==null?void 0:ie.providerControls,controlValues:(D=x.targetEntry)==null?void 0:D.controlValues,isActive:u,isCliTerminal:x.isCliTerminal}),!x.isCliTerminal&&s.jsx(ol,{contextKey:e.tabKey,panelLabel:K,isSending:n,isBusy:ye,statusMessage:ee,onSend:r,isActive:u,showControlsToggle:C.length>0,onControlsToggle:ve,messageInput:e.messageInput})]})}let Sl=es;function Nl(){return Sl()}class ph{constructor(){Xe(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 Cl=new ph;class fh{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 fh;function hh(e){e.dashboardWS&&(Cl=e.dashboardWS),e.connectionManager&&(lt=e.connectionManager),e.useDaemonsHook&&(Sl=e.useDaemonsHook)}const xh=.5,bh=1.25;function ct(e){return go(e)}function gs(e){return ul(e).join(" · ")}function Il(e){const t=dl(e);return t||(e.title?e.title:gs(e)||"No messages yet")}function Tl(e,t){const{isReconnecting:r,isConnecting:n}=Hs(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function gh(e,t){const r=["Chat",...ul(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function cs(e){return Tl(e)||gs(e)}function yh(e){return`${ct(e)} · ${Il(e)}`}function vh(e){const t=hn(e),r=t?ot(t):Es(e);return`${ct(e)} — ${r||"Agent"}`}function wh(e){return Es(e)||"CLI"}function Ml(e){return ll(e)}function Al(e){return e?`Remote · ${ct(e)||e.workspaceName||"Session"}`:"Remote"}function jh({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:c=!0,isInputActive:l=!0}){var ne;es();const{sendPtyInput:d}=yt(),[m,u]=i.useState(!1),f=i.useRef(!1);f.current=m;const[b,v]=i.useState("Runtime terminal unavailable"),[h,p]=i.useState(!1),[g,y]=i.useState(null),[x,C]=i.useState(!1),[S,w]=i.useState(!1),[M,L]=i.useState(1),[j,k]=i.useState(!1),[B,_]=i.useState({width:0,height:0}),[T,F]=i.useState({width:0,height:0}),[H,R]=i.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[I,N]=i.useState(null),K=i.useRef(null),P=i.useRef(null),E=i.useRef(!1),U=i.useRef(!1),ee=i.useRef(c),ye=i.useRef(0),le=i.useRef(!1),Q=i.useRef(""),xe=i.useRef(null),we=i.useRef(!1),be=i.useRef(!1),X=i.useRef(null),ue=i.useRef(null),fe=i.useRef(null),ve=32*1024,pe=()=>{var $,q,se,ae;return((q=($=K.current)==null?void 0:$.ownerDocument)==null?void 0:q.defaultView)||((ae=(se=P.current)==null?void 0:se.ownerDocument)==null?void 0:ae.defaultView)||window},Se=$=>{const q=pe();return{ownerWindow:q,frameId:q.requestAnimationFrame($)}},Z=()=>{const $=X.current;if($){try{$.ownerWindow.cancelAnimationFrame($.frameId)}catch{}X.current=null}},de=()=>{const $=ue.current;if($){try{$.ownerWindow.clearTimeout($.timeoutId)}catch{}ue.current=null}},oe=()=>{const $=fe.current;if($){try{$.ownerWindow.clearTimeout($.timeoutId)}catch{}fe.current=null}},me=()=>{c&&X.current===null&&(X.current=Se(()=>{et()}))},ie=e.tabKey,D=e.sessionId||"",z=e.daemonId||((ne=e.routeId)==null?void 0:ne.split(":")[0])||e.routeId||"",ce=yo(e),re=m?o||ce:b,G=xh,je=bh,ge=.05,Ae=()=>{const $=T.width,q=T.height;if(!Number.isFinite(B.width)||B.width<=0||!Number.isFinite(B.height)||B.height<=0||!Number.isFinite($)||$<=0||!Number.isFinite(q)||q<=0)return 1;const se=B.width/$,ae=B.height/q;return Number(Math.min(je,Math.max(G,Math.min(se,ae))).toFixed(2))},Me=Ae(),O=E.current&&M>Me,Ne=Number.isFinite(T.width)&&T.width>0?Math.max(B.width,Math.round(T.width*M)):B.width,Re=Number.isFinite(T.height)&&T.height>0?Math.max(B.height,Math.round(T.height*M)):B.height,Fe=()=>{Se(()=>{const $=P.current;$&&($.scrollLeft=0,$.scrollTop=$.scrollHeight-$.clientHeight)})},He=()=>{var $,q;ye.current=0,le.current=!1,Q.current="",xe.current=null,we.current=!1,be.current=!1,E.current||(U.current=!1,L(1)),X.current!==null&&Z(),u(!1),v("Runtime terminal unavailable"),oe(),de(),y(null),N(null),k(!1),p(!1),C(!1),w(!1),(q=($=r.current)==null?void 0:$.reset)==null||q.call($)},Ge=()=>{var $,q;ye.current=0,le.current=!1,Q.current="",xe.current=null,we.current=!1,be.current=!1,X.current!==null&&Z(),u(!0),v(""),oe(),de(),y(null),N(null),k(!1),p(!1),C(!1),w(!1),(q=($=r.current)==null?void 0:$.reset)==null||q.call($)},qe=()=>{be.current&&(be.current=!1,Se(()=>{var $,q;(q=($=r.current)==null?void 0:$.scrollToTop)==null||q.call($)}))},et=()=>{if(X.current=null,!c)return;const $=Q.current;if(!$)return;const q=$.slice(0,ve);Q.current=$.slice(q.length);const se=r.current;if(!se){Q.current=q+Q.current,me();return}se.write(q,()=>{if(Q.current.length>0){me();return}qe()})},dt=$=>{$&&(Q.current+=$,me())},pt=($,q=0,se,ae,ke={})=>{var De,Te,Ee,Oe;const _e=!!ke.force;!_e&&q>0&&ye.current>=q||!_e&&q===0&&le.current||(ye.current=q,q>0&&C(!0),u(!0),v(""),typeof se=="number"&&typeof ae=="number"&&se>0&&ae>0&&((Te=(De=r.current)==null?void 0:De.resize)==null||Te.call(De,se,ae)),Q.current="",(Oe=(Ee=r.current)==null?void 0:Ee.reset)==null||Oe.call(Ee),$?dt($):qe())};i.useEffect(()=>{He()},[D]),i.useEffect(()=>{var q;if(!D)return;const $=((q=lt.onRuntimeEvent)==null?void 0:q.call(lt,D,se=>{if(!(!se||se.sessionId!==D)){if(se.type==="runtime_snapshot"){if(!c){xe.current={text:se.text||"",seq:se.seq||0,cols:se.cols,rows:se.rows,force:!!se.force};return}pt(se.text||"",se.seq||0,se.cols,se.rows,{force:!!se.force});return}if(se.type==="session_output"){le.current=!0,typeof se.seq=="number"&&(ye.current=Math.max(ye.current,se.seq),se.seq>0&&C(!0)),f.current||u(!0),f.current||v(""),typeof se.data=="string"&&dt(se.data);return}if(se.type==="session_cleared"){if(!c){we.current=!0,Q.current="",xe.current=null;return}Ge();return}if(se.type==="session_io_error"){const ae=typeof se.error=="string"&&se.error?se.error:typeof se.reason=="string"&&se.reason?se.reason:"unknown error";u(!1),v(`Runtime input failed: ${ae}`);return}}},z))||(()=>{});return()=>{$()}},[z,D,r,c]);const bt=async($={})=>{var q;if(!z||!D)return{success:!1,error:"daemonId and sessionId are required"};$.preserveStatus||v($.loadingMessage||"Loading runtime terminal...");try{const se=await((q=lt.requestRuntimeSnapshot)==null?void 0:q.call(lt,z,D,{sinceSeq:$.sinceSeq,force:$.force}));return se&&se.success===!1?($.preserveStatus||(u(!1),v(`Runtime terminal unavailable: ${se.error}`)),se):se||{success:!0}}catch(se){const ae=(se==null?void 0:se.message)||String(se);return $.preserveStatus||(u(!1),v(`Runtime terminal unavailable: ${ae}`)),{success:!1,error:ae}}},Ce=async $=>{var _e,De;const q=((_e=K.current)==null?void 0:_e.ownerDocument)||document,se=q.defaultView||window,ae=(De=se.navigator)==null?void 0:De.clipboard;if(ae!=null&&ae.writeText&&se.isSecureContext)try{return await ae.writeText($),!0}catch{}let ke=null;try{return ke=q.createElement("textarea"),ke.value=$,ke.setAttribute("readonly","true"),ke.style.position="fixed",ke.style.left="-9999px",ke.style.top="0",q.body.appendChild(ke),ke.focus(),ke.select(),q.execCommand("copy")}catch{return!1}finally{ke==null||ke.remove()}},Ue=$=>{de(),N($);const q=pe();ue.current={ownerWindow:q,timeoutId:q.setTimeout(()=>{ue.current=null,N(se=>se===$?null:se)},2200)}},Qe=$=>{oe(),y($);const q=pe();fe.current={ownerWindow:q,timeoutId:q.setTimeout(()=>{fe.current=null,y(se=>se===$?null:se)},2200)}},ze=async()=>{var ke,_e,De,Te;const $=((_e=(ke=r.current)==null?void 0:ke.getSelection)==null?void 0:_e.call(ke))||"",q=((Te=(De=r.current)==null?void 0:De.getVisibleText)==null?void 0:Te.call(De))||"",se=$.trimEnd()||q.trimEnd();if(!se){Ue("Nothing to copy");return}if(!await Ce(se)){Ue("Copy failed");return}Ue($.trimEnd()?"Copied selection":"Copied visible terminal")},rt=$=>{if(!m||!c)return;((d==null?void 0:d(z,D,$))??!1)||Ue("Terminal input failed")},W=async()=>{if(h)return;p(!0),y("Loading older terminal output..."),be.current=!0;const $=await bt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),($==null?void 0:$.success)===!1){be.current=!1,y(`Older terminal output unavailable: ${$.error}`);return}w(!0),Qe("Older terminal output loaded"),Se(()=>{var q;(q=r.current)==null||q.bumpResize()})};i.useEffect(()=>{var q,se;if(!D)return;z&&((q=lt.getState)==null?void 0:q.call(lt,z))==="connected"&&bt();const $=(se=lt.onStateChange)==null?void 0:se.call(lt,(ae,ke)=>{ae!==z||ke!=="connected"||bt()});return()=>{$==null||$()}},[z,D,r]),i.useEffect(()=>{t&&He()},[t,ie,r]),i.useEffect(()=>{var ae,ke;const $=K.current,q=(ke=(ae=$==null?void 0:$.ownerDocument)==null?void 0:ae.defaultView)==null?void 0:ke.ResizeObserver;if(!$||!q)return;const se=new q(_e=>{const De=_e[0];if(!De)return;const{width:Te,height:Ee}=De.contentRect;_(Oe=>{const Ie=Math.round(Te),Ye=Math.round(Ee);return Oe.width===Ie&&Oe.height===Ye?Oe:{width:Ie,height:Ye}})});return se.observe($),()=>se.disconnect()},[]),i.useEffect(()=>{if(E.current)return;const $=Ae();!Number.isFinite($)||$<=0||L(q=>U.current?$<q-ge?$:q:(U.current=!0,$))},[T.height,T.width,B.height,B.width]),i.useEffect(()=>{O&&Fe()},[O,Re,Ne]),i.useEffect(()=>{var se;const $=ee.current;if(ee.current=c,!c)return;$||w(!1),we.current&&(we.current=!1,Ge());const q=xe.current;q&&(xe.current=null,pt(q.text,q.seq,q.cols,q.rows,{force:!!q.force})),z&&D&&((se=lt.getState)==null?void 0:se.call(lt,z))==="connected"&&bt(),Q.current&&X.current===null&&me(),Se(()=>{var ae;(ae=r.current)==null||ae.bumpResize()})},[z,c,D]),i.useEffect(()=>()=>{X.current!==null&&Z(),de(),oe()},[]),i.useEffect(()=>{const $=ae=>{var _e;const ke=ae.detail;ke!=null&&ke.sessionId&&ke.sessionId!==D||m&&((_e=r.current)==null||_e.bumpResize())},q=pe(),se=q===window?[window]:[window,q];for(const ae of se)ae.addEventListener("adhdev:fit-cli-terminal",$);return()=>{for(const ae of se)ae.removeEventListener("adhdev:fit-cli-terminal",$)}},[m,D,r]);const J=m&&x&&!S&&(H.atTop||!H.canScroll)||h||!!g;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:K,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[J&&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:()=>{W()},disabled:!D||h,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:h?"Loading older...":"Load older terminal output"}),g&&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:g})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[I&&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:I}),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:()=>{ze()},disabled:!m,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>k($=>!$),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":j,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),j&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":"Terminal control keys",className:"absolute right-0 top-10 w-56 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>k(!1),"aria-label":"Close terminal control keys",children:"×"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt("\x1B"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt(" "),children:"Tab"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt("\r"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt("\x1B[A"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt("\x1B[D"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt("\x1B[B"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt("\x1B[C"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt(""),children:"Ctrl-C"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt(""),children:"Ctrl-D"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>rt(""),children:"Bksp"})]})]})]}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{E.current=!0,L($=>{const q=Math.max(Me,Number(($-.1).toFixed(2)));return q>Me&&Fe(),q})},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:()=>{E.current=!0,L($=>{const q=Math.min(je,Number(($+.1).toFixed(2)));return q>Me&&Fe(),q})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:P,className:O?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:Ne>0?`${Ne}px`:"100%",height:Re>0?`${Re}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:T.width>0?`${T.width}px`:"100%",height:T.height>0?`${T.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:M},children:s.jsx(Yc,{ref:r,readOnly:!m||!c,sizingMode:"measured",onViewportMetrics:F,onScrollMetrics:R,onInput:$=>{!m||(d==null||d(z,D,$))}})})})}),!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:b})]}),s.jsx(ol,{contextKey:e.tabKey,panelLabel:ct(e),isSending:a,isBusy:!!ce,statusMessage:re,onSend:async $=>ce?!1:n($),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const kh=5e3,Sh=12e3;function Nh(e){return e==="disconnected"||e==="reconnecting"}function Ch({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=kh,reconnectActionDelayMs:o=Sh}){const c=Nh(e),[l,d]=i.useState(()=>!c||a<=0),[m,u]=i.useState(()=>!c||o<=0),f=i.useRef(!1);i.useEffect(()=>{if(!c){d(!1);return}if(f.current=!1,a<=0){f.current=!0,d(!0);return}d(!1);const w=setTimeout(()=>{f.current=!0,d(!0)},a);return()=>clearTimeout(w)},[a,c]),i.useEffect(()=>{if(!c){u(!1);return}if(o<=0){u(!0);return}u(!1);const w=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(w)},[o,c]);const b=c?l:e==="offline"||e==="auth_failed",v=!!(n&&e!=="auth_failed"&&(!c||m)),h=i.useMemo(()=>!t||e!=="connected"?!1:a<=0||f.current,[a,t,e]),p=e==="auth_failed"?"red":e==="offline"?"orange":"accent",g={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))"},y={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)"},x={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},C="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",S={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[b&&s.jsx("div",{className:C,style:S,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:g[p],border:y[p],color:x[p]},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.")]}),v&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>n==null?void 0:n(),disabled:e==="offline",children:"Reconnect now"})]})}),h&&s.jsx("div",{className:C,style:S,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function Ih({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=i.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[o,c]=i.useState(!1);if(i.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!t||!e||e.backend!=="xterm"||o)return null;const l=(r==null?void 0:r.trim())||"This machine",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!0)};return s.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[l," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:d,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function So({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(io,{size:n}):s.jsx(zt,{size:n})})}const Bt="New session",Ll="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 Th(e){if(!e||e.isGitRepo===!1||e.reason==="not_git_repo")return null;if(e.hasConflicts)return`${e.branch||"Git"} · conflicts${e.changedFiles>0?` ${e.changedFiles}`:""}`;const t=[e.branch||"Git"];return e.changedFiles>0&&t.push(`±${e.changedFiles}`),e.ahead>0&&t.push(`↑${e.ahead}`),e.behind>0&&t.push(`↓${e.behind}`),t.length===1&&e.dirty&&t.push("dirty"),t.join(" ")}function Mh(e){return!e||e.isGitRepo===!1||e.reason==="not_git_repo"?null:e.hasConflicts?"conflict":e.error?"error":e.dirty||e.changedFiles>0||e.ahead>0||e.behind>0?"dirty":"quiet"}function Ah(e){switch(e){case"conflict":return"border-red-500/25 bg-red-500/[0.08] text-red-400";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-emerald-500/15 bg-emerald-500/[0.06] text-emerald-500"}}function Bs({git:e,className:t="",compact:r=!1}){const n=Th(e),a=Mh(e);if(!n||!a)return null;const o=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${Ah(a)} ${t}`.trim(),title:o.join(" · ")||n,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:n})]})}function Lh({wsStatus:e,isConnected:t,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),o=a.filter(l=>l==="connected").length,c=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&c>0&&o===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 Ai({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Li({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const c=In(e.updatedAt),l=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),o()},children:"Delete"})]})]})}function Rh({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:f,onShowAllHidden:b,onResetPanelsToMain:v,inboxOpen:h,onInboxOpenChange:p,hiddenOpen:g,onHiddenOpenChange:y,onOpenNewSession:x,onOpenDashboardGuide:C,guideNudgeVisible:S=!1,actionShortcuts:w,notifications:M,notificationUnreadCount:L,onOpenNotification:j,onMarkNotificationRead:k,onMarkNotificationUnread:B,onDeleteNotification:_,onOpenGitDialog:T,onOpenMeshGraph:F}){var Se;const{ides:H,p2pStates:R={}}=es(),I=!!e&&st(e)&&!Ze(e),N=!!e&&Ze(e),K=!!(e!=null&&e.daemonId)&&typeof((Se=e==null?void 0:e.settings)==null?void 0:Se.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.length>0,P=l||(e?il(e)?"terminal":"chat":null),[E,U]=i.useState(!1),ee=i.useRef(null),ye=i.useRef(null),le=H.filter(Z=>Z.type==="adhdev-daemon"),Q=Lh({wsStatus:t,isConnected:r,daemonCount:le.length,p2pStates:R}),xe=Q.subtitle,we=Q.tone==="connected"?"#22c55e":Q.tone==="limited"?"#eab308":"#ef4444",be=Q.tone==="connected"?"0 0 4px #22c55e80":Q.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",X=i.useMemo(()=>M.filter(Z=>!Z.readAt),[M]),ue=i.useMemo(()=>M.filter(Z=>!!Z.readAt),[M]),fe=i.useMemo(()=>X.slice(0,9),[X]),ve=L;i.useEffect(()=>{if(!h)return;const Z=de=>{var oe;(oe=ee.current)!=null&&oe.contains(de.target)||p(!1)};return document.addEventListener("mousedown",Z),()=>document.removeEventListener("mousedown",Z)},[h,p]),i.useEffect(()=>{if(!g)return;const Z=de=>{var oe;(oe=ye.current)!=null&&oe.contains(de.target)||y(!1)};return document.addEventListener("mousedown",Z),()=>document.removeEventListener("mousedown",Z)},[g,y]),i.useEffect(()=>{if(!g&&!h)return;const Z=de=>{if(!de.altKey)return;const oe=de.code.match(/^Digit([1-9])$/);if(!oe)return;const me=Number(oe[1])-1,ie=g?u[me]:void 0,D=h?fe[me]:void 0;if(!(!ie&&!D)){if(de.preventDefault(),de.stopPropagation(),ie){f==null||f(ie),y(!1);return}D&&(j(D),p(!1))}};return window.addEventListener("keydown",Z,!0),()=>window.removeEventListener("keydown",Z,!0)},[u,g,h,fe,y,p,j,f]);const pe=Z=>{if(!Z)return;const de=n.find(oe=>oe.tabKey===Z);de&&(m==null||m(de))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(zt,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?ct(e):"Dashboard"}),s.jsx("span",{title:Q.title,"aria-label":Q.title,className:"header-title-status-dot",style:{background:we,boxShadow:be}}),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:we,boxShadow:be}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[xe&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",xe]}),x&&s.jsx("button",{type:"button",onClick:x,className:"btn btn-secondary btn-sm ml-2",title:`${Bt}${w!=null&&w.openNewSession?` (${w.openNewSession})`:""}`,"aria-label":Bt,children:s.jsx(Wc,{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:"?"}),S&&s.jsx("span",{children:"Guide"})]}),e&&(I||N||!Ze(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:gs(e)||ct(e),children:ct(e)}),T&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>T(e.daemonId,e.workspacePath),children:s.jsx(Bs,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Bs,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),K&&F&&s.jsxs("button",{type:"button",onClick:()=>F(e),className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",title:"Open live repo mesh graph",children:[s.jsx(Is,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(I||N)&&c&&s.jsxs(s.Fragment,{children:[I&&d&&P&&s.jsx(So,{mode:P,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:N?"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(gt,{size:14})})]}),!Ze(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(ao,{size:14})}),!I&&!Ze(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(It,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:ee,children:[s.jsxs("div",{className:`dashboard-header-hidden${E?" is-drop-target":""}`,ref:ye,onDragEnter:Z=>{Z.dataTransfer.types.includes("text/tab-key")&&(Z.preventDefault(),U(!0))},onDragOver:Z=>{Z.dataTransfer.types.includes("text/tab-key")&&(Z.preventDefault(),Z.dataTransfer.dropEffect="move",U(!0))},onDragLeave:Z=>{Z.currentTarget.contains(Z.relatedTarget)||U(!1)},onDrop:Z=>{const de=Z.dataTransfer.getData("text/tab-key");Z.preventDefault(),U(!1),pe(de)},children:[s.jsxs("button",{type:"button",onClick:()=>y(!g),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${w!=null&&w.toggleHiddenTabs?` (${w.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(oo,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),g&&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(Ai,{value:w==null?void 0:w.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[v&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:v,children:"Reset panels"}),u.length>0&&b&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{b(),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(Ai,{value:w==null?void 0:w.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:ct(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(Z=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{f==null||f(Z),y(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:ct(Z)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(Z)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(Z)+1]}):null,gs(Z)]})]},Z.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!h),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Cn,{size:16}),ve>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ve})]}),h&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[X.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),X.map(Z=>s.jsx(Li,{notification:Z,shortcutIndex:fe.indexOf(Z)>=0?fe.indexOf(Z)+1:void 0,onOpen:()=>j(Z),onMarkRead:()=>k(Z.id),onMarkUnread:()=>B(Z.id),onDelete:()=>_(Z.id)},Z.id))]}),ue.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),ue.map(Z=>s.jsx(Li,{notification:Z,onOpen:()=>j(Z),onMarkRead:()=>k(Z.id),onMarkUnread:()=>B(Z.id),onDelete:()=>_(Z.id)},Z.id))]}),M.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function jt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function _h(e,t){return String(e||"")!==String(t||"")}function Ph(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!r&&!n&&!a&&!o?e:e.filter(c=>!(o&&!c.canResume||r&&![c.title,c.preview].map(d=>String(d||"").toLowerCase()).join(`
41
- `).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!el(c.summaryMetadata).map(d=>d.toLowerCase()).join(`
42
- `).includes(a)))}function Dh(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 o=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function Rl(e,t={}){return Dh(Ph(e,t),t.sortMode||"recent")}function gn(e){return e?"Resume saved history":"Start fresh"}function No(e){return e?"Resuming saved history…":"Starting fresh…"}function Eh(){return"Start fresh"}function _l(e,t=!1){return e==="cli"?gn(t):e==="ide"?"Start IDE":"Start ACP session"}function Pl(e,t=!1){return e==="cli"?No(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function $h(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Bh(){return"Open saved history"}function Oh(){return"Saved History"}function Co(){return"Use saved history when you want continuity in the same provider conversation."}function Kh(){return"No saved history found yet."}function Fh(){return"Refresh saved history"}function Wh(){return"Refreshing saved history…"}function ls(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function ds(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 Os(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ks(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Io(e){return`Resume saved history with ${e}?`}function To(){return"Review or change the target workspace before resuming saved history."}function Hh(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 Mo({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:f,onSwitchSession:b,onRefreshHistory:v,onResumeSavedSession:h}){var _;const p=t.find(T=>T.id===e.routeId),g=(p==null?void 0:p.chats)||[],y=(_=p==null?void 0:p.activeChat)==null?void 0:_.id,x=st(e)&&!Ze(e),[C,S]=i.useState(()=>jt()),w=l||C,M=String(d||"").trim(),L=T=>{if(m){m(T);return}S(T)},j=i.useMemo(()=>a.map(T=>{const F=String(T.workspace||"").trim();return T.canResume||F||!M?T:{...T,workspace:M,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[M,a]),k=i.useMemo(()=>Rl(j,{textQuery:w.textQuery,workspaceQuery:w.workspaceQuery,modelQuery:w.modelQuery,resumableOnly:w.resumableOnly,sortMode:w.sortMode}),[j,w.modelQuery,w.resumableOnly,w.sortMode,w.textQuery,w.workspaceQuery]),B=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:x?Oh():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:vh(e)}),x&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Co()})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(gt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!x&&s.jsx("button",{onClick:f,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),x?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:w.textQuery,onChange:T=>L({...w,textQuery:T.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:w.workspaceQuery,onChange:T=>L({...w,workspaceQuery:T.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:w.modelQuery,onChange:T=>L({...w,modelQuery:T.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:w.sortMode,onChange:T=>L({...w,sortMode:T.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:w.resumableOnly,onChange:T=>L({...w,resumableOnly:T.target.checked})}),"Resume-ready only"]})]}),k.map(T=>{const F=e.providerSessionId===T.providerSessionId,H=F||!T.canResume||!!c,R=T.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{H||!h||h(T)},disabled:H,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${F?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${H?"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 ${F?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:T.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Hh(T.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:T.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[T.workspace||"Workspace unknown",R?" · selected workspace":"",bs(T.summaryMetadata)?` · ${bs(T.summaryMetadata)}`:"",T.messageCount>0?` · ${T.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:F?"ACTIVE":T.canResume?R?"RESUME IN SELECTED WORKSPACE":c===T.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},T.id)})]}):g.map(T=>s.jsxs("div",{onClick:()=>{b(e.routeId,T.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${y===T.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${y===T.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[T.id.substring(0,12),"..."]}),y===T.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},T.id)),(x&&!o&&k.length===0||!x&&g.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(pm,{size:32})}),s.jsx("div",{className:"text-[13px]",children:x?a.length>0?"No saved history matches these filters.":Kh():"No recent chat sessions found."})]}),x&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Wh()})})]}),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:v,disabled:n||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||o?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(wr,{size:13})," ",x?Fh():"Refresh History"]})})})]})]});return typeof document>"u"?B:xr.createPortal(B,document.body)}const Ri={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 Dl({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=Ri[n.type]||Ri.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 o;(o=n.actions)!=null&&o.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:o=>{o.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(gt,{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((o,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${o.variant==="primary"||o.variant==="danger",""}`,style:o.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)"}:o.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(),o.onClick(),t(n.id)},children:o.label},c))})]})]},n.id)})})}const Uh=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function zh(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Vh(e){return e.sessionId||e.instanceId||e.agentType}function Zn(e,t){return t||e||"unknown"}function El(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Ct(r,{fallbackId:r.id}));return t}function $l(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 Ao(e,t={}){return Gh(e,$l(e,t))}function Gh(e,t={}){var f,b,v,h,p;const r=[],n=t.machineName,a=t.connectionState,o=zh(e),c=e.workspace||"",l=xp(e.type,{agentName:e.cliName}),d=st(e)||Ze(e)?l:ot(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(g=>{var y,x;return{sessionId:g.id,instanceId:g.id,providerSessionId:g.providerSessionId,transport:g.transport,sessionCapabilities:g.capabilities,agentType:g.providerType,agentName:g.providerName||ot(g.providerType),status:g.status,title:g.title,lastMessagePreview:g.lastMessagePreview,lastMessageRole:g.lastMessageRole,lastMessageAt:g.lastMessageAt,lastMessageHash:g.lastMessageHash,messages:((y=g.activeChat)==null?void 0:y.messages)||[],activeModal:((x=g.activeChat)==null?void 0:x.activeModal)||void 0,unread:g.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,surfaceHidden:g.surfaceHidden,git:g.git,settings:g.settings,messageInput:g.messageInput}}):[],u=Uh(e);if(u){const g=e.sessionId||e.instanceId,y=(f=e.settings)==null?void 0:f.meshCoordinatorFor,x=(b=e.settings)==null?void 0:b.meshNodeFor,C=y?" (Coordinator)":x?" (Mesh Node)":"",S=l+C,w=(v=e.activeChat)==null?void 0:v.activeModal,M=w&&Array.isArray(w.buttons)&&w.buttons.length>0,L=bp(e.activeChat,[{status:e.status,activeModal:(h=e.activeChat)==null?void 0:h.activeModal}],e.agents||[]),j=e.activeChat||{title:"",messages:[]};let k=j.title&&String(j.title).trim()?String(j.title).trim():"";const B=(p=e.activeChat)==null?void 0:p.id,_=e.chats;if(B&&Array.isArray(_)&&_.length>0){const R=_.find(I=>I.id===B||I.id&&String(I.id)===String(B));R!=null&&R.title&&String(R.title).trim()&&(k=String(R.title).trim())}const T=(st(e)||Ze(e),e.type),F=(st(e)||Ze(e))&&bi(k,S,T)?"":k,H=j.messages||[];r.push({routeId:e.id,sessionId:g,providerSessionId:e.providerSessionId,nativeSessionId:g,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:st(e)?e.mode||"terminal":"chat",agentName:S,agentType:T,status:L,title:F,messages:H,resume:e.resume,hostIdeType:!st(e)&&!Ze(e)?e.type:void 0,workspaceName:o,workspacePath:c,git:e.git,displayPrimary:F||o||(st(e)?e.mode==="chat"?S:`Terminal${C}`:S),displaySecondary:st(e)&&o?S:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:M?w.buttons:void 0,modalMessage:M?w.message:void 0,streamSource:"native",tabKey:Zn(g,e.id),machineName:n,connectionState:a,settings:e.settings,messageInput:e.messageInput})}if(u&&(st(e)||Ze(e)))return r;for(const g of m){const y=g.activeModal&&Array.isArray(g.activeModal.buttons)&&g.activeModal.buttons.length>0,x=gp(g),C=Vh(g),S=`${e.id}:${C}`,w=g.title&&String(g.title).trim()||"",M=bi(w,g.agentName,g.agentType)?"":w,L=g.messages||[];(g.transport==="cdp-webview"||g.sessionId||g.providerSessionId||L.length>0||y||M||!["idle","panel_hidden","disconnected","not_monitored"].includes(x))&&r.push({routeId:e.id,sessionId:g.sessionId||g.instanceId,providerSessionId:g.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:g.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:g.sessionCapabilities,mode:"chat",agentName:g.agentName,agentType:g.agentType,status:x,title:M,messages:L,hostIdeType:e.type,workspaceName:o,workspacePath:c,git:g.git||e.git,displayPrimary:M||o||g.agentName||d,displaySecondary:`${d} · ${g.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:g.lastMessagePreview,lastMessageRole:g.lastMessageRole,lastMessageAt:g.lastMessageAt,lastMessageHash:g.lastMessageHash,lastUpdated:g.lastUpdated||e.lastUpdated,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,modalButtons:y?g.activeModal.buttons:void 0,modalMessage:y?g.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Zn(g.sessionId||g.instanceId,S),machineName:n,connectionState:a,settings:g.settings,messageInput:g.messageInput})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:c,git:e.git,displayPrimary:o||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Zn(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function Bl(e){return String(e.type||e.id||"").trim()}function qh(e){var t;return e.category!=="cli"||!Bl(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function Yh(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!qh(a))continue;const o=Bl(a);if(!o||t.has(o))continue;t.add(o);const c=String(a.displayName||a.name||o),l=a.detectedPath||((n=a.lastDetection)==null?void 0:n.path)||null;r.push({type:o,label:c,icon:a.icon,statusLabel:l?`Detected at ${l}`:"Detected on this machine",detectedPath:l})}return r}function Rn(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],r=new Set,n=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||r.has(o)||(r.add(o),n.push(o))}return n}function Ha(e,t){const r=new Set(t.map(n=>n.type));return Rn(e).filter(n=>r.has(n))}function Xh(e){return e.map(t=>t.type)}function Jh(e,t){const r=Rn(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function Qh(e,t){return Rn(e).filter(r=>r!==t)}function _i(e,t,r){const n=Rn(e),a=n.indexOf(t);if(a<0)return n;const o=n.filter(l=>l!==t);if(r==="top")return[t,...o];if(r==="bottom")return[...o,t];const c=r==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(c,0,t),o}function Pi({direction:e}){return s.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?s.jsx("polyline",{points:"18 15 12 9 6 15"}):s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function Di({value:e,availableProviders:t,onChange:r,disabled:n=!1,saveButton:a}){const[o,c]=i.useState(""),l=i.useMemo(()=>new Map(t.map(b=>[b.type,b])),[t]),d=i.useMemo(()=>Ha(e,t),[e,t]),m=e.length-d.length,u=t.filter(b=>!d.includes(b.type)),f=()=>{o&&(r(Jh(d,o)),c(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):d.map((b,v)=>{const h=l.get(b);return s.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border-subtle bg-bg-primary px-3 py-2 sm:flex-row sm:items-center sm:justify-between",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",v+1]}),(h==null?void 0:h.icon)&&s.jsx("span",{"aria-hidden":"true",children:h.icon}),s.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:b}),s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:h?`${h.label} · ${h.statusLabel}`:b})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:n||v===0,title:"Move up",onClick:()=>r(_i(d,b,"up")),children:s.jsx(Pi,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:n||v===d.length-1,title:"Move down",onClick:()=>r(_i(d,b,"down")),children:s.jsx(Pi,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(Qh(d,b)),children:"Remove"})]})]},b)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:o,onChange:b=>c(b.target.value),disabled:n||u.length===0,children:[s.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.map(b=>s.jsxs("option",{value:b.type,children:[b.label," (",b.type,")"]},b.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:f,children:"Add provider"}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Inventory is filtered to CLI providers detected on this machine. New launches use this order; existing running sessions may need restart.",m>0?` ${m} provider${m===1?"":"s"} from the saved policy are not detected now and will be omitted when saved.`:""]})]})}function Zh(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 Ol(e,t){const r=Zh(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Kl=[{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:"🏄"}],Fl=[{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:"🧩"}],Wl=[{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:"🟠"}],ex=Kl,tx=Fl,sx=Wl;function Vt(...e){return vu(wu(e))}function rx({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:Vt("dashboard-header",o),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 mr({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:o="max-w-6xl",contentClassName:c,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(rx,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Vt("mx-auto flex w-full flex-col gap-4",o,c),children:l})})]})}const Ua="adhdev:themechange";function nx(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ss(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ns(e){return e==="system"?nx():e}function Hl(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Zr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Ua,{detail:{preference:e,theme:t}}))}function ax(){const e=Ss(),t=Ns(e);Hl(t),Zr(e,t)}function Lo(){const[e,t]=i.useState(Ss),[r,n]=i.useState(()=>Ns(Ss()));i.useEffect(()=>{Hl(r)},[r]),i.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),Zr("system",m)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),i.useEffect(()=>{const c=d=>{const m=d.detail||{},u=m.preference,f=m.theme;t(u==="dark"||u==="light"||u==="system"?u:Ss()),n(f==="dark"||f==="light"?f:Ns(Ss()))},l=d=>{if(d.key!=="theme")return;const m=Ss(),u=Ns(m);t(m),n(u)};return window.addEventListener(Ua,c),window.addEventListener("storage",l),()=>{window.removeEventListener(Ua,c),window.removeEventListener("storage",l)}},[]);const a=i.useCallback(c=>{const l=Ns(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Zr(c,l)},[]),o=i.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=Ns(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Zr(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const Ei={dark:"Dark",light:"Light",system:"System"};function ox({collapsed:e}){const{preference:t,cycleTheme:r}=Lo(),n=t==="dark"?s.jsx(hm,{size:16}):t==="light"?s.jsx(fm,{size:16}):s.jsx(xm,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Ei[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Ei[t]})]})}function ea(e,t){return e?typeof e=="function"?e(t):e:null}function ix({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:c,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=i.useState(!1),[f,b]=i.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),v=()=>u(!0),h=()=>u(!1),p=()=>{b(C=>{const S=!C;try{localStorage.setItem(d,S?"1":"0")}catch{}return S})},g=i.useMemo(()=>({collapsed:f,mobileMenuOpen:m,openMobileMenu:v,closeMobileMenu:h,toggleCollapsed:p}),[f,m]),y=C=>`nav-item${C.active?" active":""} cursor-pointer ${f?"justify-center py-2.5 px-0":""}${C.className?` ${C.className}`:""}`,x=C=>s.jsxs("div",{className:y(C),id:`nav-${C.id}`,onClick:()=>{C.onSelect(),h()},title:f?C.title??(typeof C.label=="string"?C.label:void 0):C.title,children:[s.jsx("span",{className:"nav-icon",children:C.icon}),!f&&C.label]},C.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${f?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:v,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:h,onKeyDown:C=>C.key==="Escape"&&h()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${f?"justify-center gap-0":""}`,children:ea(t,g)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:h,children:s.jsx(gt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(x)}),n.map(C=>s.jsxs("div",{className:C.className??"border-t border-border-subtle pt-2 mt-2",children:[!f&&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(x)]},C.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(x),ea(o,g),s.jsx(ox,{collapsed:f}),ea(c,g)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function vt({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:Vt("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})]}),o]})}function yn({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:Vt("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 cx={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"},lx={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ms({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:Vt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",cx[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:lx[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function Tt({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:Vt("mb-5",n),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function ta(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:Vt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const dx={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"},ux={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function mx({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:Vt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",dx[e],r),children:[s.jsx("span",{className:Vt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",ux[e])}),n]})}function as({label:e,description:t,checked:r,disabled:n,onChange:a,extra:o}){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:[o,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 px({onPrefChange:e}){const[t,r]=Tp(),[n,a]=i.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);i.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 o=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>o("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(It,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>o("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:()=>{rl().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(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(bm,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>o("completionAlert",c)}),s.jsx(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(gm,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>o("approvalAlert",c)}),s.jsx(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ds,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>o("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 vn(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function fx(e,t){const r=vn(e),n=vn(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 Ul(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function pr(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||fx(r,t)>=0)return!1;const n=vn(r),a=vn(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function hx(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function sa(e,t){return e instanceof Error?e.message:t}function xx({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(c=>c.type==="adhdev-daemon");return o.length===0?s.jsx(yn,{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:o.map(c=>s.jsx(gx,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function $i({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return xr.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:o,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:o,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 bx(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...ex,...tx,...sx].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 gx({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var H,R;const[o,c]=i.useState("idle"),[l,d]=i.useState(""),[m,u]=i.useState(null),[f,b]=i.useState("idle"),[v,h]=i.useState(""),p=e.version||null,g=((H=e.machine)==null?void 0:H.platform)||((R=e.system)==null?void 0:R.platform)||"",y=Ct(e,{fallbackId:e.id}),x=g==="win32"?"🪟":g==="darwin"?"🍎":"🐧",C=t.filter(I=>I.daemonId===e.id&&I.transport==="cdp-page"),S=t.filter(I=>I.daemonId===e.id&&I.transport==="pty"),w=t.filter(I=>I.daemonId===e.id&&I.transport==="acp"),M=e.p2p,L=async()=>{if(r){c("upgrading"),d("Starting upgrade...");try{const I=hx(await r(e.id,"daemon_upgrade",{}));I.alreadyLatest?(c("done"),d(`Already on v${I.version||"latest"}.`)):I.upgraded||I.success?(c("done"),d(`Upgrade to v${I.version||"latest"} started. Daemon is restarting...`)):(c("error"),d(I.error||"Upgrade failed"))}catch(I){c("error"),d(sa(I,"Connection lost during upgrade"))}}},j=async()=>{if(u(null),!!n){b("loading");try{await n(e.id),b("done"),h("Machine disconnected.")}catch(I){b("error"),h(sa(I,"Failed to disconnect"))}}},k=async()=>{if(u(null),!!a){b("loading");try{await a(e.id),b("done"),h("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(I){b("error"),h(sa(I,"Failed to revoke token"))}}},B="0.9.81",_=Ul(e,B),T=pr(e,B),F=C.length+S.length+w.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:x}),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] ${_?"":"bg-bg-secondary"}`,style:_?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!_&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&_&&s.jsx("button",{onClick:L,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${B}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${T?"↑ Update now":`↑ Update${` to v${B}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(mx,{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&&F>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),F>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(I=>{const N=bx(I.type),K=I.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:N.icon}),s.jsx("span",{children:N.name}),K!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${K?"bg-green-400":"animate-pulse"}`,style:K?void 0:{background:"var(--status-warning)"},title:K?"CDP connected":"CDP connecting..."})]},I.id)}),S.map(I=>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:I.cliName||"CLI"})]},I.id)),w.map(I=>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:I.cliName||"ACP"})]},I.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||v)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||f==="error"?"text-red-400":o==="done"||f==="done"?"text-green-400":"text-text-muted"}`,children:v||l})]}),m==="disconnect"&&s.jsx($i,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
43
-
44
- This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
45
-
46
- Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:j,onCancel:()=>u(null)}),m==="revoke"&&s.jsx($i,{title:"⚠️ Remove Machine",message:`Remove "${y}" from your dashboard?
47
-
48
- This will:
49
- • Immediately disconnect the machine
50
- • Delete the machine registration
51
- • Require restarting ADHDev on that machine
52
-
53
- Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:k,onCancel:()=>u(null)})]})}const yx=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function vx(){const{preference:e,setPreference:t}=Lo();return s.jsx("div",{className:"flex gap-2",children:yx.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 wx(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 jx(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function ra(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Bi(e){const{r:t,g:r,b:n}=jx(e);return .2126*ra(t)+.7152*ra(r)+.0722*ra(n)}function Oi(e,t){const r=Bi(e),n=Bi(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function zl(e){const t=wx(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Oi(t,r)>=Oi(t,n)?r:n}const za={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},Va={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},kx=[{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"}}}],Vl="adhdev-chat-theme",Gl="adhdev-chat-theme-custom";function en(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Vl)||"ember"}catch{return"ember"}}function Pt(e){try{const t=localStorage.getItem(Gl);if(t){const r=JSON.parse(t);return{...e==="dark"?za:Va,...r[e]}}}catch{}return e==="dark"?za:Va}function Kr(e,t){try{localStorage.setItem(Gl,JSON.stringify({dark:e,light:t}))}catch{}}function Mt(e,t){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${t})`}function wn(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 Sx={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function fr(e,t){var a;const r=(a=Sx[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",wn(r,24)),n.style.setProperty("--accent-on-primary",zl(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${wn(r,18)})`),n.style.setProperty("--border-accent",Mt(r,.35)),n.style.setProperty("--nav-active-bg",Mt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Mt(r,.06)}`)}function us(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Mt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Mt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Mt(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",Mt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Mt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",wn(e.accentColor,30)),t.style.setProperty("--accent-on-primary",zl(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${wn(e.accentColor,40)})`),t.style.setProperty("--border-accent",Mt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Mt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Mt(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${Mt(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function Ro(){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 Nx(e){try{localStorage.setItem(Vl,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ms()?"dark":"light";us(Pt(t))}else Ro(),fr(e,ms()?"dark":"light")}function Cx(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=en();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ms()?"dark":"light";us(Pt(t))}else Ro(),fr(e,ms()?"dark":"light")}function ms(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function kt({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 er({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 Ix({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=i.useState(()=>Pt(r));i.useEffect(()=>{a(Pt(r))},[r]);const o=i.useCallback((c,l)=>{a(d=>{const m={...d,[c]:l},f=Pt(r==="dark"?"light":"dark");return r==="dark"?Kr(m,f):Kr(f,m),us(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(er,{title:"App Background",children:[s.jsx(kt,{label:"Background",value:n.bgPrimary,onChange:c=>o("bgPrimary",c)}),s.jsx(kt,{label:"Surface",value:n.bgSecondary,onChange:c=>o("bgSecondary",c)}),s.jsx(kt,{label:"Card",value:n.surfacePrimary,onChange:c=>o("surfacePrimary",c)})]}),s.jsxs(er,{title:"App Text",children:[s.jsx(kt,{label:"Primary",value:n.textPrimary,onChange:c=>o("textPrimary",c)}),s.jsx(kt,{label:"Secondary",value:n.textSecondary,onChange:c=>o("textSecondary",c)}),s.jsx(kt,{label:"Muted",value:n.textMuted,onChange:c=>o("textMuted",c)})]}),s.jsxs(er,{title:"Borders & Accent",children:[s.jsx(kt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>o("borderSubtle",c)}),s.jsx(kt,{label:"Border default",value:n.borderDefault,onChange:c=>o("borderDefault",c)}),s.jsx(kt,{label:"Accent",value:n.accentColor,onChange:c=>o("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(er,{title:"Chat Bubbles",children:[s.jsx(kt,{label:"User bubble",value:n.userBubble,onChange:c=>o("userBubble",c)}),s.jsx(kt,{label:"User text",value:n.userText,onChange:c=>o("userText",c)}),s.jsx(kt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>o("assistantBubble",c)}),s.jsx(kt,{label:"Agent text",value:n.assistantText,onChange:c=>o("assistantText",c)})]}),s.jsxs(er,{title:"Chat Layout",children:[s.jsx(kt,{label:"Chat BG",value:n.containerBg,onChange:c=>o("containerBg",c)}),s.jsx(kt,{label:"Send button",value:n.sendButton,onChange:c=>o("sendButton",c)}),s.jsx(kt,{label:"Input border",value:n.inputBorder,onChange:c=>o("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=>o("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?za:Va,d=Pt(e?"light":"dark");e?Kr(c,d):Kr(d,c),a(c),us(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 Tx(){const[e,t]=i.useState(en),[r,n]=i.useState(!0),[a,o]=i.useState(()=>Pt("dark"));i.useEffect(()=>{n(ms());const d=new MutationObserver(()=>{const f=ms();n(f);const b=en();b==="custom"?us(Pt(f?"dark":"light")):fr(b,f?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const f=ms();n(f);const b=en();b==="custom"?us(Pt(f?"dark":"light")):fr(b,f?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?us(Pt(r?"dark":"light")):(Ro(),fr(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o(Pt(r?"dark":"light"))},[r]);const c=d=>{t(d),Nx(d)},l=[...kx,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(d=>{const m=e===d.id,u=r?d.preview.dark:d.preview.light,f=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:u.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:f},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[m&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:d.id==="custom"?"🎨 Custom":d.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&s.jsx(Ix,{dark:r,onColorsChange:d=>o(d)})]})}const _o="adhdev_mobileDashboardMode_v1",Ga="adhdev:mobile-dashboard-mode-change";function Po(){try{return localStorage.getItem(_o)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Mx(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Po())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==_o||t()};return window.addEventListener(Ga,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Ga,r),window.removeEventListener("storage",n)}}function Ax(e){try{localStorage.setItem(_o,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ga,{detail:e}))}function Lx(){const[e,t]=i.useState(!0);return i.useEffect(()=>{t(Po()==="chat")},[]),s.jsx(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zt,{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),Ax(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const na=new Map,Ki=new Map;function Rx(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 _x(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 ql(){const{sendCommand:e}=yt(),{injectEntries:t,getIdes:r}=br();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??Mf,c=Ki.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<o)return;const l=na.get(n);if(l)return l;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=Rx(m);if(!u)return;const f=r().find(v=>v.id===n),b=_x(f,n,u.machine,u.timestamp||Date.now());t([b]),Ki.set(n,Date.now())})().finally(()=>{na.delete(n)});return na.set(n,d),d},[r,t,e])}function Px(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 Dx(e,t){const{sendData:r}=yt(),{injectEntries:n,getIdes:a}=br(),o=Array.from(new Set(e.filter(Boolean))).join("|");i.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=o?o.split("|"):[];if(c.length===0)return;const l=c.map(d=>Ut.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const f=a().find(v=>v.id===d),b=Px(f,d,u);n([b])}));return()=>{l.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function Ex(e,t){const{sendData:r}=yt(),[n,a]=i.useState(null),[o,c]=i.useState(!1);return i.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(t!=null&&t.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const d=Ut.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},m=>{l&&(clearTimeout(l),l=null),a(m.diagnostics),c(!1)});return d.initialSendAccepted?l=setTimeout(()=>{c(!1)},_f):c(!1),()=>{l&&clearTimeout(l),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:o,applyDiagnostics:a}}function $x(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Yl(e){const{sendData:t}=yt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=$x(e);if(!a||!e.sessionId||!t){n({});return}const o=Ut.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}),_s.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 o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const Xl="adhdev_hiddenTabs",Jl="adhdev_autoHiddenMeshTabs";function Bx(){try{const e=localStorage.getItem(Xl);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ss(e){try{localStorage.setItem(Xl,JSON.stringify([...e]))}catch{}}function Ox(){try{const e=localStorage.getItem(Jl);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function Fi(e){try{localStorage.setItem(Jl,JSON.stringify([...e]))}catch{}}function cr(e){return jo(e)}function _n(e,t){return Rs(t).some(r=>e.has(r))}function Kx(e){var t,r,n;return((t=e.settings)==null?void 0:t.launchedByCoordinator)===!0&&typeof((r=e.settings)==null?void 0:r.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0&&((n=e.settings)==null?void 0:n.spawnedSessionVisibility)==="hidden"}function Fx(e,t,r=new Set){return e.filter(n=>{if(!Kx(n))return!1;const a=cr(n);return r.has(a)?!1:!_n(t,n)})}function Wx(){const[e,t]=i.useState(Bx),[r,n]=i.useState(Ox),a=i.useCallback(b=>{const v=cr(b);t(h=>{const p=new Set(h);return p.has(v)?p.delete(v):p.add(v),ss(p),p})},[]),o=i.useCallback(b=>{const v=cr(b);t(h=>{if(h.has(v))return h;const p=new Set(h);return p.add(v),ss(p),p})},[]),c=i.useCallback(b=>{const v=cr(b);t(h=>{if(h.has(v))return h;const p=new Set(h);return p.add(v),ss(p),p}),n(h=>{if(h.has(v))return h;const p=new Set(h);return p.add(v),Fi(p),p})},[]),l=i.useCallback(b=>{const v=cr(b);t(h=>{if(!h.has(v))return h;const p=new Set(h);return p.delete(v),ss(p),p}),n(h=>{if(h.has(v))return h;const p=new Set(h);return p.add(v),Fi(p),p})},[]),d=i.useCallback(()=>{t(b=>{if(b.size===0)return b;const v=new Set;return ss(v),v})},[]),m=i.useCallback((b,v)=>{t(h=>{const p=new Set(h);for(const g of v)p.add(g);return ss(p),p})},[]),u=i.useCallback((b,v)=>{t(h=>{const p=new Set(h);for(const g of v)p.delete(g);return ss(p),p})},[]),f=i.useCallback(b=>_n(e,b),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:c,showTarget:l,showAllTabs:d,hideAllForDaemon:m,showAllForDaemon:u,isHidden:f}}function Ql(e){return e instanceof Error?e.message:String(e||"")}function Zl(e){const t=Ql(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 ed(e){const t=Ql(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function td({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!st(e)||Ze(e))return;const o=Us(e);if(o===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(ws(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Kt(e),mode:t})}catch(l){const d=ed(l);c&&!d&&a(m=>{const u={...m};return o===sd(r,c)?delete u[c]:u[c]=o,u}),Zl(l)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function Wi(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 Hx(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 o=Wi(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>Wi(d,t)):a.childSessions,l=c!==a.childSessions;return o!==a||l?(r=!0,{...o,...l?{childSessions:c}:{}}):a});return r?n:e}function sd(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 Ux(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,o]of Object.entries(e))sd(t,a)===o&&(delete n[a],r=!0);return r?n:e}function zx({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{rl()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:Ml(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return Rp(a),i.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const d=Date.now(),m={};for(const[u,f]of Object.entries(l))d-f<5e3&&(m[u]=f);return Object.keys(m).length===Object.keys(l).length?l:m})},5500);return()=>clearTimeout(c)},[t,r]),i.useEffect(()=>{const o=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const d=l.filter(m=>m.timestamp>c).slice(-100);return d.length===l.length?l:d})},6e4);return()=>clearInterval(o)},[n]),null}function Hi(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 ps(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=Hi(t==null?void 0:t.receivedAt)||Hi(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function qa(e,t=0){return ps(e)||e.lastUpdated||t||0}function rd(e){return ps(e)||e.lastUpdated||0}function nd(e,t,r=rd){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const c=e.displaySecondary.localeCompare(t.displaySecondary);return c!==0?c:e.tabKey.localeCompare(t.tabKey)}function Ya(e){var r;const t=xt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Vx(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Ya(e)&&!e.title.trim()}function Gx(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(Ya(r))-Number(Ya(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:nd(t,r)})[0]||null}function Dt(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"),o=Gx(a);return n?o&&Vx(n)?o:n:o||r[0]||null}function qx(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!t||r.startsWith(`${t}:`)?r:`${t}:${r}`}function Yx(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=qx(n),o=r.get(a);if(!o){r.set(a,n);continue}const c=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>c||(n.timestamp||0)>(o.timestamp||0))&&r.set(a,n)}return Array.from(r.values())}function aa(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 Xx(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 Ui(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Xx(Ps(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 Jx(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||""),Ui(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||""),Ui(r.activeChat)].join(":"))].join("|")}function Qx(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 Zx(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Rs({routeId:n.routeId}))r.set(o,a);for(const o of Rs({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Rs({tabKey:n.tabKey}))r.set(o,n)}return r}function eb(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function tb(e){const t=eb(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=Ps(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function sb({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>Yx(e),[e]),o=i.useMemo(()=>El(e),[e]),c=i.useRef([]),l=i.useRef([]),d=i.useRef([]),m=i.useRef(new Map),u=i.useRef(new Map),f=i.useMemo(()=>{const S=new Map,w=[];for(const k of a){const{connectionState:B="new",machineName:_}=$l(k,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),T=Jx(k),F=m.current.get(k.id);if(F&&F.ide===k&&F.sourceSignature===T&&F.connectionState===B&&F.machineName===_){S.set(k.id,F),w.push(...F.conversations);continue}const H=Ao(k,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),R={ide:k,sourceSignature:T,connectionState:B,machineName:_,conversations:H};S.set(k.id,R),w.push(...H)}m.current=S;const M=new Map,L=k=>{const B=tb(k),_=u.current.get(k.tabKey);if(_&&_.signature===B)return M.set(k.tabKey,_),_.timestamp;const T={signature:B,timestamp:rd(k)||(_==null?void 0:_.timestamp)||0};return M.set(k.tabKey,T),T.timestamp},j=[...w].sort((k,B)=>nd(k,B,L));return u.current=M,j},[a,t,o]),b=i.useMemo(()=>{const S=Qx(f,r);return aa(c.current,S)?c.current:(c.current=S,S)},[f,r]),v=i.useMemo(()=>{const S=new Map,w=Array.from(new Set(b.map(M=>M.routeId)));for(const M of w){const L=Dt(b,M);L&&S.set(M,L)}return S},[b]),h=i.useMemo(()=>{const S=new Map;for(const w of b){const M=v.get(w.routeId),L=w.streamSource==="native"&&M?M:w;for(const j of Rs({providerSessionId:w.providerSessionId,sessionId:w.sessionId,tabKey:w.tabKey}))S.set(j,L)}return S},[b,v]),p=i.useMemo(()=>Zx(b,v),[b,v]),g=i.useCallback(S=>{if(S)return h.get(S)},[h]),y=i.useCallback(S=>{if(S)return p.get(S)},[p]),x=i.useMemo(()=>{const S=b.filter(w=>!_n(n,w));return aa(l.current,S)?l.current:(l.current=S,S)},[b,n]),C=i.useMemo(()=>{const S=x.map(w=>w.tabKey);return aa(d.current,S)?d.current:(d.current=S,S)},[x]);return{chatIdes:a,conversations:b,visibleConversations:x,visibleTabKeys:C,resolveConversationBySessionId:g,resolveConversationByTarget:y}}function rb({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=i.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),o=i.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=i.useCallback(()=>{t&&n(l=>{const d=new URLSearchParams(l);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:c}}function nb({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){i.useEffect(()=>{nt.setIdes(e)},[e]),i.useEffect(()=>{nt.setResolveAction((a,o,c)=>{t(a,o,c).catch(()=>{})})},[t]),i.useEffect(()=>{const a=nt.onToast(o=>{r(l=>l.some(m=>m.message===o.message&&o.timestamp-m.timestamp<3e3)?l:[...l.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const c=o.duration||5e3;setTimeout(()=>r(l=>l.filter(d=>d.id!==o.id)),c)});return()=>{a()}},[r]),i.useEffect(()=>{const a=Cl.on("status_event",o=>{nt.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=c=>{var p;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const d=l.targetSessionId||l.targetKey||l.daemonId,m=n(d),u=(m==null?void 0:m.routeId)||l.daemonId;if(!u)return;const f=Number(l.buttonIndex),b=l.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[f])||"Approve",v=String(b).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),h=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(v);t(u,"resolve_action",{action:h?"approve":"reject",button:b,...Number.isFinite(f)&&{buttonIndex:f},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(g=>console.error("[SW Action] approval failed:",g))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,t])}const ab="adhdev_dashboardLayout_v1",ob="adhdev_dashboardDockview_v1",ib="adhdev_dashboardDockviewHiddenRestore_v1",tr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Do(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function cb(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function ad(e){return`${ab}:${e}`}function lb(e){const t=ad(e);return Do(t,null)}function db(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=ad(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function od(e){return`${ob}:${e}`}function ub(e){const t=od(e);return Do(t,null)}function mb(e,t){try{const r=od(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function id(e){return`${ib}:${e}`}function pb(e){const t=id(e);return Do(t,{})}function fb(e,t){try{const r=id(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function hb(){return{groupAssignments:[...tr.groupAssignments],focusedGroup:tr.focusedGroup,groupActiveTabIds:{...tr.groupActiveTabIds},groupTabOrders:{...tr.groupTabOrders},groupSizes:[...tr.groupSizes]}}function xb(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function bb(){const[e]=i.useState(()=>cb(typeof window<"u"?window.innerWidth:1280)),[t,r]=i.useState(()=>new Map),[n,a]=i.useState(0),[o,c]=i.useState({}),[l,d]=i.useState({}),[m,u]=i.useState([]),[f,b]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[v,h]=i.useState(!1),p=i.useCallback(()=>{if(v)return;const k=lb(e)??hb();r(new Map(k.groupAssignments)),a(k.focusedGroup),c(k.groupActiveTabIds),d(k.groupTabOrders),u(k.groupSizes),h(!0)},[v,e]);i.useEffect(()=>{v&&db(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:l,groupSizes:m})},[v,e,t,n,o,l,m]),i.useEffect(()=>{const k=window.matchMedia("(max-width: 767px)"),B=_=>b(_.matches);return k.addEventListener("change",B),()=>k.removeEventListener("change",B)},[]);const g=i.useCallback(k=>{r(k)},[]),y=i.useCallback(k=>{a(k)},[]),x=i.useCallback(k=>{c(k)},[]),C=i.useCallback(k=>{d(k)},[]),S=i.useCallback(k=>{u(k)},[]),w=i.useCallback(k=>{y(k)},[y]),M=i.useCallback((k,B)=>{c(_=>(_[k]??null)===(B??null)?_:{..._,[k]:B})},[]),L=i.useCallback((k,B)=>{d(_=>{const T=_[k];return xb(T,B)?_:{..._,[k]:B}})},[]),j=i.useCallback((k,B)=>{const _=B.get(k)??0;return M(_,k),w(_),_},[w,M]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:g,focusedGroup:n,updateFocusedGroup:y,focusGroup:w,groupActiveTabIds:o,updateGroupActiveTabIds:x,setGroupActiveTab:M,groupTabOrders:l,updateGroupTabOrders:C,setGroupTabOrder:L,groupSizes:m,updateGroupSizes:S,isMobile:f,hasHydratedStoredLayout:v,hydrateStoredLayout:p,focusConversationTab:j}}function gb(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=wo(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function yb({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:c,setSearchParams:l,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:f,handleRefreshHistory:b}){const v=i.useRef(!1),h=i.useRef(!1),p=i.useRef(null),g=i.useRef(!1);i.useEffect(()=>{if(!e||v.current||t.length===0)return;if(!a){o();return}const y=r(e);y&&(c(y.tabKey,n),v.current=!0,h.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(x=>{const C=new URLSearchParams(x);return C.delete("activeTab"),C},{replace:!0}))},[e,t,r,n,a,o,c,l]),i.useEffect(()=>{if(!(h.current||a)&&t.length!==0){if(!e){o(),h.current=!0;return}if(v.current){h.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(h.current||a)&&(o(),h.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,o]),i.useEffect(()=>{if(!d){g.current=!1;return}if(!m||g.current||u)return;const y=f.find(x=>x.id===m.routeId);y&&(!y.chats||y.chats.length===0||gb(y.chats,m))&&(g.current=!0,b())},[d,m,u,f,b])}function oa(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=wo(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function cd({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[c,l]=i.useState(!1),[d,m]=i.useState(!1),u=i.useCallback(async h=>{try{await e("standalone","launch_ide",{ideType:h,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),f=i.useCallback(async(h,p)=>{try{const g=h||(t==null?void 0:t.daemonId)||"",y=await e(g,"switch_chat",{id:p,sessionId:p,...is(t)}),x=y==null?void 0:y.result;if((y==null?void 0:y.success)===!0||x==="switched"||x==="switched-by-title")return;x===!1||x==="not_found"?Js(a,"⚠️ Session tab not found — try refreshing history"):typeof x=="string"&&x.startsWith("error:")?Js(a,`⚠️ Switch error: ${x}`):Js(a,"⚠️ Session switch failed")}catch(g){console.error("Switch failed",g),Js(a,`❌ Switch failed: ${g.message||"connection error"}`)}},[t,e,a]),b=i.useCallback(async()=>{if(!(!t||c)){l(!0);try{const h=$s(t);await e(h,"new_chat",{...is(t)}),o(p=>({...p,[t.tabKey]:Date.now()}))}catch(h){console.error("New chat failed",h)}finally{l(!1)}}},[t,c,e,o]),v=i.useCallback(async()=>{var h,p;if(!(!t||d)){m(!0);try{const g=$s(t),y=async()=>e(g,"list_chats",{forceExpand:!0,...is(t)});let x=await y(),C=(x==null?void 0:x.chats)||((h=x==null?void 0:x.result)==null?void 0:h.chats);oa(C,t)&&(await new Promise(S=>setTimeout(S,450)),x=await y(),C=(x==null?void 0:x.chats)||((p=x==null?void 0:x.result)==null?void 0:p.chats)),x!=null&&x.success&&Array.isArray(C)&&(n(t.routeId,C),oa(C,t)&&!oa(r,t)&&Js(a,"⚠️ History dialog did not fully open — try once more"))}catch(g){console.error("Refresh history failed",g)}finally{m(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:f,handleNewChat:b,handleRefreshHistory:v}}function vb(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 wb(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function zi(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 Fr(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 o=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const d=a[l];typeof d=="number"&&d>0&&o.set(c,d)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function Vi(e,t){const r={};for(const[n,a]of Object.entries(e)){const o=t[Number(n)];typeof o=="number"&&(r[o]=a)}return r}function jb(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 kb(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),o=a.reduce((c,l)=>c+l,0);return o>0?a.map(c=>c/o*100):Array(r).fill(100/r)}function Gi(e,t){const r={};for(const[n,a]of Object.entries(e)){const o=Number(n);r[o>=t?o+1:o]=a}return r}function qi(e){return Array(e).fill(100/e)}function Sb({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:c,isMobile:l,visibleConversations:d,visibleTabKeys:m}){const u=i.useRef(null),f=i.useMemo(()=>Fr(e,m),[e,m]),b=f.assignments,v=i.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),h=v>1,p=i.useCallback((w,M)=>{t(L=>{const j=new Map(Fr(L,m).assignments);return M===0?j.delete(w):j.set(w,M),j}),n(L=>({...L,[M]:w})),r(M)},[t,m,n,r]),g=i.useCallback(w=>{t(M=>{const L=Fr(M,m).assignments,j=new Map;for(const[k,B]of L)B!==w&&(B>w?j.set(k,B-1):j.set(k,B));return j}),c(M=>{if(M.length<=1)return[];const L=[...M];L.splice(w,1);const j=L.reduce((k,B)=>k+B,0);return j>0?L.map(k=>k/j*100):[]}),r(0)},[t,m,c,r]),y=i.useCallback((w,M)=>{M.preventDefault();const L=u.current;if(!L)return;const j=M.clientX,k=L.offsetWidth,B=o.length===v?[...o]:qi(v),_=F=>{const R=(F.clientX-j)/k*100,I=[...B];I[w]=Math.max(15,B[w]+R),I[w+1]=Math.max(15,B[w+1]-R),c(I)},T=()=>{document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",T),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",_),document.addEventListener("mouseup",T)},[o,v,c]),x=i.useCallback((w,M,L)=>{if(v>=4)return;const j=L==="left"?M:M+1;t(k=>{const B=Fr(k,m).assignments,_=new Map;for(const T of d){const F=B.get(T.tabKey)??0,H=F>=j?F+1:F;H>0&&_.set(T.tabKey,H)}return j>0&&_.set(w,j),_}),c(k=>{const B=k.length===v?[...k]:qi(v),_=B[M]??100/v,T=Math.max(15,_/2),F=Math.max(15,_/2),H=[...B];H[M]=T,H.splice(j,0,F);const R=H.reduce((I,N)=>I+N,0);return H.map(I=>I/R*100)}),n(k=>{const B=Gi(k,j);return B[j]=w,B}),a(k=>{const B=Gi(k,j);return B[j]=[w],B}),r(j)},[v,t,m,d,c,n,a,r]);i.useEffect(()=>{vb(e,b)||t(b)},[e,b,t]),i.useEffect(()=>{const{mapping:w,usedGroups:M}=f;n(L=>{const j=Vi(L,w);return zi(L,j)?L:j}),a(L=>{const j=Vi(L,w);return zi(L,j)?L:j}),r(L=>{const j=l?0:jb(L,M,w);return L===j?L:j}),c(L=>{const j=l?[]:kb(L,M,f.groupCount);return wb(L,j)?L:j})},[f,l,n,a,r,c]);const C=i.useMemo(()=>{const w=Array.from({length:v},()=>[]);for(const M of d){const L=b.get(M.tabKey)??0,j=Math.min(L,v-1);w[j].push(M)}return w},[d,b,v]),S=i.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:b,numGroups:v,isSplitMode:h,groupedConvs:C,moveTabToGroup:p,closeGroup:g,handleResizeStart:y,splitTabRelative:x,clearAllSplits:S}}function ia(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function Nb(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="latest"||t==="stable"?"latest":t==="next"||t==="preview"?"next":null}function Wr(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Eo(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=ia(t.channel)||ia(e.updateChannel)||ia(e.releaseChannel)||void 0,n=Nb(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=Wr(t.targetVersion)||Wr(e.serverVersion)||void 0,o=Wr(t.minVersion)||void 0,c=Wr(t.updateCommand)||(r?`adhdev update --channel ${r}`:void 0);return{...r?{channel:r}:{},...n?{npmTag:n}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...c?{updateCommand:c}:{}}}function Cs(e,t=null){return Eo(e).targetVersion||t}function ld(e){return Eo(e).channel||null}function dd(e){const t=Eo(e);return{...t.channel?{channel:t.channel}:{},...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},...Object.keys(t).length>0?{updatePolicy:t}:{}}}function Cb({ides:e,sendDaemonCommand:t}){const r="0.9.81",n=i.useMemo(()=>e.filter(f=>f.type!=="adhdev-daemon"?!1:Ul(f,Cs(f,r))).sort((f,b)=>Number(pr(b,Cs(b,r)))-Number(pr(f,Cs(f,r)))),[r,e]),a=i.useMemo(()=>n.some(f=>pr(f,Cs(f,r))),[r,n]),o=i.useMemo(()=>n.map(f=>Cs(f,r)).find(f=>typeof f=="string"&&f.trim().length>0)||r,[r,n]),[c,l]=i.useState(!1),[d,m]=i.useState({}),u=i.useCallback(async f=>{var v,h;const b=e.find(p=>p.id===f);if(b){m(p=>({...p,[f]:"upgrading"}));try{const p=await t(f,"daemon_upgrade",dd(b));(v=p==null?void 0:p.result)!=null&&v.upgraded||(h=p==null?void 0:p.result)!=null&&h.success?m(g=>({...g,[f]:"done"})):m(g=>({...g,[f]:"error"}))}catch{m(p=>({...p,[f]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:c,setVersionBannerDismissed:l,upgradingDaemons:d,handleBannerUpgrade:u}}const ud=80;function tn(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function Ib(e){return{...e,createdAt:tn(e.createdAt),updatedAt:tn(e.updatedAt,e.createdAt),lastEventAt:tn(e.lastEventAt,e.updatedAt||e.createdAt)}}function Tb(e){const t=jo(e);return t==="unknown:"?e.id:t}function Mb(e){return[e.type,yl(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Ab(e,t=ud){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Tb(n),o=r.get(a);if(!o){r.set(a,n);continue}(n.updatedAt>o.updatedAt||n.updatedAt===o.updatedAt&&n.createdAt>o.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const o=a.updatedAt-n.updatedAt;return o!==0?o:a.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function Lb(e,t){const r=Date.now(),n=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden)continue;const c=Tn(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const d=tn(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=Mb({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||a.lastUpdated});n.push(Ib({id:m,dedupKey:m,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:ll(a),preview:of(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return Ab(n)}function Rb(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function _b(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=ud}=e,a=i.useMemo(()=>Lb(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=i.useMemo(()=>Rb(a),[a]);return{notifications:a,unreadCount:o}}function Pb({notifications:e,sendDaemonCommand:t}){const r=i.useCallback(o=>{const c=e.find(d=>d.id===o),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=i.useCallback(o=>{const c=e.find(l=>l.id===o);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=i.useCallback(o=>{const c=e.find(l=>l.id===o);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const Db=i.createContext(null);function Eb(){return i.useContext(Db)}function Pn(...e){const t=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const c=o.toLowerCase();t.has(c)||(t.add(c),r.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)n(o);continue}n(a)}return r}function $b(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 Dn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=$b(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 Bb(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 Ob(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function En(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=Ob(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 o=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=o.includes("\\")?"\\":"/",l=(m,u)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${u}`:m==="/"||m==="\\"?`${c}${u}`:`${m.replace(/[\\/]+$/,"")}${c}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:typeof(m==null?void 0:m.path)=="string"&&m.path.trim()?m.path:l(o,m.name)})).sort((m,u)=>m.name.localeCompare(u.name)):[];return{path:o,directories:d}}function Kb(e,t){const r={meshId:t.meshId||"",workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp"};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand)\s*\}\}/g,(n,a)=>r[a]||"")}function md(e,t={}){const r=e==null?void 0:e.mcpConfig;return(r==null?void 0:r.mode)!=="manual"?null:{serverName:r.serverName||"adhdev-mesh",configFormat:r.format,configPathCommand:r.configPathCommand,requiresRestart:r.requiresRestart===!0,instructions:r.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:Kb(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function Fb(e){if(!e||typeof e!="object")return null;const t=e,r=typeof t.instructions=="string"?t.instructions:"",n=typeof t.template=="string"?t.template:"";return!r&&!n?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:r||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:n}}function Zt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function pd(e){return Nr(e)||e.tabKey||e.routeId||null}function fd(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(o=>{if(n&&o.routeId!==n)return!1;const c=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(l=>typeof l=="string"?l.trim():"").filter(Boolean);return!!(t&&c.includes(t)||r&&c.includes(r)||n&&o.routeId===n)});if(a!=null&&a.tabKey)return a.tabKey;if(n){const o=Dt(e.conversations,n)||e.conversations.find(c=>c.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return t||r||n||null}function Yt(e){return String(e||"").trim()}function hd(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function jn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Wb(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Hb(e,t){const r=Yt(e.providerSessionId),n=Yt(e.targetSessionId),a=t.find(o=>{const c=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Yt).filter(Boolean);return!!(r&&c.includes(r)||n&&c.includes(n))});return a?a.tabKey:n||r||null}function Ub(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=hd(t.daemonId);if(n&&n!==e.machineId)return null;const a=Yt(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=Yt(e.resumeSessionId),c=Yt(e.launchedSessionId),l=Yt(t.providerSessionId),d=Yt(t.targetSessionId);if(o&&o!==l&&o!==d||c&&c!==l&&c!==d)return null;const m=jn(e.workspacePath);if(m){const u=jn(t.workspaceName);if(u&&!Wb(u,m))return null}return Hb(t,r)}function Yi(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function zb({ides:e,conversations:t,onOpenSession:r}){const[n,a]=i.useState(null),o=i.useRef(null),c=i.useCallback(()=>{o.current=null,a(null)},[]),l=i.useCallback(d=>{o.current=d,a(d)},[]);return i.useEffect(()=>{if(!n)return;const d=jn(n.workspacePath),m=e.find(f=>{var g,y,x,C;if(!f||f.type==="adhdev-daemon"||hd(f.daemonId||f.id)!==n.machineId||(yr(f)?"cli":As(f)?"acp":"ide")!==n.kind)return!1;const h=String(f.agentType||f.type||"");if(n.providerType&&h!==n.providerType)return!1;if(n.resumeSessionId)return String(f.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const S=String(n.launchedSessionId||"");return[f.providerSessionId,f.sessionId,f.instanceId,f.id].map(M=>String(M||"")).filter(Boolean).includes(S)}if(d){const S=jn(f.workspace||f.runtimeWorkspaceLabel);return S?S===d:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((C=(x=(y=(g=f.activeChat)==null?void 0:g.messages)==null?void 0:y.at)==null?void 0:x.call(y,-1))==null?void 0:C.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const u=fd({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:t});u&&(c(),r(u))},[c,t,e,r,n]),i.useEffect(()=>nt.onStatusEvent(d=>{const m=o.current;if(!m)return;const u=Ub(m,d,t);u&&(c(),r(u))}),[c,t,r]),i.useEffect(()=>{if(!n)return;const d=window.setTimeout(()=>{a(m=>!m||m.startedAt!==n.startedAt?m:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[n]),{trackPendingLaunch:l}}function Vb({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const c=Eb(),l=i.useCallback(async(p,g)=>En(e,p,g),[e]),d=i.useCallback(async(p,g)=>{if(!g.trim())return{ok:!1,error:"Choose a workspace path first."};try{const y=await e(p,"workspace_add",{path:g.trim()});return y!=null&&y.success?{ok:!0}:{ok:!1,error:(y==null?void 0:y.error)||"Could not save workspace"}}catch(y){return{ok:!1,error:y instanceof Error?y.message:"Could not save workspace"}}},[e]),m=i.useCallback(async(p,g,y)=>{var x;try{const C={ideType:g,enableCdp:!0};(x=y==null?void 0:y.workspacePath)!=null&&x.trim()&&(C.workspace=y.workspacePath.trim());const S=await e(p,"launch_ide",C);return!(S!=null&&S.success)&&(S==null?void 0:S.success)!==void 0?{ok:!1,error:(S==null?void 0:S.error)||"Could not launch IDE"}:(t({machineId:p,kind:"ide",providerType:g,workspacePath:(y==null?void 0:y.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(C){return{ok:!1,error:C instanceof Error?C.message:"Could not launch IDE"}}},[e,t]),u=i.useCallback(async(p,g,y,x)=>{var S,w,M;const C=Date.now();try{const L={cliType:y};(S=x==null?void 0:x.workspacePath)!=null&&S.trim()?L.dir=x.workspacePath.trim():x!=null&&x.workspaceId&&(L.workspaceId=x.workspaceId),(w=x==null?void 0:x.resumeSessionId)!=null&&w.trim()&&(L.resumeSessionId=x.resumeSessionId.trim()),Array.isArray(x==null?void 0:x.cliArgs)&&x.cliArgs.length>0&&(L.cliArgs=x.cliArgs),(M=x==null?void 0:x.initialModel)!=null&&M.trim()&&(L.initialModel=x.initialModel.trim());const j=await e(p,"launch_cli",L),k=(j==null?void 0:j.result)||j,B=(k==null?void 0:k.sessionId)||(k==null?void 0:k.id);return j!=null&&j.success&&B?(t({machineId:p,kind:g,providerType:y,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,launchedSessionId:B,startedAt:C}),{ok:!0}):j!=null&&j.success?(t({machineId:p,kind:g,providerType:y,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(j==null?void 0:j.error)||(k==null?void 0:k.error)||`Could not launch ${g.toUpperCase()} session`}}catch(L){return Yi(L)?(t({machineId:p,kind:g,providerType:y,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:L instanceof Error?L.message:`Could not launch ${g.toUpperCase()} session`}}},[r,e,t]),f=i.useCallback(async p=>{var g;if(c!=null&&c.listMeshes)return c.listMeshes(p);if(!p)return[];try{const y=await e(p,"list_meshes",{}),x=(y==null?void 0:y.result)??y;if((x==null?void 0:x.success)===!1)throw new Error((x==null?void 0:x.error)||"Could not load meshes");return(Array.isArray(x==null?void 0:x.meshes)?x.meshes:Array.isArray((g=x==null?void 0:x.result)==null?void 0:g.meshes)?x.result.meshes:[]).map(S=>{var w;return{id:String((S==null?void 0:S.id)||""),name:String((S==null?void 0:S.name)||(S==null?void 0:S.id)||"Untitled mesh"),repoIdentity:(S==null?void 0:S.repoIdentity)||(S==null?void 0:S.repo_identity)||null,workspace:Array.isArray(S==null?void 0:S.nodes)&&S.nodes.length>0?String(((w=S.nodes[0])==null?void 0:w.workspace)||""):null,nodesCount:Array.isArray(S==null?void 0:S.nodes)?S.nodes.length:void 0,status:(S==null?void 0:S.status)||null}}).filter(S=>S.id)}catch(y){throw console.error("List meshes failed",y),y}},[c,e]),b=i.useCallback(async(p,g,y)=>{if(!g.trim())return{ok:!1,error:"Choose a mesh first."};if(c!=null&&c.launchMeshCoordinator)return c.launchMeshCoordinator(p,g,y);const x=Date.now();try{const C={meshId:g.trim()};y.trim()&&(C.cliType=y.trim());const S=await e(p,"launch_mesh_coordinator",C),w=(S==null?void 0:S.result)??S;if((w==null?void 0:w.success)===!1||(S==null?void 0:S.success)===!1){const L=String((w==null?void 0:w.code)||(S==null?void 0:S.code)||""),j=Fb((w==null?void 0:w.meshCoordinatorSetup)||(w==null?void 0:w.manualSetup)||(S==null?void 0:S.meshCoordinatorSetup)||(S==null?void 0:S.manualSetup));return{ok:!1,error:(w==null?void 0:w.error)||(S==null?void 0:S.error)||"Could not launch mesh coordinator",code:L||void 0,manualSetup:j}}const M=(w==null?void 0:w.sessionId)||(w==null?void 0:w.id);return M?r(M):t({machineId:p,kind:"cli",providerType:(w==null?void 0:w.cliType)||y.trim()||void 0,workspacePath:(w==null?void 0:w.workspace)||null,startedAt:x}),{ok:!0}}catch(C){return Yi(C)?(t({machineId:p,kind:"cli",providerType:y.trim()||void 0,startedAt:x}),{ok:!0}):{ok:!1,error:C instanceof Error?C.message:"Could not launch mesh coordinator"}}},[c,r,e,t]),v=i.useCallback(async(p,g)=>{if(!p||!g)return[];try{const y=await e(p,"list_saved_sessions",{providerType:g,kind:"cli",limit:30}),x=(y==null?void 0:y.result)??y;return Array.isArray(x==null?void 0:x.sessions)?x.sessions:[]}catch(y){return console.error("List saved sessions failed",y),[]}},[e]),h=i.useCallback(async p=>{await td({conversation:n,mode:p,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:l,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:f,handleLaunchMeshCoordinator:b,handleListMachineSavedSessions:v,setActiveCliViewMode:h}}function Gb(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 qb(e,t,r=Date.now()){return!e||!Gb(t)?null:{tabKey:e,nonce:r}}function Yb({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:c}){const[l,d]=i.useState(null),[m,u]=i.useState(null),f=i.useMemo(()=>{var g,y;if(!e){if(l){const x=t.find(C=>C.tabKey===l);if(x)return x}return r[0]}const p=n[a];if(p){const x=t.find(C=>C.tabKey===p);if(x)return x}return((g=o[a])==null?void 0:g[0])||((y=o[0])==null?void 0:y[0])},[t,l,a,n,o,e,r]),b=i.useCallback(p=>{d(p)},[]),v=i.useCallback(p=>{d(p.tabKey),c(g=>{const y=new URLSearchParams(g),x=lf(p);return x?y.set("activeTab",x):y.delete("activeTab"),y},{replace:!0})},[c]),h=i.useCallback((p,g)=>{const y=qb(p,g);y&&u(y)},[]);return{activeConv:f,openDesktopConversation:v,requestScrollToBottom:h,scrollToBottomRequest:m,setDesktopActiveTab:b}}function Xb(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 Jb(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&t&&t!==r),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Qb({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=i.useRef(null),o=i.useRef(null),c=i.useRef(null),l=i.useRef(null),d=i.useRef(null);i.useEffect(()=>{const m=()=>{c.current&&(clearTimeout(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const u=mn(e,r),f=Jb({tabKey:e.tabKey,historySessionId:Nr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:ps(e),liveState:u}),b=f.autoReadKey,v=Xb({autoReadKey:b,shouldMarkSeen:f.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!f.shouldMarkSeen){v.shouldCancelPending&&m(),a.current=b;return}if(!v.shouldSchedule)return;v.shouldCancelPending&&m();const h=()=>{if(document.visibilityState!=="visible"||a.current===b)return;a.current=b,o.current=null,c.current=null,l.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const g=f.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:g,completionMarker:f.completionMarker}).catch(()=>{})};if(o.current=v.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(h,1500);const g=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};d.current=g,document.addEventListener("visibilitychange",g);return}const p=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(h,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),i.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function ca(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const r=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(r)?r:""}function Zb({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:c,setClearedTabs:l,setSearchParams:d}){var N;const[m,u]=i.useState(!1),[f,b]=i.useState([]),[v,h]=i.useState(()=>jt()),[p,g]=i.useState(!1),[y,x]=i.useState(null),C=i.useRef(null),S=i.useMemo(()=>r||t||e,[e,r,t]),w=!!S&&st(S)&&!Ze(S),M=i.useMemo(()=>{if(!S||!w)return null;const K=S.daemonId||S.routeId||"",P=Kt(S),E=ca(S);return`${K}:${P}:${S.providerSessionId||""}:${E}`},[S,w]),L=i.useMemo(()=>!S||!w?"":ca(S),[S,w]),{isCreatingChat:j,isRefreshingHistory:k,handleSwitchSession:B,handleNewChat:_,handleRefreshHistory:T}=cd({sendDaemonCommand:a,activeConv:S,chats:(N=n.find(K=>K.id===(S==null?void 0:S.routeId)))==null?void 0:N.chats,updateRouteChats:o,setToasts:c,setClearedTabs:l}),F=i.useCallback(()=>{u(!0)},[]),H=i.useCallback(()=>{u(!1)},[]),R=i.useCallback(async()=>{if(!(!S||!w||p)){g(!0);try{const K=S.daemonId||S.routeId,P=Kt(S),E=ca(S),U=await a(K,"list_saved_sessions",{agentType:P,providerType:P,kind:"cli",limit:50,...S.providerSessionId?{providerSessionId:S.providerSessionId}:{},...E?{workspace:E}:{}}),ee=(U==null?void 0:U.result)??U;b(Array.isArray(ee==null?void 0:ee.sessions)?ee.sessions:[])}catch(K){console.error("Refresh saved sessions failed",K),b([])}finally{g(!1)}}},[S,p,w,a]);i.useEffect(()=>{if(!m){C.current=null;return}if(!w){C.current=null,b([]),g(!1);return}!M||p||C.current!==M&&(C.current=M,R())},[R,m,p,w,M]);const I=i.useCallback(async K=>{if(!S||!w||!K.providerSessionId||!K.workspace)return;const P=S.daemonId||S.routeId,E=Kt(S);try{x(K.providerSessionId);const U=await a(P,"launch_cli",{cliType:E,dir:K.workspace,resumeSessionId:K.providerSessionId,initialModel:tl(K.summaryMetadata,"model",{preferShortValue:!0})||void 0}),ee=(U==null?void 0:U.result)??U,ye=typeof(ee==null?void 0:ee.sessionId)=="string"?ee.sessionId:typeof(ee==null?void 0:ee.id)=="string"?ee.id:"";ye&&d(le=>{const Q=new URLSearchParams(le);return Q.set("activeTab",ye),Q},{replace:!0}),H()}catch(U){console.error("Resume saved session failed",U)}finally{x(null)}},[H,S,w,a,d]);return{historyModalOpen:m,openHistoryModal:F,closeHistoryModal:H,historyTargetConv:S,isSavedSessionHistoryTarget:w,isHistoryCreatingChat:j,isHistoryRefreshingHistory:k,handleHistorySwitchSession:B,handleHistoryNewChat:_,handleHistoryRefresh:T,savedHistorySessions:f,savedHistoryFilters:v,setSavedHistoryFilters:h,missingWorkspaceResumePath:L,isSavedHistoryLoading:p,resumingSavedHistorySessionId:y,handleRefreshSavedHistory:R,handleResumeSavedHistorySession:I}}function eg({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}){const[d,m]=i.useState(null),[u,f]=i.useState(null),b=i.useMemo(()=>{if(e||!n)return null;const y=l(n);return y&&!st(y)&&!Ze(y)?y:null},[e,n,l]),v=i.useMemo(()=>{const y=d==null?void 0:d.routeId;if(!y)return null;const x=d!=null&&d.tabKey?o.find(C=>C.tabKey===d.tabKey):a?o.find(C=>C.tabKey===a):null;return(x==null?void 0:x.routeId)===y?x:Dt(o,y)},[o,d,a]),h=i.useMemo(()=>{if(v)return c.find(y=>y.id===v.routeId)},[c,v]);i.useEffect(()=>{b&&(m({routeId:b.routeId,tabKey:vi(b)}),f(b),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,b]);const p=i.useCallback(y=>{y&&(m({routeId:y.routeId,tabKey:vi(y)}),f(y))},[]),g=i.useCallback(()=>{m(null),f(null)},[]);return{remoteDialogConv:v,remoteDialogIdeEntry:h,remoteDialogActiveConv:u,setRemoteDialogActiveConv:f,openRemoteDialog:p,closeRemoteDialog:g}}function tg({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:f,remoteDialogActiveConv:b,setRemoteDialogActiveConv:v,openRemoteDialog:h,closeRemoteDialog:p}=eg({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:c,resolveConversationByTarget:l}),[g,y]=i.useState(!1),[x,C]=i.useState(null),S=i.useCallback(async L=>{const j=L||d;!j||!st(j)&&!Ze(j)||(C(j),y(!0))},[d]),w=i.useCallback(()=>{y(!1),C(null)},[]),M=i.useCallback(async L=>{const j=x||d;if(!j||!st(j)&&!Ze(j)){w();return}y(!1);try{const k=Kt(j),B=j.routeId||j.daemonId||"";await m(B,"stop_cli",{cliType:k,targetSessionId:j.sessionId,mode:L})}catch(k){console.error("Stop CLI failed:",k)}finally{C(null)}},[d,w,x,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:f,remoteDialogActiveConv:b,setRemoteDialogActiveConv:v,openRemoteDialog:h,closeRemoteDialog:p,cliStopDialogOpen:g,cliStopTargetConv:x,requestCliStop:S,cancelCliStop:w,confirmCliStop:M}}function xd({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var C,S;const c=Ws(),l=ws(e),d=o?null:cl(e),m=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!o&&e.streamSource==="agent-stream"&&!!e.agentName,f=!o&&!u&&(e.transport==="pty"||e.transport==="acp"),b=Es(e),v=cf(e),h=(C=e.settings)==null?void 0:C.meshNodeFor,p=e.meshQueueStats,g=(S=e.settings)==null?void 0:S.meshCoordinatorFor;if(!m&&!u&&!f&&!d&&!h&&!p)return null;const y=i.useCallback(()=>{if(n){n();return}l&&c("/dashboard",{state:{openMachineId:l}})},[l,c,n]),x=i.useCallback(()=>{if(r){r();return}const w=pd(e);w&&c(Zt(w))},[e,c,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[m&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:x,title:v,children:[s.jsx(It,{size:12}),s.jsx("span",{children:v})]}):s.jsxs("span",{className:"conversation-meta-chip",title:v,children:[s.jsx(It,{size:12}),s.jsx("span",{children:v})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[s.jsx(Ds,{size:12}),s.jsx("span",{children:b})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[s.jsx(Ds,{size:12}),s.jsx("span",{children:b})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:d,children:[s.jsx(Jt,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(Jt,{size:12}),s.jsx("span",{children:d})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Jt,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),g&&p&&s.jsxs("span",{className:`conversation-meta-chip ${p.pending>0?"is-active":""}`,style:p.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${p.pending} pending, ${p.assigned} assigned, ${p.completed} completed, ${p.failed} failed`,children:[s.jsx(im,{size:12}),s.jsxs("span",{children:[p.pending," Pending"]})]})]})}function la(e,t=!0){return(e??!0)&&t}const $o=i.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:c,handleRelaunch:l,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u=null,handleFocusAgent:f,isFocusingAgent:b,actionLogs:v,userName:h,scrollToBottomRequestNonce:p,isInputActive:g=!0,isVisible:y=!0}){const x=n,C=!n,S=la(y,x),w=la(y,C),M=la(y),L=Yl(t),j=L.status||L.modalMessage||L.modalButtons?{...t,...L.status?{status:L.status}:{},...L.modalMessage!==void 0?{modalMessage:L.modalMessage}:{},...L.modalButtons!==void 0?{modalButtons:L.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Qc,{activeConv:j,onModalButton:c}),s.jsx(xd,{conversation:j,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),j.transport!=="pty"&&j.transport!=="acp"&&j.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(gr,{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,j.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:x?"visible":"hidden",pointerEvents:x?"auto":"none"},children:s.jsx(jh,{activeConv:j,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,isVisible:S,isInputActive:g&&S})}),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(Wa,{activeConv:j,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:b,actionLogs:v,userName:h,scrollToBottomRequestNonce:p,isInputActive:g&&w,isVisible:w})})]}):s.jsx(Wa,{activeConv:j,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:b,actionLogs:v,userName:h,scrollToBottomRequestNonce:p,isInputActive:g&&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 sg({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:f,onOpenHistory:b,onOpenRemote:v,onStopCli:h,cliViewMode:p,onSetCliViewMode:g,handleSendChat:y,handleFocusAgent:x,handleModalButton:C,handleRelaunch:S}){const w=i.useRef(null),M=st(e)&&!t,L=M&&p==="terminal",j=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 ${j} 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(no,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:ct(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(xd,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>f(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[M&&p&&s.jsx(So,{mode:p,onChange:g,compact:!0}),M&&h&&s.jsx("button",{onClick:()=>{h(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(gt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",children:s.jsx(ao,{size:14})}),!t&&!M&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),type:"button",children:s.jsx(It,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx($o,{activeConv:e,clearToken:0,isCliTerminal:L,ideEntry:n,terminalRef:w,handleModalButton:C,handleRelaunch:S,handleSendChat:y,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:x,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const da={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 rg(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function bd(){const[e,t]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),c=e==="unix"?"unix":r;i.useEffect(()=>{t(rg())},[]);const l=i.useCallback(()=>{navigator.clipboard.writeText(da[c].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!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:da[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:da[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 gd({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:It},{key:"chats",label:"Chats",icon:zt}];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:o})=>{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(o,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function Hr({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 js({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 sr({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 ng({conversation:e,onCancel:t,onConfirm:r}){const n=ct(e),a=gs(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"fade-in relative w-full sm:w-[min(92vw,420px)] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] border border-border-subtle bg-bg-primary shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),s.jsx("div",{className:"mt-1 text-[13px] leading-relaxed text-text-muted",children:"This only collapses the chat locally. You can restore it from Hidden tabs."})]}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary text-text-secondary transition-colors hover:bg-surface-primary hover:text-text-primary",onClick:t,"aria-label":"Cancel hide chat",children:s.jsx(gt,{size:16})})]}),s.jsx("div",{className:"px-4 py-4",children:s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[s.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),s.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border-subtle bg-bg-secondary px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))]",children:[s.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:t,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function Ur({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onCollectChatDebugBundle:o}){const c=t==="needs_attention"||t==="task_complete",l=t==="working",d=t==="earlier",m=t==="task_complete",{isReconnecting:u,isConnecting:f}=Hs(e.conversation),b=ct(e.conversation),v=gs(e.conversation),h=Tl(e.conversation,{requiresAction:t==="needs_attention"}),p=c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":l?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":d?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",g=c?"bg-accent-primary shadow-glow":l?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":d?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",y=d?"text-text-secondary":"text-text-primary",x=d?"text-text-muted":"text-text-secondary",C=d?"text-text-secondary opacity-80":"text-text-muted",S=d?"text-text-muted opacity-80":"text-text-muted",w=!l&&!m,M="text-[color:var(--status-warning)]",L=j=>{if(!o)return;j.preventDefault(),j.stopPropagation();const k=o==null?void 0:o(e.conversation);Promise.resolve(k).catch(B=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",B)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${p}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[c||l?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${g}`,style:c?{color:"var(--accent-on-primary)"}:void 0,children:r(b)}),a&&s.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:j=>{j.preventDefault(),j.stopPropagation(),a()},"aria-label":`Hide ${b}`,title:"Hide conversation",children:[s.jsx(oo,{size:11}),s.jsx("span",{children:"Hide"})]})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:L,type:"button",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${y}`,children:b}),w&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${S}`,children:Jc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${x}`,children:[s.jsx("span",{className:"truncate",children:v}),s.jsx(Bs,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),u?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${M} animate-pulse`,children:"Reconnecting…"})]}):f?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):h==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:M,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${C}`,children:e.preview})]}),c&&!m&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),m&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),l&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]})},e.conversation.tabKey)}function Xi({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 ag({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:c,getAvatarText:l,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:f,onHideConversation:b,onOpenNewSession:v,onOpenMachine:h,onOpenSettings:p,onSectionChange:g,wsStatus:y="connected",isStandalone:x=!1,onCollectChatDebugBundle:C}){const[S,w]=i.useState(null),M=y==="disconnected"||y==="reconnecting"||y==="offline"||y==="auth_failed",L=c.length>0,j=t.length>0||r.length>0||n.length>0||a.length>0,k=e==="machines"?"Machines":"Chats",B=x?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",_=x?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",T=i.useCallback(async R=>{const I=$s(R);if(!I)return;const N=Array.isArray(R.messages)?R.messages:[],K=fl({activeConv:R,visibleMessages:N,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:N.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),P=await m(I,"get_chat_debug_bundle",{...is(R),delivery:"daemon_file",frontendSnapshot:K}),E=xn(P),U=bl(E),ee=await xl(U);ee==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),nt.showToast(hl(E,{locatorCopyStatus:ee}),ee==="failed"?"warning":"success")},[d,m]),F=C||T,H=i.useCallback(()=>{S&&(b==null||b(S),w(null))},[S,b]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${B}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:k}),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(Cn,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:p,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(Nn,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${_}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?s.jsx(sr,{icon:s.jsx(Xi,{}),title:y==="offline"?"Network offline":y==="auth_failed"?"Session expired":"Reconnecting",subtitle:y==="offline"?"Waiting for network…":y==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(sr,{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(bd,{})})}):s.jsx(js,{children:c.map((R,I)=>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] ${I>0?"border-t border-border-subtle/70":""}`,onClick:()=>h(R.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(R.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:R.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:R.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[R.unread," new"]}):R.total>0?`${R.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:R.subtitle}),R.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[R.total," chat",R.total!==1?"s":"",R.unread>0?` · ${R.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},R.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(Hr,{title:"Needs attention",className:"mb-0"}),s.jsx(js,{children:t.map((R,I)=>s.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:s.jsx(Ur,{item:R,type:"needs_attention",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:b?()=>w(R.conversation):void 0,onCollectChatDebugBundle:F})},R.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(Hr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(js,{children:r.map((R,I)=>s.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:s.jsx(Ur,{item:R,type:"task_complete",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:b?()=>w(R.conversation):void 0,onCollectChatDebugBundle:F})},R.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(Hr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(js,{children:n.map((R,I)=>s.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:s.jsx(Ur,{item:R,type:"working",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:b?()=>w(R.conversation):void 0,onCollectChatDebugBundle:F})},R.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(Hr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(js,{children:a.map((R,I)=>s.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:s.jsx(Ur,{item:R,type:"earlier",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:b?()=>w(R.conversation):void 0,onCollectChatDebugBundle:F})},R.conversation.tabKey))}):j?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):M?s.jsx(sr,{icon:s.jsx(Xi,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):L?s.jsx(sr,{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(zt,{size:20})}),title:"No conversations yet",subtitle:Ll,children:v&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:v,"aria-label":Bt,title:Bt,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:Bt})]})}):s.jsx(sr,{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"&&o.length>0&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(js,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[o.length," collapsed ",o.length===1?"conversation":"conversations"]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:f,children:"Restore all"})]})})})]}),e==="chats"&&v&&j&&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:v,"aria-label":Bt,title:Bt,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),S&&s.jsx(ng,{conversation:S,onCancel:()=>w(null),onConfirm:H}),s.jsx(gd,{section:e,onSectionChange:g})]})}function og(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 yd(e){const t=[e.workspace||"Workspace unknown"],r=bs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=og(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function $n({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:c="Use this folder",onClose:l,onNavigate:d,onConfirm:m}){const[u,f]=i.useState(r);i.useEffect(()=>{f(r)},[r]);const b=Bb(r),v=u.trim();return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:s.jsx(gt,{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:()=>{!b||a||d(b)},disabled:!b||a,children:[s.jsx(no,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:h=>f(h.target.value),onKeyDown:h=>{h.key!=="Enter"||!v||a||(h.preventDefault(),d(v))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!v||a||d(v)},disabled:!v||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):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(h=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(h.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(xs,{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:h.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:h.path})]})]},h.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(v||r),disabled:!v&&!r||a,children:c})]})]})})}function Bo({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:f,showModelInput:b,modelValue:v,onModelChange:h,historyProviderNode:p,onConfirm:g,onCancel:y}){const x=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(gt,{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&&o&&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=>o(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:d,children:n.map(C=>s.jsx("option",{value:C.key,children:C.label},C.key))}),(x==null?void 0:x.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:x.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}`)),b&&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:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:v||"",onChange:C=>h(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:d})]}),m&&f&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:C=>f(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:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,disabled:d,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:g,disabled:d,children:[s.jsx(co,{size:14}),d?l:c]})]})]})})}function Ji(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function fs(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,o=[];a&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])o.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${Ji(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(d=>d.path===c):null;if(c&&!l&&o.push({key:`custom:${c}`,label:Ji(c),description:c,workspaceId:null,workspacePath:c}),n){const d=`saved:${n}`;if(o.some(m=>m.key===d))return{options:o,selectedKey:d}}return l?{options:o,selectedKey:`saved:${l.id}`}:c?{options:o,selectedKey:`custom:${c}`}:{options:o,selectedKey:"__home__"}}function ig(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function cg(e){return[ig(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function lg(e){return e.lastLaunchedAt?In(e.lastLaunchedAt):""}function vd(e){return{metaText:cg(e),updatedLabel:lg(e)}}function ua(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function dg({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var et,dt,pt,bt;const c=Sr(),[l,d]=i.useState(!1),m=(((et=e.detectedIdes)==null?void 0:et.length)||0)>0,u=i.useMemo(()=>(e.workspaces||[]).map(Ce=>({id:Ce.id,path:Ce.path,label:Ce.label})),[e]),f=e.defaultWorkspaceId||null,[b,v]=i.useState(f||((dt=u[0])==null?void 0:dt.id)||""),[h,p]=i.useState(""),[g,y]=i.useState(""),[x,C]=i.useState([]),[S,w]=i.useState(!1),[M,L]=i.useState(""),[j,k]=i.useState(!1),[B,_]=i.useState(ua(m,t.length,r.length)),T=i.useRef(null),[F,H]=i.useState(null),R=i.useRef("__home__"),[I,N]=i.useState("__home__"),[K,P]=i.useState(""),[E,U]=i.useState(""),[ee,ye]=i.useState(""),[le,Q]=i.useState([]),[xe,we]=i.useState(()=>jt().textQuery),[be,X]=i.useState(()=>jt().workspaceQuery),[ue,fe]=i.useState(()=>jt().modelQuery),[ve,pe]=i.useState(()=>jt().resumableOnly),[Se,Z]=i.useState(()=>jt().sortMode),[de,oe]=i.useState(!1),[me,ie]=i.useState(!1),D=i.useRef(null),z=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const ce=b==="__custom__"?h.trim():((pt=u.find(Ce=>Ce.id===b))==null?void 0:pt.path)||"",re=b==="__custom__"&&!!ce&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),G=b!=="__custom__"&&((bt=u.find(Ce=>Ce.id===b))==null?void 0:bt.path)||"",je=i.useMemo(()=>(e.recentLaunches||[]).map(Ce=>Ce.workspace),[e]),ge=i.useCallback(async Ce=>{w(!0),L("");try{const Ue=await a(Ce);y(Ue.path),p(Ue.path),C(Ue.directories)}catch(Ue){L(Ue instanceof Error?Ue.message:"Could not load folder")}finally{w(!1)}},[a]),Ae=i.useCallback(()=>{var Ue;v("__custom__"),k(!0);const Ce=Dn(e.platform,Pn(h.trim(),G,je,e.defaultWorkspacePath,(Ue=u.find(Qe=>Qe.id===f))==null?void 0:Ue.path,u.map(Qe=>Qe.path)));ge(Ce)},[h,f,ge,je,G,e.platform,u]),Me=i.useCallback(Ce=>{if(Ce!=null&&Ce.workspaceId){v(Ce.workspaceId),p("");return}if(Ce!=null&&Ce.workspacePath){v("__custom__"),p(Ce.workspacePath);return}v(""),p("")},[]),O=i.useCallback(Ce=>{if(v(Ce),Ce==="__custom__"){Ae();return}p("")},[Ae]),Ne=i.useCallback(Ce=>{v("__custom__"),p(Ce)},[]),Re=i.useCallback((Ce,Ue)=>{T.current=Ue,R.current=Ce.selectedWorkspaceKey||"__home__",N(Ce.selectedWorkspaceKey||"__home__"),P(Ce.initialArgs||""),U(Ce.initialModel||""),ye(""),Q([]);const Qe=Ce.providerType?`${e.id}:${Ce.providerType}`:null;if(_h(z.current,Qe)){const ze=jt();we(ze.textQuery),X(ze.workspaceQuery),fe(ze.modelQuery),pe(ze.resumableOnly),Z(ze.sortMode)}z.current=Qe,H(Ce),Ce.providerType&&o&&(oe(!0),o(Ce.providerType).then(ze=>Q(ze||[])).catch(ze=>console.warn("Failed to load saved sessions",ze)).finally(()=>oe(!1)))},[o,e.id]),Fe=i.useMemo(()=>Rl(le,{textQuery:xe,workspaceQuery:be,modelQuery:ue,resumableOnly:ve,sortMode:Se}),[ue,ve,le,Se,xe,be]);i.useEffect(()=>{ee&&(Fe.some(Ce=>Ce.providerSessionId===ee)||ye(""))},[Fe,ee]);const He=i.useCallback(()=>{T.current&&(ie(!0),T.current().finally(()=>{T.current=null,ie(!1),H(null)}))},[]),Ge=i.useCallback(()=>{T.current=null,H(null)},[]),qe=i.useCallback(Ce=>{R.current=Ce,N(Ce)},[]);return i.useEffect(()=>{var Ce;D.current!==e.id&&(D.current=e.id,v(f||((Ce=u[0])==null?void 0:Ce.id)||"__custom__"),p(""),y(""),C([]),L(""),k(!1),we(jt().textQuery),X(jt().workspaceQuery),fe(jt().modelQuery),pe(jt().resumableOnly),Z(jt().sortMode),z.current=null,_(ua(m,t.length,r.length)))},[r.length,t.length,f,m,e.id,u]),i.useEffect(()=>{var Ce;b!=="__custom__"&&(b&&u.some(Ue=>Ue.id===b)||v(f||((Ce=u[0])==null?void 0:Ce.id)||"__custom__"))},[f,b,u]),i.useEffect(()=>{B==="ide"&&m||B==="cli"&&t.length>0||B==="acp"&&r.length>0||_(ua(m,t.length,r.length))},[B,r.length,t.length,m]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:f,workspaceChoice:b,customWorkspacePath:h,browseCurrentPath:g,browseDirectories:x,browseBusy:S,browseError:M,browseDialogOpen:j,activeLauncherKind:B,launchConfirm:F,launchConfirmWorkspaceKeyRef:R,launchConfirmWorkspaceKey:I,launchConfirmArgs:K,launchConfirmModel:E,launchConfirmResumeId:ee,launchConfirmSavedSessions:le,launchConfirmTextFilter:xe,launchConfirmWorkspaceFilter:be,launchConfirmModelFilter:ue,launchConfirmResumableOnly:ve,launchConfirmSortMode:Se,filteredLaunchConfirmSavedSessions:Fe,launchConfirmSessionsLoading:de,launchConfirmBusy:me,resolvedWorkspacePath:ce,canCreateMissingWorkspace:re,openBrowseDialog:Ae,loadBrowsePath:ge,handleWorkspaceChoiceChange:O,chooseCustomWorkspacePath:Ne,setCustomWorkspacePath:p,setBrowseDialogOpen:k,setActiveLauncherKind:_,openLaunchConfirm:Re,handleConfirmLaunch:He,closeLaunchConfirm:Ge,setWorkspaceSelectionFromOption:Me,setLaunchConfirmWorkspaceKeyAndSync:qe,setLaunchConfirmArgs:P,setLaunchConfirmModel:U,setLaunchConfirmResumeId:ye,setLaunchConfirmTextFilter:we,setLaunchConfirmWorkspaceFilter:X,setLaunchConfirmModelFilter:fe,setLaunchConfirmResumableOnly:pe,setLaunchConfirmSortMode:Z}}function ug({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:c,machineAction:l,isStandalone:d,section:m,showBottomNav:u,onBack:f,onSectionChange:b,onOpenConversation:v,onOpenRecent:h,onOpenMachineDetails:p,onMachineUpgrade:g,onLaunchDetectedIde:y,onAddWorkspace:x,onBrowseDirectory:C,onLaunchWorkspaceProvider:S,onListSavedSessions:w}){const M=I=>I==="ide"?"IDE":I==="cli"?"CLI":"ACP",L=r.slice(0,4),j=t.slice(0,3),k=dg({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:C,onListSavedSessions:w}),B=i.useMemo(()=>L.map(I=>{const{metaText:N,updatedLabel:K}=vd(I);return{key:`recent-launch:${I.id}`,primary:I.label,secondary:N,updatedLabel:K,onClick:()=>{const{options:P,selectedKey:E}=fs({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspacePath:I.workspace});k.openLaunchConfirm({title:I.kind==="ide"?ls("restart-ide",I.label):I.providerSessionId?Io(I.label):ls("start-fresh",I.label),description:I.kind==="ide"?ds("restart-ide"):I.providerSessionId?To():ds("start-fresh"),confirmLabel:I.kind==="ide"?Os("restart-ide"):I.providerSessionId?gn(!0):Os("start-fresh"),busyLabel:I.kind==="ide"?Ks("restart-ide"):I.providerSessionId?No(!0):Ks("start-fresh"),workspaceOptions:P,selectedWorkspaceKey:E,details:[{label:"Mode",value:M(I.kind)},...I.providerType?[{label:"Provider",value:I.providerType}]:[]]},async()=>{const U=P.find(ee=>ee.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption(U),await h({...I,workspace:(U==null?void 0:U.workspacePath)??null})})}}}),[k,h,L]),_=i.useMemo(()=>j.map(I=>({key:`recent-chat:${I.conversation.tabKey}`,primary:ct(I.conversation),secondary:gh(I.conversation,{timestampLabel:I.timestamp?Jc(I.timestamp):null}),unread:I.unread,onClick:()=>v(I.conversation)})),[v,j]),T=k.showAllRecent?B:B.slice(0,4),F=B.length>0,H=_.length>0,R=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${R} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:f,type:"button","aria-label":"Back",children:s.jsx(no,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Ct(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[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:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:_.map(I=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${I.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:I.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:I.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:I.secondary})]},I.key))})]}),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:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:T.map(I=>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:I.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:I.primary}),I.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:I.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:I.secondary})]},I.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:()=>k.setShowAllRecent(I=>!I),children:k.showAllRecent?"Show fewer":`Show ${B.length-4} more`})})]}),(k.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:k.workspaceChoice,onChange:I=>k.handleWorkspaceChoiceChange(I.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:k.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[k.workspaceRows.map(I=>s.jsxs("option",{value:I.id,children:[I.id===k.defaultWorkspaceId?"⭐ ":"",Mn(I.path,I.label)||I.path]},I.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),k.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(xs,{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:k.resolvedWorkspacePath||k.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:k.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:()=>{k.resolvedWorkspacePath&&x(k.resolvedWorkspacePath)},disabled:!k.resolvedWorkspacePath||k.browseBusy,children:"Save as workspace"})]})]}),k.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[k.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.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:()=>k.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.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:()=>k.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.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:()=>k.setActiveLauncherKind("acp"),children:"ACP"})]}),k.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:k.activeLauncherKind==="ide"?"Choose an IDE":k.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:k.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(I=>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:N,selectedKey:K}=fs({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspaceId:k.workspaceChoice!=="__custom__"?k.workspaceChoice:null,currentWorkspacePath:k.resolvedWorkspacePath});k.openLaunchConfirm({title:`Launch ${I.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:N,selectedWorkspaceKey:K,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:I.name}]},async()=>{const P=N.find(E=>E.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption(P),y(I.type,{workspacePath:(P==null?void 0:P.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:I.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath||"Use selected workspace"})]},I.type)):(k.activeLauncherKind==="cli"?n:a).map(I=>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 N=k.activeLauncherKind==="cli"?"cli":"acp",{options:K,selectedKey:P}=fs({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspaceId:k.workspaceChoice!=="__custom__"?k.workspaceChoice:null,currentWorkspacePath:k.resolvedWorkspacePath});k.openLaunchConfirm({title:`Launch ${I.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${N.toUpperCase()}`,workspaceOptions:K,selectedWorkspaceKey:P,details:[{label:"Mode",value:N.toUpperCase()},{label:"Provider",value:I.displayName}],showArgsInput:!0,showModelInput:N==="acp",initialArgs:"",initialModel:"",providerType:I.type},async()=>{const E=K.find(U=>U.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption(E),S(N,I.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.workspacePath)??null,args:k.launchConfirmArgs,model:k.launchConfirmModel,resumeSessionId:k.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[I.icon?`${I.icon} `:"",I.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath||"Use selected workspace"})]},I.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,k.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:()=>x(k.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:[o&&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:g,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"})]})]})]})]}),k.browseDialogOpen&&s.jsx($n,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:k.browseCurrentPath,directories:k.browseDirectories,busy:k.browseBusy,error:k.browseError,confirmLabel:"Use this folder",onClose:()=>k.setBrowseDialogOpen(!1),onNavigate:I=>{k.loadBrowsePath(I)},onConfirm:I=>{k.chooseCustomWorkspacePath(I),k.setBrowseDialogOpen(!1)}}),k.launchConfirm&&s.jsx(Bo,{title:k.launchConfirm.title,description:k.launchConfirm.description,details:k.launchConfirm.details,workspaceOptions:k.launchConfirm.workspaceOptions,selectedWorkspaceKey:k.launchConfirmWorkspaceKey,onWorkspaceChange:k.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:k.launchConfirm.providerType?gn(!!k.launchConfirmResumeId):k.launchConfirm.confirmLabel,busyLabel:k.launchConfirm.providerType?void 0:k.launchConfirm.busyLabel,busy:k.launchConfirmBusy,showArgsInput:k.launchConfirm.showArgsInput,argsValue:k.launchConfirmArgs,onArgsChange:k.setLaunchConfirmArgs,showModelInput:k.launchConfirm.showModelInput,modelValue:k.launchConfirmModel,onModelChange:k.setLaunchConfirmModel,historyProviderNode:k.launchConfirm.providerType&&(k.launchConfirmSessionsLoading||k.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"}),k.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:Co()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:k.launchConfirmTextFilter,onChange:I=>k.setLaunchConfirmTextFilter(I.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:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:k.launchConfirmWorkspaceFilter,onChange:I=>k.setLaunchConfirmWorkspaceFilter(I.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:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:k.launchConfirmModelFilter,onChange:I=>k.setLaunchConfirmModelFilter(I.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:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),s.jsxs("select",{value:k.launchConfirmSortMode,onChange:I=>k.setLaunchConfirmSortMode(I.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.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:k.launchConfirmResumableOnly,onChange:I=>k.setLaunchConfirmResumableOnly(I.target.checked),disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:k.launchConfirmResumeId,onChange:I=>k.setLaunchConfirmResumeId(I.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Eh()}),k.filteredLaunchConfirmSavedSessions.map(I=>s.jsxs("option",{value:I.providerSessionId,disabled:!I.canResume,children:[I.title||I.providerSessionId," ",I.canResume?"":"(workspace missing)"]},I.providerSessionId))]}),!k.launchConfirmSessionsLoading&&k.launchConfirmSavedSessions.length>0&&k.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),k.launchConfirmResumeId&&(()=>{const I=k.filteredLaunchConfirmSavedSessions.find(K=>K.providerSessionId===k.launchConfirmResumeId);if(!I)return null;const N=yd(I);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:N.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:N.providerSessionId}),s.jsx("div",{className:"mt-1",children:N.metaLine}),N.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:N.updatedLabel}),N.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:N.preview})]})})()]}),onConfirm:k.handleConfirmLaunch,onCancel:k.closeLaunchConfirm}),u&&s.jsx(gd,{section:m,onSectionChange:b})]})}function sn(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function mg(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:sn(e)}function pg(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 fg(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:bs(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;const a=yr(n)?"cli":As(n)?"acp":"ide",o=bs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(yr(n)?n.cliName||n.type:As(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:As(n)?o||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:n.lastMessageAt||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function hg(e,t){const r=new Map;for(const n of t){const a=ws(n.conversation),o=r.get(a);o?o.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],o=[...a].sort((f,b)=>b.timestamp-f.timestamp)[0]||null,c=(o==null?void 0:o.conversation)||null,l=$a(n),d=a.filter(f=>f.unread||f.requiresAction).length,m=pg(n),u=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Ct(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:c,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:l,preview:c?yh(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const o=n.latestTimestamp||n.fallbackActivityAt||0,c=a.latestTimestamp||a.fallbackActivityAt||0;return c!==o?c-o:n.label.localeCompare(a.label)})}function xg(e){return e==="chat"}function zr(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 bg({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:b,onRequestedMobileSectionConsumed:v,setSelectedTabKey:h,setScreen:p,setSelectedMachineId:g,setSection:y,setMachineBackTarget:x,resetMachineAction:C}){const S=i.useRef(null),w=i.useCallback(M=>{if(!(M!=null&&M.sessionId))return;const L=mn(M,c),j=Math.max(Date.now(),ps(M),L.lastUpdated||0);zr("mark_read:start",{tabKey:M.tabKey,sessionId:M.sessionId,displayPrimary:ct(M),inboxBucket:L.inboxBucket,unread:L.unread,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,activityAt:ps(M),readAt:j}),l(ws(M)||M.routeId,"mark_session_seen",{sessionId:M.sessionId,providerSessionId:M.providerSessionId,seenAt:j,completionMarker:L.completionMarker}).then(k=>{zr("mark_read:result",{tabKey:M.tabKey,sessionId:M.sessionId,result:k})}).catch(k=>{zr("mark_read:error",{tabKey:M.tabKey,sessionId:M.sessionId,error:k instanceof Error?k.message:String(k)})})},[c,l]);return i.useEffect(()=>{var L;if(!n){xg(o)&&p("inbox"),h(((L=e[0])==null?void 0:L.tabKey)||null),S.current=null;return}if(o!=="chat"){S.current=null;return}const M=`${n.tabKey}:${n.sessionId||""}`;S.current!==M&&(S.current=M,w(n))},[e,w,o,n,p,h]),i.useEffect(()=>{if(!d)return;const M=e.find(L=>L.tabKey===d);M&&(h(M.tabKey),p("chat"),m==null||m())},[e,m,d,p,h]),i.useEffect(()=>{if(!u)return;const M=t.find(L=>L.id===u);M&&(g(M.id),C(),y("machines"),x("inbox"),p("machine"),f==null||f())},[t,f,u,C,x,p,y,g]),i.useEffect(()=>{b&&(y(b),p("inbox"),v==null||v())},[v,b,p,y]),i.useEffect(()=>{const M=r.filter(L=>L.inboxBucket==="task_complete"||L.unread);M.length!==0&&zr("inbox_state",{screen:o,selectedTabKey:a,items:M.map(L=>{const j=mn(L.conversation,c);return{liveState:j,tabKey:L.conversation.tabKey,sessionId:L.conversation.sessionId,displayPrimary:ct(L.conversation),serverBucket:j.inboxBucket,computedBucket:L.inboxBucket,serverUnread:j.unread,computedUnread:L.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:ps(L.conversation)}})})},[r,c,o,a]),{markConversationRead:w}}function gg(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Qi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function yg(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function vg({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,o]=i.useState("idle"),[c,l]=i.useState(""),[d,m]=i.useState(null),u=i.useCallback(()=>{o("idle"),l(""),m(null)},[]),f=i.useCallback(async(x,C,S)=>{var w;try{o("loading"),l(`Launching ${C}…`);const M={ideType:C,enableCdp:!0};(w=S==null?void 0:S.workspacePath)!=null&&w.trim()&&(M.workspace=S.workspacePath.trim()),await e(x,"launch_ide",M),o("done"),l(`${C} launch requested`)}catch(M){o("error"),l(M instanceof Error?M.message:"Launch IDE failed"),console.error("Launch IDE failed",M)}},[e]),b=i.useCallback(async(x,C,S)=>{if(C.trim())try{o("loading"),l(S!=null&&S.createIfMissing?"Creating folder…":"Saving workspace…");const w=await e(x,"workspace_add",{path:C.trim(),createIfMissing:(S==null?void 0:S.createIfMissing)===!0});if(w!=null&&w.success){o("done"),l(S!=null&&S.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),l((w==null?void 0:w.error)||"Could not save workspace")}catch(w){o("error"),l(w instanceof Error?w.message:"Could not save workspace")}},[e]),v=i.useCallback(async x=>{var C,S,w,M,L,j;try{o("loading"),l("Starting daemon upgrade…");const k=await e(x,"daemon_upgrade",{});if((C=k==null?void 0:k.result)!=null&&C.alreadyLatest){o("done"),l(`Already on v${((S=k==null?void 0:k.result)==null?void 0:S.version)||"latest"}.`);return}if((w=k==null?void 0:k.result)!=null&&w.upgraded||(M=k==null?void 0:k.result)!=null&&M.success){o("done"),l(`Upgrade to v${((L=k==null?void 0:k.result)==null?void 0:L.version)||"latest"} started. Daemon is restarting…`);return}o("error"),l(((j=k==null?void 0:k.result)==null?void 0:j.error)||"Upgrade failed")}catch(k){o("error"),l(k instanceof Error?k.message:"Upgrade failed")}},[e]),h=i.useCallback(async(x,C,S,w)=>{var j,k,B;const M=Date.now(),L={machineId:x,kind:C,providerType:S,workspaceId:(w==null?void 0:w.workspaceId)||null,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:M};try{o("loading"),l(`Launching ${S}…`),m(L);const _={cliType:S};(j=w==null?void 0:w.workspacePath)!=null&&j.trim()?_.dir=w.workspacePath.trim():w!=null&&w.workspaceId&&(_.workspaceId=w.workspaceId),w!=null&&w.resumeSessionId&&(_.resumeSessionId=w.resumeSessionId),(k=w==null?void 0:w.args)!=null&&k.trim()&&(_.cliArgs=w.args.trim().split(/\s+/).filter(Boolean)),(B=w==null?void 0:w.model)!=null&&B.trim()&&(_.initialModel=w.model.trim());const T=await e(x,"launch_cli",_),F=(T==null?void 0:T.result)||T,H=(F==null?void 0:F.sessionId)||(F==null?void 0:F.id);if(T!=null&&T.success&&H){m(null),o("done"),l(`${S} launched`),t(Zt(H));return}if(T!=null&&T.success){o("loading"),l(`${S} launch requested — waiting for session…`);return}m(null),o("error"),l((T==null?void 0:T.error)||(F==null?void 0:F.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(_){if(yg(_)){o("loading"),l(`${S} launch requested — waiting for session…`);return}m(null),o("error"),l(_ instanceof Error?_.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),p=i.useCallback(async(x,C)=>{try{const S=await e(x,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),w=(S==null?void 0:S.result)??S;return Array.isArray(w==null?void 0:w.sessions)?w.sessions:[]}catch(S){return console.error("Failed to list saved sessions on mobile:",S),[]}},[e]),g=i.useCallback(async(x,C)=>En(e,x,C),[e]);i.useEffect(()=>{if(!d)return;const x=Qi(d.workspacePath),C=r.find(w=>{var _,T,F,H;if(!w||w.type==="adhdev-daemon"||gg(w.daemonId||w.id)!==d.machineId||(w.transport==="acp"?"acp":w.transport==="pty"?"cli":null)!==d.kind||String(w.agentType||w.type||"")!==d.providerType)return!1;const k=String(w.providerSessionId||"");if(d.resumeSessionId&&k)return k===d.resumeSessionId;if(x){const R=Qi(w.workspace||w.runtimeWorkspaceLabel);return R?R===x:!1}return Number(w.lastUpdated||w._lastUpdate||w.timestamp||((H=(F=(T=(_=w.activeChat)==null?void 0:_.messages)==null?void 0:T.at)==null?void 0:F.call(T,-1))==null?void 0:H.timestamp)||0)>=d.startedAt-5e3});if(!C)return;const S=fd({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:n});S&&(m(null),o("done"),l(`${d.providerType} launched`),t(Zt(S)))},[n,r,t,d]),i.useEffect(()=>{if(!d)return;const x=window.setTimeout(()=>{m(C=>!C||C.startedAt!==d.startedAt?C:(o("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(x)},[d]);const y=i.useCallback(async(x,C)=>{if(C.kind==="ide"&&C.providerType){await f(x,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await h(x,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[f,h]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:f,handleAddWorkspace:b,handleMachineUpgrade:v,handleLaunchWorkspaceProvider:h,handleListSavedSessions:p,handleBrowseDirectory:g,handleOpenRecent:y}}function wg({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:c,setSelectedMachineId:l,setSection:d,setMachineBackTarget:m}){const u=i.useCallback(y=>{o(y.tabKey),c("chat"),n(y)},[n,c,o]),f=i.useCallback(y=>{const x=e.find(C=>C.routeId===y.routeId&&C.streamSource==="native");x&&(o(x.tabKey),c("chat"),n(x))},[e,n,c,o]),b=i.useCallback(()=>{n(t),c("inbox")},[n,t,c]),v=i.useCallback((y,x="inbox")=>{l(y),a(),d("machines"),m(x),c("machine")},[a,m,c,d,l]),h=i.useCallback(y=>{const x=ws(y);x&&v(x,"chat")},[v]),p=i.useCallback(()=>{a(),c(r)},[r,a,c]),g=i.useCallback(y=>{d(y),c("inbox")},[c,d]);return{openConversation:u,openNativeConversation:f,backFromConversation:b,openMachine:v,openConversationMachine:h,backFromMachine:p,changeMachineSection:g}}function ys(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function jg(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function kg({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:b,onRequestedMobileSectionConsumed:v,onOpenHistory:h,onOpenRemote:p,onStopCli:g,wsStatus:y,isConnected:x,onShowAllHiddenConversations:C,onHideConversation:S,onOpenNewSession:w,liveSessionInboxState:M,setCliViewModeOverrides:L}){const[j,k]=i.useState(()=>{var G;return((G=e[0])==null?void 0:G.tabKey)||null}),[B,_]=i.useState(()=>e[0]?"chat":"inbox"),[T,F]=i.useState("chats"),[H,R]=i.useState(null),[I,N]=i.useState("inbox"),K=i.useRef([]),P=Ws(),E="0.9.81",U=i.useMemo(()=>e.find(G=>G.tabKey===j)||e[0]||null,[e,j]),ee=i.useMemo(()=>U?r.find(G=>G.id===U.routeId):void 0,[r,U]),ye=i.useMemo(()=>!U||Ze(U)||!st(U)?null:Us(U),[U]),le=i.useMemo(()=>r.filter(G=>G.type==="adhdev-daemon").sort(ho),[r]),Q=i.useMemo(()=>le.find(G=>G.id===H)||null,[le,H]),xe=Ln({sendDaemonCommand:a,activeConv:U||void 0,setActionLogs:o,isStandalone:c}),we=vg({sendDaemonCommand:a,navigate:P,ides:r,conversations:e}),be=i.useMemo(()=>e.map(G=>{const je=B==="chat"&&(U==null?void 0:U.tabKey)===G.tabKey,ge=Tn(G,M,{hideOpenTaskCompleteUnread:!0,isOpenConversation:je}),Ae=ps(G),Me=Il(G);return{conversation:G,timestamp:Ae,preview:Me,unread:ge.unread,requiresAction:ge.requiresAction,isWorking:ge.isWorking,inboxBucket:ge.inboxBucket}}),[e,M,B,U]),{markConversationRead:X}=bg({conversations:e,machineEntries:le,items:be,selectedConversation:U,selectedTabKey:j,screen:B,liveSessionInboxState:M,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:b,onRequestedMobileSectionConsumed:v,setSelectedTabKey:k,setScreen:_,setSelectedMachineId:R,setSection:F,setMachineBackTarget:N,resetMachineAction:we.resetMachineAction}),ue=wg({conversations:e,selectedConversation:U,machineBackTarget:I,markConversationRead:X,resetMachineAction:we.resetMachineAction,setSelectedTabKey:k,setScreen:_,setSelectedMachineId:R,setSection:F,setMachineBackTarget:N}),fe=i.useMemo(()=>sn(be.filter(G=>G.requiresAction)),[be]),ve=i.useMemo(()=>sn(be.filter(G=>G.unread&&!G.requiresAction)),[be]),pe=i.useMemo(()=>mg(be.filter(G=>!G.unread&&!G.requiresAction&&G.isWorking),K.current),[be]);i.useEffect(()=>{K.current=pe.map(G=>G.conversation.tabKey)},[pe]);const Se=i.useMemo(()=>sn(be.filter(G=>!G.unread&&!G.requiresAction&&!G.isWorking)),[be]),Z=i.useMemo(()=>Q?be.filter(G=>ws(G.conversation)===Q.id):[],[be,Q]),de=i.useMemo(()=>fg(Q,r),[r,Q]),oe=(Q==null?void 0:Q.version)||null,me=!!Q&&!!oe&&!0&&oe!==E,ie=i.useMemo(()=>(Q==null?void 0:Q.availableProviders)||[],[Q]),D=i.useMemo(()=>ie.filter(G=>ys(G,"cli")).map(G=>({type:G.type,displayName:G.displayName||G.type,icon:G.icon})),[ie]),z=i.useMemo(()=>ie.filter(G=>ys(G,"acp")).map(G=>({type:G.type,displayName:G.displayName||G.type,icon:G.icon})),[ie]),ce=i.useMemo(()=>hg(le,be),[be,le]),re=i.useCallback(async G=>{Q&&await we.handleOpenRecent(Q.id,G)},[we,Q]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:B==="chat"&&U?s.jsx(sg,{selectedConversation:U,isAcp:Ze(U),isStandalone:c,selectedIdeEntry:ee,actionLogs:n,userName:l,isSendingChat:xe.isSendingChat,sendFeedbackMessage:xe.sendFeedbackMessage,isFocusingAgent:xe.isFocusingAgent,handleModalButton:xe.handleModalButton,handleRelaunch:xe.handleRelaunch,onBack:ue.backFromConversation,onOpenNativeConversation:ue.openNativeConversation,onOpenMachine:ue.openConversationMachine,onOpenHistory:h,onOpenRemote:p,onStopCli:g,cliViewMode:ye,onSetCliViewMode:async G=>{await td({conversation:U,mode:G,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:L})},handleSendChat:xe.handleSendChat,handleFocusAgent:xe.handleFocusAgent}):B==="machine"&&Q?s.jsx(ug,{selectedMachineEntry:Q,selectedMachineConversations:Z,selectedMachineRecentLaunches:de,cliProviders:D,acpProviders:z,selectedMachineNeedsUpgrade:me,appVersion:E,machineAction:we.machineAction,isStandalone:c,section:T,showBottomNav:I==="inbox",onBack:ue.backFromMachine,onSectionChange:ue.changeMachineSection,onOpenConversation:ue.openConversation,onOpenRecent:re,onOpenMachineDetails:()=>P(`/machines/${Q.id}`),onMachineUpgrade:()=>we.handleMachineUpgrade(Q.id),onLaunchDetectedIde:(G,je)=>we.handleLaunchDetectedIde(Q.id,G,je),onAddWorkspace:(G,je)=>we.handleAddWorkspace(Q.id,G,je),onBrowseDirectory:G=>we.handleBrowseDirectory(Q.id,G),onLaunchWorkspaceProvider:(G,je,ge)=>we.handleLaunchWorkspaceProvider(Q.id,G,je,ge),onListSavedSessions:G=>we.handleListSavedSessions(Q.id,G)}):s.jsx(ag,{section:T,attentionItems:fe,unreadItems:ve,workingItems:pe,completedItems:Se,hiddenConversations:t,machineCards:ce,getAvatarText:jg,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ue.openConversation,onShowAllHidden:C,onHideConversation:S,onOpenNewSession:w,onOpenMachine:ue.openMachine,onOpenSettings:()=>P("/settings"),onSectionChange:F,wsStatus:y,isConnected:x,isStandalone:c})})}function ma(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Sg({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const c=i.useRef(0),[l,d]=i.useState(!1),[m,u]=i.useState(null),f=i.useCallback(()=>{c.current=0,d(!1),u(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const b=i.useCallback(g=>{g.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,d(!0))},[]),v=i.useCallback(g=>{if(!g.dataTransfer.types.includes("text/tab-key"))return;if(g.preventDefault(),!ma(t,r)){u("merge");return}const y=g.currentTarget.getBoundingClientRect(),x=g.clientX-y.left,C=y.width/3;x<C?u("split-left"):x>C*2?u("split-right"):u("merge")},[t,r]),h=i.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,d(!1),u(null))},[]),p=i.useCallback(g=>{c.current=0,d(!1);const y=g.dataTransfer.getData("text/tab-key"),x=y?e.some(S=>S.tabKey===y):!1,C=m;if(u(null),o(),!!y){if(g.preventDefault(),C==="split-left"&&ma(t,r)){r==null||r(y,"split-left");return}if(C==="split-right"&&ma(t,r)){r==null||r(y,"split-right");return}if(x){a(y);return}n==null||n(y)}},[e,m,t,r,n,a,o]);return{dragOver:l,dropAction:m,resetDragState:f,handleDragEnter:b,handleDragOver:v,handleDragLeave:h,handleDrop:p}}function Ng(e,t){const r=new Set(t.map(o=>o.tabKey)),n=e.filter(o=>r.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...n,...a]}function Cg({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,c]=i.useState(t??null),[l,d]=i.useState(r??[]),[m,u]=i.useState(null),f=i.useRef(null),b=i.useRef(null),v=i.useRef(n),h=i.useRef(a);i.useEffect(()=>{v.current=n},[n]),i.useEffect(()=>{h.current=a},[a]),i.useEffect(()=>{t&&t!==o&&c(t)},[t,o]),i.useEffect(()=>{d(L=>{const j=Ng(L,e);return j.length===L.length&&j.every((k,B)=>k===L[B])?L:j})},[e]);const p=i.useMemo(()=>{const L=m??l;if(L.length===0)return e;const j=new Map(L.map((k,B)=>[k,B]));return[...e].sort((k,B)=>{const _=j.get(k.tabKey)??999,T=j.get(B.tabKey)??999;return _-T})},[e,m,l]);i.useEffect(()=>{var j,k;if(p.length===0){o!==null&&(c(null),(j=v.current)==null||j.call(v,null));return}if(o&&p.some(B=>B.tabKey===o))return;const L=p[0].tabKey;L!==o&&(c(L),(k=v.current)==null||k.call(v,L))},[p,o]);const g=i.useMemo(()=>p.find(L=>L.tabKey===o),[p,o]),y=i.useCallback(L=>{var j;c(L),(j=v.current)==null||j.call(v,L)},[]),x=i.useCallback((L,j,k)=>{d(B=>{var H;const _=B.filter(R=>R!==L),T=_.indexOf(j);if(T<0)return B;const F=k==="left"?T:T+1;return _.splice(F,0,L),(H=h.current)==null||H.call(h,_),_}),u(null)},[]),C=i.useCallback((L,j,k)=>{const _=(l.length>0?l:e.map(H=>H.tabKey)).filter(H=>H!==L),T=_.indexOf(j);if(T<0)return;const F=k==="left"?T:T+1;_.splice(F,0,L),f.current=_,u(_)},[l,e]),S=i.useCallback(()=>{var j;const L=f.current;L&&(d(L),(j=h.current)==null||j.call(h,L))},[]),w=i.useCallback(()=>{f.current=null,u(null)},[]),M=i.useCallback(L=>{d(j=>{var B;const k=j.filter(_=>_!==L);return k.push(L),(B=h.current)==null||B.call(h,k),k})},[]);return{activeTabId:o,activeConv:g,sortedConversations:p,previewOrderRef:f,draggingTabRef:b,selectTab:y,handleTabReorder:x,updatePreviewOrder:C,commitPreviewOrder:S,clearPreviewOrder:w,moveTabToEnd:M,setDraggingTabKey:L=>{b.current=L}}}function Ig({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 Oo({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:o}){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&&!!o,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?Ll:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),l&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Bt,"aria-label":Bt,children:[s.jsx(Wc,{size:14}),s.jsx("span",{children:Bt})]})}),c&&s.jsx(bd,{}),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 wd="adhdev-tab-shortcuts";function jd(){try{return JSON.parse(localStorage.getItem(wd)||"{}")}catch{return{}}}function kd({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,c]=i.useState(()=>jd()),[l,d]=i.useState(null),m=i.useCallback(f=>{const b=[];return f.metaKey&&b.push(a?"⌘":"Meta"),f.ctrlKey&&b.push("Ctrl"),f.altKey&&b.push(a?"⌥":"Alt"),f.shiftKey&&b.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(b.push(f.key.length===1?f.key.toUpperCase():f.key),b.join("+"))},[a]),u=i.useCallback(f=>{c(f);try{localStorage.setItem(wd,JSON.stringify(f))}catch{}},[]);return i.useEffect(()=>{if(!e||!l)return;const f=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){d(null);return}const v=m(b);if(!v)return;const h={...o};for(const[p,g]of Object.entries(h))g===v&&delete h[p];h[l]=v,u(h),d(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,o,u,m]),i.useEffect(()=>{if(!e)return;const f=b=>{if(!(!b.ctrlKey&&!b.metaKey&&!b.altKey)){for(const[v,h]of Object.entries(o))if(t.includes(v)&&m(b)===h){b.preventDefault(),r(),n(v);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,o,t,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const pa=e=>{e.preventDefault()},Tg=i.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:c,draggingTabRef:l,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:f,onReorderTab:b,onCommitPreviewOrder:v,onClearPreviewOrder:h,onDragStateReset:p,onDragTabKeyChange:g,onReceiveTab:y,onOpenContextMenu:x,longPressTimer:C,isGroupActive:S}){const w=Hs(t),M=w.isGenerating?"agent-tab-generating":w.isWaiting?"agent-tab-waiting":"",L=w.isReconnecting,j=i.useCallback(N=>{l.current=t.tabKey,g(t.tabKey),N.dataTransfer.setData("text/tab-key",t.tabKey),N.dataTransfer.effectAllowed="move"},[t.tabKey,l,g]),k=i.useCallback(()=>{l.current=null,g(null),v(),h(),p()},[l,g,v,h,p]),B=i.useCallback(N=>{const K=l.current;if(!(!K||K===t.tabKey)&&N.dataTransfer.types.includes("text/tab-key")){N.preventDefault(),N.stopPropagation();const P=N.currentTarget.getBoundingClientRect(),E=N.clientX<P.left+P.width/2?"left":"right";f(K,t.tabKey,E)}},[t.tabKey,l,f]),_=i.useCallback(N=>{N.preventDefault(),N.stopPropagation();const K=N.dataTransfer.getData("text/tab-key");if(K&&K!==t.tabKey){const P=N.currentTarget.getBoundingClientRect(),E=N.clientX<P.left+P.width/2?"left":"right";c.includes(K)?b(K,t.tabKey,E):y&&y(K)}h()},[t.tabKey,c,b,y,h]),T=i.useCallback(N=>{N.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),F=i.useCallback(N=>{N.preventDefault(),x(N.clientX,N.clientY,t.tabKey)},[t.tabKey,x]),H=i.useCallback(N=>{const K=N.touches[0];C.current=setTimeout(()=>{x(K.clientX,K.clientY,t.tabKey)},600)},[t.tabKey,C,x]),R=i.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),I=["adhdev-dockview-tab",M,r&&"is-active",S&&"is-group-active",L&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:I,draggable:!0,onDragStart:j,onDragEnd:k,onDragOver:B,onDrop:_,onClick:T,onContextMenu:F,onTouchStart:H,onTouchEnd:R,onTouchMove:R,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:w.isGenerating?s.jsx("div",{className:"tab-spinner"}):w.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):L?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):w.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:ct(t),children:ct(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[L?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:cs(t)}):w.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[cs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:cs(t)}),s.jsx(Bs,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(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 Mg({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:b,onDragTabKeyChange:v,onReceiveTab:h,onHideTab:p,isGroupActive:g,allowTabShortcuts:y=!0}){const[x,C]=i.useState(null),S=i.useRef(null),w=i.useRef(null),M=i.useMemo(()=>e.map(F=>F.tabKey),[e]);jr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(x==null?void 0:x.tabKey)||null});const{isMac:L,tabShortcuts:j,shortcutListening:k,setShortcutListening:B,saveShortcuts:_}=kd({enabled:y,sortedTabKeys:e.map(F=>F.tabKey),onFocus:o,onSelectTab:c});i.useEffect(()=>{if(!x)return;const F=H=>{const R=document.querySelector("[data-pane-context-menu]");R&&R.contains(H.target)||C(null)};return window.addEventListener("mousedown",F,!0),()=>window.removeEventListener("mousedown",F,!0)},[x]),i.useEffect(()=>{const F=w.current;if(!F)return;const H=R=>{Math.abs(R.deltaY)<=Math.abs(R.deltaX)||(R.preventDefault(),F.scrollLeft+=R.deltaY)};return F.addEventListener("wheel",H,{passive:!1}),()=>F.removeEventListener("wheel",H)},[]);const T=i.useCallback((F,H,R)=>{C({x:F,y:H,tabKey:R})},[]);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:w,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(F=>s.jsx(Tg,{conv:F,isActive:t===F.tabKey,isDraggedTab:a.current===F.tabKey,isTaskCompleteUnread:n.has(F.tabKey),shortcut:y?j[F.tabKey]:void 0,conversationKeys:M,draggingTabRef:a,onFocus:o,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:b,onDragTabKeyChange:v,onReceiveTab:h,onOpenContextMenu:T,longPressTimer:S,isGroupActive:g},F.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),x&&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:x.x,top:x.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:pa,onClick:F=>{F.stopPropagation(),B(x.tabKey),C(null)},children:["⌨ ",j[x.tabKey]?`Change shortcut (${j[x.tabKey]})`:"Set shortcut"]}),j[x.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:pa,onClick:()=>{const F={...j};delete F[x.tabKey],_(F),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:pa,onClick:()=>{p(x.tabKey),C(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&k&&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:F=>F.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",L?"⌘+1":"Ctrl+1",", ",L?"⌥+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 Ag({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,userName:d,groupIndex:m,onFocus:u,isSplitMode:f,numGroups:b,onMoveTab:v,onReceiveTab:h,style:p,onActiveTabChange:g,initialActiveTabId:y,initialTabOrder:x,onTabOrderChange:C,onHideTab:S,isFocused:w,allowTabShortcuts:M=!0,onOpenNewSession:L,liveSessionInboxState:j}){const{sendCommand:k}=yt(),B=i.useRef(null),{activeTabId:_,activeConv:T,sortedConversations:F,draggingTabRef:H,selectTab:R,handleTabReorder:I,updatePreviewOrder:N,commitPreviewOrder:K,clearPreviewOrder:P,moveTabToEnd:E,setDraggingTabKey:U}=Cg({conversations:e,initialActiveTabId:y,initialTabOrder:x,onActiveTabChange:g,onTabOrderChange:C}),ee=Ln({sendDaemonCommand:a,activeConv:T,setActionLogs:o,isStandalone:c}),{dragOver:ye,dropAction:le,resetDragState:Q,handleDragEnter:xe,handleDragOver:we,handleDragLeave:be,handleDrop:X}=Sg({conversations:e,numGroups:b,onMoveTab:v,onReceiveTab:h,onOwnTabDrop:E,onClearPreviewOrder:P}),ue=T&&!Ze(T)&&Us(T)==="terminal",fe=i.useMemo(()=>T?t.find(Z=>Z.id===T.routeId):void 0,[t,T]),ve=i.useMemo(()=>T?n.filter(Z=>Z.routeId===T.tabKey):[],[n,T]),pe=i.useMemo(()=>new Set(F.filter(Z=>op(Z,j,{isOpenConversation:Z.tabKey===_})).map(Z=>Z.tabKey)),[_,j,F]);jr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:_,dragOver:ye});const Se=i.useCallback(Z=>{Z.streamSource==="agent-stream"&&Z.agentType&&k(Z.routeId,pl(),{agentType:Z.agentType,...Z.sessionId&&{targetSessionId:Z.sessionId}}).catch(()=>{})},[k]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...p,outline:ye?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(Mg,{conversations:F,activeTabId:_,groupIndex:m,numGroups:b,unreadTabKeys:pe,draggingTabRef:H,onFocus:u,onSelectTab:R,onConversationActivated:Se,onPreviewReorder:N,onReorderTab:I,onCommitPreviewOrder:K,onClearPreviewOrder:P,onDragStateReset:Q,onDragTabKeyChange:U,onMoveTab:v,onReceiveTab:h,onHideTab:S,isGroupActive:w??!1,allowTabShortcuts:M}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:xe,onDragOver:we,onDragLeave:be,onDrop:X,children:[ye&&s.jsx(Ig,{dropAction:le,canSplit:!!(b<4&&v)}),T?s.jsx($o,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!ue,ideEntry:fe,terminalRef:B,handleModalButton:ee.handleModalButton,handleRelaunch:ee.handleRelaunch,handleSendChat:ee.handleSendChat,isSendingChat:ee.isSendingChat,sendFeedbackMessage:ee.sendFeedbackMessage,handleFocusAgent:ee.handleFocusAgent,isFocusingAgent:ee.isFocusingAgent,actionLogs:ve,userName:d,isInputActive:!f||!!w}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Oo,{conversationsCount:e.length,isSplitMode:f,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:L})})]})]})}function Lg({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:f,userName:b,focusedGroup:v,focusGroup:h,moveTabToGroup:p,splitTabRelative:g,closeGroup:y,handleResizeStart:x,groupActiveTabIds:C,setGroupActiveTab:S,groupTabOrders:w,setGroupTabOrder:M,toggleHiddenTab:L,onOpenNewSession:j,allowTabShortcuts:k=!0,liveSessionInboxState:B}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((_,T)=>{const F=t&&n.length===r?`${n[T]}%`:void 0;return s.jsxs(wt.Fragment,{children:[t&&T>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:H=>x(T-1,H),onDoubleClick:()=>y(T),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(Ag,{style:t?{flexBasis:F??`${100/r}%`,flexGrow:F?0:1,flexShrink:F?0:1}:void 0,conversations:_,clearedTabs:o,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:f,userName:b,groupIndex:T,isFocused:t&&v===T,onFocus:()=>h(T),isSplitMode:t,numGroups:r,onMoveTab:(H,R)=>{R==="left"&&T>0?p(H,T-1):R==="right"&&T<r-1?p(H,T+1):R==="split-left"&&r<4?g(H,T,"left"):R==="split-right"&&r<4&&g(H,T,"right")},onReceiveTab:H=>p(H,T),onActiveTabChange:H=>S(T,H),initialActiveTabId:C[T],initialTabOrder:w[T],onTabOrderChange:H=>M(T,H),onHideTab:L,onOpenNewSession:j,allowTabShortcuts:k,liveSessionInboxState:B})]},T)})})}function Sd({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=i.useState(null),[c,l]=i.useState(null);i.useEffect(()=>e?lt.onScreenshot("ide-page",(u,f)=>{if(u!==e)return;const b=new FileReader;b.onload=()=>o(b.result),b.readAsDataURL(f)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var u;return e?((u=lt.onStatus)==null?void 0:u.call(lt,(f,b)=>{f===e&&b!=null&&b.screenshotUsage&&l(b.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,t]),i.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 d=i.useCallback(async(m,u)=>{const f=e?lt.get(e):null;return!f||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):f.sendInput(m,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:d}}const Nd="adhdev-dashboard-action-shortcuts",Rg=1200,_g=[["toggleHiddenTabs","G H"],["openNewSession","N"],["setActiveTabShortcut","G S"],["selectPreviousGroupTab","G K"],["selectPreviousGroupTab","T ←"],["selectPreviousGroupTab","⌥+["],["selectPreviousGroupTab","Ctrl+Alt+["],["selectNextGroupTab","G J"],["selectNextGroupTab","T →"],["selectNextGroupTab","⌥+]"],["selectNextGroupTab","Ctrl+Alt+]"],["splitActiveTabDown","S ↓"],["splitActiveTabDown","⌘+⌥+-"],["splitActiveTabDown","Ctrl+Alt+-"],["splitActiveTabRight","S →"],["splitActiveTabRight","⌘+⌥+\\"],["splitActiveTabRight","⌘+⌥+="],["splitActiveTabRight","Ctrl+Alt+\\"],["focusLeftPane","F ←"],["focusLeftPane","⌘+⌥+←"],["focusLeftPane","⌘+⌥+["],["focusLeftPane","Ctrl+Alt+←"],["focusRightPane","F →"],["focusRightPane","⌘+⌥+→"],["focusRightPane","⌘+⌥+]"],["focusRightPane","Ctrl+Alt+→"],["focusUpPane","F ↑"],["focusUpPane","⌘+⌥+U"],["focusUpPane","Ctrl+Alt+↑"],["focusDownPane","F ↓"],["focusDownPane","⌘+⌥+J"],["focusDownPane","Ctrl+Alt+↓"],["moveActiveTabToLeftPane","M ←"],["moveActiveTabToLeftPane","⌘+⌥+⇧+←"],["moveActiveTabToLeftPane","⌘+⌥+,"],["moveActiveTabToLeftPane","Ctrl+Alt+Shift+←"],["moveActiveTabToRightPane","M →"],["moveActiveTabToRightPane","⌘+⌥+⇧+→"],["moveActiveTabToRightPane","⌘+⌥+."],["moveActiveTabToRightPane","Ctrl+Alt+Shift+→"],["moveActiveTabToUpPane","M ↑"],["moveActiveTabToUpPane","⌘+⌥+I"],["moveActiveTabToUpPane","Ctrl+Alt+Shift+↑"],["moveActiveTabToDownPane","M ↓"],["moveActiveTabToDownPane","⌘+⌥+K"],["moveActiveTabToDownPane","Ctrl+Alt+Shift+↓"],["triggerPrimaryApprovalAction","⌥+A"],["triggerSecondaryApprovalAction","⌥+D"],["toggleCliView","T"]];function Pg(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function at(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function Cd(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:at("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:at("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:at("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:at("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:at("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:at("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:at("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:at("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:at("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:at("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:at("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:at("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:at("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:at("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:at("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:at("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:at("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:at("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:at("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:at("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:at("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:at("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:at("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:at("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:at("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:at("toggleCliView",e)}]}function Xa(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function kn(e){const t=Object.fromEntries(Cd(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Nd)||"{}"),n={...t,...r};for(const[a,o]of _g)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function Id(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Dg({enabled:e=!0,onTrigger:t}){const r=Pg(),[n,a]=i.useState(()=>kn(r)),[o,c]=i.useState(null),[l,d]=i.useState([]),m=i.useRef({parts:[],timer:null}),u=i.useCallback(p=>{const g=[];return p.metaKey&&g.push(r?"⌘":"Meta"),p.ctrlKey&&g.push("Ctrl"),p.altKey&&g.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&g.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(g.push(Id(p.key)),g.join("+"))},[r]),f=i.useCallback(p=>{a(p);try{localStorage.setItem(Nd,JSON.stringify(p))}catch{}},[]);i.useEffect(()=>{const p=kn(r),g=Object.entries(n),y=Object.entries(p);g.length===y.length&&g.every(([x,C])=>p[x]===C)||f(p)},[n,r,f]);const b=i.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),v=i.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},Rg))},[]);i.useEffect(()=>{if(!o)return;const p=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){c(null),d([]);return}const y=u(g);if(!y)return;const C=!(g.metaKey||g.ctrlKey||g.altKey)&&/^[A-Z0-9]$/.test(y);if(l.length===0&&C){d([y]);return}const w=[...l,y].slice(0,2).join(" "),M={...n};for(const[L,j]of Object.entries(M))j===w&&delete M[L];M[o]=w,f(M),c(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,u,f,o,l]),i.useEffect(()=>{if(!e||o)return;const p=g=>{if(g.defaultPrevented)return;const y=u(g);if(!y)return;const x=g.metaKey||g.ctrlKey||g.altKey;if(Xa(g.target))return;const C=m.current.parts,S=x?[y]:[...C.slice(-1),y].slice(-2),w=S.join(" "),M=S[S.length-1],L=Object.entries(n).filter(([,T])=>!!T),j=L.find(([,T])=>T===w);if(j){g.preventDefault(),b(),t(j[0]);return}if(L.some(([,T])=>T.startsWith(`${w} `))){g.preventDefault(),m.current.parts=S,v();return}const B=L.find(([,T])=>T===M);if(B){g.preventDefault(),b(),t(B[0]);return}if(L.some(([,T])=>T.startsWith(`${M} `))){g.preventDefault(),m.current.parts=[M],v();return}b()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,v,e,u,t,b,o]),i.useEffect(()=>()=>b(),[b]);const h=i.useMemo(()=>Cd(r),[r]);return{isMac:r,actionDefinitions:h,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:f}}function Eg({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 Td(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Zi({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!Td(n):!0}function $g({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:Td(r)}const Md=1e3,Bg=4;function ec(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function tc(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function Og({detachDelayMs:e=Md,stillnessThresholdPx:t=Bg,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,c=null,l=null,d=null,m=null,u=!1;const f=()=>{m!=null&&(a(m),m=null)},b=()=>{f(),l=null},v=()=>{f(),o=null,c=null,l=null,d=null,u=!1},h=()=>{!o||!l||!d||u||m!=null||(m=n(()=>{m=null,!(!o||!l||!d||u)&&ec(d,c)&&(tc(l,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},p=y=>{if(!(!o||u)){if(!ec(y,c)){d={clientX:y.clientX,clientY:y.clientY},b();return}(!l||tc(l,y,t))&&(f(),l={clientX:y.clientX,clientY:y.clientY}),d={clientX:y.clientX,clientY:y.clientY},h()}},g=y=>{!o||u||(y&&(d={clientX:y.clientX,clientY:y.clientY}),b())};return{startDrag:y=>{f(),o=y.panelId,c=y.selfPanelBounds??null,l=null,d={clientX:y.clientX,clientY:y.clientY},u=!1},markSelfPanel:p,markNonSelfPanel:g,markNoDropTarget:g,markDockTarget:g,endDrag:v,isDragging:()=>o!=null,hasDetached:()=>u,dispose:v}}function Kg(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Vr(e){return e.isActive}function sc(e){return e.isVisible}const Ad=i.createContext(null);function Bn(){const e=i.useContext(Ad);if(!e)throw new Error("DashboardDockviewContext missing");return e}function rn(e){return ct(e)||e.tabKey}function Fg(e){return`remote:${e}`}function Rt(e){return e.startsWith("remote:")}function rc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Wg(e){e.preventDefault()}function fa(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 ha(e,t){e.classList.remove(Aa.className,La.className),e.classList.add(t==="light"?Aa.className:La.className)}function nc(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 Hg(e){const[,t]=i.useState(0);i.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 Ug(e,t,r){var c;const n=[t];let a;for(const l of n){let d;for(const m of l){const u=e.addPanel({id:m.tabKey,component:"conversation",title:rn(m),params:{kind:"conversation",tabKey:m.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return r??((c=t[0])==null?void 0:c.tabKey)??null}function ac(e,t){const r=new Set(t.map(a=>a.tabKey)),n=new Map;for(const a of t)n.set(a.tabKey,(n.get(a.tabKey)||0)+1);for(const a of[...e.panels])Rt(a.id)||r.has(a.id)||e.removePanel(a);for(const a of t){const o=e.getPanel(a.tabKey);if(o){(n.get(a.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:a.tabKey,daemonId:a.daemonId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,panelId:o.id}),o.update({params:{tabKey:a.tabKey}}),o.title!==rn(a)&&o.api.setTitle(rn(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:rn(a),params:{kind:"conversation",tabKey:a.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 oc(e,t,r){var d,m;const n=r?Fg(r):null;for(const u of[...e.panels])Rt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Dt(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),c=Al(a);if(o){o.title!==c&&o.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((m=e.panels.find(u=>!Rt(u.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function zg({params:e,api:t}){var v;const r=Bn(),n=i.useRef(null),[a,o]=i.useState(()=>Vr(t)),[c,l]=i.useState(()=>sc(t)),d=r.conversationsByTabKey.get(e.tabKey),m=Ln({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o(Vr(t)),l(sc(t));const h=[t.onDidActiveChange(p=>o(p.isActive)),t.onDidActiveGroupChange(p=>{if(!Vr(t)&&!p.isActive){o(!1);return}o(Vr(t))}),t.onDidVisibilityChange(p=>l(p.isVisible))];return()=>{for(const p of h)p.dispose()}},[t]);const u=i.useMemo(()=>d?r.ides.find(h=>h.id===d.routeId):void 0,[r.ides,d]),f=i.useMemo(()=>d?r.actionLogs.filter(h=>h.routeId===d.tabKey):[],[r.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(Oo,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const b=!Ze(d)&&Us(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx($o,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:b,ideEntry:u,terminalRef:n,handleModalButton:m.handleModalButton,handleRelaunch:m.handleRelaunch,handleSendChat:m.handleSendChat,isSendingChat:m.isSendingChat,handleFocusAgent:m.handleFocusAgent,isFocusingAgent:m.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((v=r.scrollToBottomRequest)==null?void 0:v.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:c})})}function Vg({params:e}){var d;const t=Bn(),r=i.useMemo(()=>Dt([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=i.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:c,handleRemoteAction:l}=Sd({doId:a,targetSessionId:r?ml(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(Xc,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:o,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 Gg(){const e=Bn();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Oo,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function qg(e){var v,h;Hg(e);const t=Bn(),r=i.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=Dt([...t.conversationsByTabKey.values()],e.params.routeId),g=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,y=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${g?" 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=((h=e.api.group.activePanel)==null?void 0:h.id)===e.api.id,o=e.api.isGroupActive,c=Tn(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,d=c.isConnecting,m=c.isGenerating,u=c.isWaiting,f=c.unread,b=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${o?" is-group-active":""}${l?" is-reconnecting":""}`,title:ct(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var g;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((g=p.target)==null?void 0:g.ownerDocument)??document})},children:[f&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?s.jsx("div",{className:"tab-spinner"}):u?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):d?s.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:ct(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:cs(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:cs(n)}):s.jsx("span",{children:cs(n)})})]}),b&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:b,children:b})]})}function Yg({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:f,registerActionHandlers:b,onActiveTabChange:v,onOpenNewSession:h,onRequestScrollToBottom:p,requestedActiveTabKey:g,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:x,scrollToBottomRequest:C,liveSessionInboxState:S,layoutProfile:w}){var Qe,ze,rt;const{theme:M}=Lo(),{sendCommand:L}=yt(),j=i.useRef(null),k=i.useRef(null),B=i.useRef(null),_=i.useRef(!1),T=i.useRef(!1),F=i.useRef(!1),H=i.useRef(null),R=i.useRef([]),[I,N]=i.useState(null),[K,P]=i.useState(0),E=i.useRef(typeof window>"u"?{}:pb(w)),U=i.useMemo(()=>new Map(e.map(W=>[W.tabKey,W])),[e]),ee=i.useMemo(()=>{const W=j.current;return W?W.groups.some(V=>{try{const J=V.model.location.type;return J!=="floating"&&J!=="popout"?!1:V.panels.some(ne=>U.has(ne.id))}catch{return!1}}):!1},[U,K,e]),ye=i.useCallback(()=>{var W;(W=j.current)==null||W.focus()},[]),le=i.useCallback((W,V)=>{p==null||p(W,V)},[p]),Q=i.useCallback(W=>{const V=document,J=W.document;for(const ae of V.querySelectorAll('link[rel="stylesheet"]')){const ke=J.createElement("link");ke.rel="stylesheet",ke.href=ae.href,ae.crossOrigin&&(ke.crossOrigin=ae.crossOrigin),J.head.appendChild(ke)}for(const ae of V.querySelectorAll("style")){const ke=J.createElement("style");ke.textContent=ae.textContent,J.head.appendChild(ke)}const ne=[];for(const ae of V.styleSheets)try{for(const ke of ae.cssRules)ke instanceof CSSStyleRule&&(ke.selectorText===":root"||ke.selectorText==="html")&&ne.push(ke.cssText)}catch{}if(ne.length>0){const ae=J.createElement("style");ae.textContent=ne.join(`
54
- `),J.head.appendChild(ae)}const $=V.documentElement.getAttribute("data-theme");$&&J.documentElement.setAttribute("data-theme",$),J.documentElement.style.colorScheme=$==="light"?"light":"dark",J.body.className=V.body.className;const q=V.documentElement.getAttribute("style");q&&J.documentElement.setAttribute("style",q);const se=J.getElementById("dv-popout-window");se instanceof HTMLElement&&(se.classList.add("adhdev-dockview"),ha(se,M))},[M]),xe=i.useCallback(()=>{var V;const W=j.current;if(W)for(const J of W.groups)try{const ne=(V=J.element)==null?void 0:V.ownerDocument;if(!ne||ne===document)continue;const $=ne.getElementById("dv-popout-window");$ instanceof HTMLElement&&($.classList.add("adhdev-dockview"),ha($,M));const q=document.documentElement.getAttribute("data-theme");q&&ne.documentElement.setAttribute("data-theme",q),ne.documentElement.style.colorScheme=q==="light"?"light":"dark",ne.body.className=document.body.className;const se=document.documentElement.getAttribute("style");se?ne.documentElement.setAttribute("style",se):ne.documentElement.removeAttribute("style")}catch{}},[M]),we=i.useCallback(W=>{const V=j.current;if(!V)return;const J=V.getPanel(W);J&&V.addPopoutGroup(J,{popoutUrl:"/popout.html",onDidOpen:({window:ne})=>{Q(ne),de();const $=U.get(W);ne.document.title=$?`${ct($)} — ADHDev`:"ADHDev — Popout"}})},[U,Q]),be=i.useCallback(W=>{const V=j.current,J=V==null?void 0:V.getPanel(W);if(!V||!J)return;const ne=V.groups.filter($=>{var q;try{return((q=$.element)==null?void 0:q.ownerDocument)===document}catch{return!0}});ne.length>0?J.api.moveTo({group:ne[0],position:"center"}):J.api.moveTo({position:"center"}),J.api.setActive()},[]),X=i.useCallback(W=>{var ne;const V=j.current;if(!V)return!1;const J=V.getPanel(W);if(!J)return!1;try{return((ne=J.group.element)==null?void 0:ne.ownerDocument)!==document}catch{return!1}},[]),ue=i.useCallback(W=>{X(W)&&be(W),u(W)},[X,be,u]),fe=i.useCallback(W=>{const V=j.current,J=V==null?void 0:V.getPanel(W);!V||!J||V.addFloatingGroup(J,{width:600,height:500})},[]),ve=i.useCallback(W=>{var J;const V=(J=j.current)==null?void 0:J.getPanel(W);if(!V)return!1;try{return V.group.model.location.type==="floating"}catch{return!1}},[]),pe=i.useCallback(()=>{var V,J;const W=(J=(V=j.current)==null?void 0:V.activePanel)==null?void 0:J.id;return!W||Rt(W)?null:U.has(W)?W:null},[U]),Se=i.useCallback(W=>{const V=j.current,J=V==null?void 0:V.getPanel(W);if(!V||!J)return;const ne=V.groups.filter($=>{try{return $.model.location.type==="grid"}catch{return!0}});ne.length>0?J.api.moveTo({group:ne[0],position:"center"}):J.api.moveTo({position:"center"}),J.api.setActive()},[]),Z=i.useCallback(()=>{var q;const W=j.current;if(!W)return;const J=W.groups.filter(se=>{var ae;try{return((ae=se.element)==null?void 0:ae.ownerDocument)===document&&se.model.location.type==="grid"}catch{return!1}})[0]||null,ne=[...W.panels];for(const se of ne){const ae=(q=se.group.element)==null?void 0:q.ownerDocument,ke=se.group.model.location.type;ae===document&&ke==="grid"||(J&&J.id!==se.group.id?se.api.moveTo({group:J,position:"center"}):se.api.moveTo({position:"center"}))}const $=W.activePanel;$&&($.group.model.openPanel($),$.api.setActive()),fa(document)},[]),de=i.useCallback(()=>{var V,J;const W=j.current;if(W)for(const ne of W.groups){const $=(V=ne.element)==null?void 0:V.ownerDocument;if(!$||$===document)continue;const q=$.getElementById("dv-popout-window");if(!(q instanceof HTMLElement))continue;let se=null,ae=$.title||"ADHDev",ke="Popout workspace";const _e=ne.activePanel;if(_e)if(se=_e.id,Rt(_e.id)){const Ie=((J=_e.params)==null?void 0:J.routeId)||_e.id.slice(7),Ye=Dt([...U.values()],Ie);ae=Al(Ye),ke=Ye!=null&&Ye.machineName?`Remote view · ${Ye.machineName}`:"Remote view"}else{const Ie=U.get(_e.id);ae=Ie?ct(Ie):_e.title||_e.id,ke=Ie?cs(Ie):"Dockview panel"}$.title=`${ae} — ADHDev`;const De=Array.from($.querySelectorAll("#adhdev-popout-header"));for(const Ie of De)Ie.remove();const Te=$.createElement("div");Te.id="adhdev-popout-header",$.body.appendChild(Te),Te.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(";")),Te.innerHTML=`
55
- <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
56
- <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
57
- <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${rc(ae)}</div>
58
- <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${rc(ke)}</div>
59
- </div>
60
- <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
61
- <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>
62
- <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>
63
- </div>
64
- `,q.style.top="52px",q.style.height="calc(100% - 52px)";const Ee=Te.querySelector("[data-adhdev-popout-focus]");Ee&&(Ee.onclick=()=>{window.focus()});const Oe=Te.querySelector("[data-adhdev-popout-dock]");Oe&&(Oe.disabled=!se,Oe.style.opacity=se?"1":"0.5",Oe.style.cursor=se?"pointer":"default",Oe.onclick=()=>{var Ie;se&&be(se),(Ie=$.defaultView)==null||Ie.focus()})}},[U,be]),oe=i.useCallback(W=>{var ne;const V=j.current,J=V==null?void 0:V.getPanel(W);if(!(!V||!J)){J.group.model.openPanel(J),J.api.setActive(),le(W,"dockview-shortcut");try{const $=J.group.model.location;$.type==="popout"?$.getWindow().focus():fa((ne=J.group.element)==null?void 0:ne.ownerDocument)}catch{}}},[le]),me=i.useCallback(W=>{const V=j.current,J=V==null?void 0:V.activePanel,ne=(V==null?void 0:V.activeGroup)||(J==null?void 0:J.group);if(!V||!J||!ne)return;const $=ne.panels||[];if($.length<=1)return;const q=$.findIndex(ke=>ke.id===J.id);if(q<0)return;const se=(q+W+$.length)%$.length,ae=$[se];ae&&(ae.group.model.openPanel(ae),ae.api.setActive(),Rt(ae.id)||le(ae.id,"dockview-shortcut"))},[le]),ie=i.useCallback(W=>{var Ee;const V=j.current,J=(V==null?void 0:V.activeGroup)||((Ee=V==null?void 0:V.activePanel)==null?void 0:Ee.group);if(!V||!J)return;const ne=V.groups||[],$=ne.find(Oe=>Oe.id===J.id);if(!$)return;const q=$.element.getBoundingClientRect(),se=q.left+q.width/2,ae=q.top+q.height/2,ke=(Oe,Ie,Ye,Je)=>Math.max(0,Math.min(Ie,Je)-Math.max(Oe,Ye)),_e=Oe=>{const Ie=Oe.element.getBoundingClientRect(),Ye=Ie.left+Ie.width/2,Je=Ie.top+Ie.height/2;let ft=0,ht=0,it=0,ut=!1;if(W==="left"?(ut=Ye<se,ft=Math.max(0,q.left-Ie.right),ht=Math.abs(Je-ae),it=ke(q.top,q.bottom,Ie.top,Ie.bottom)):W==="right"?(ut=Ye>se,ft=Math.max(0,Ie.left-q.right),ht=Math.abs(Je-ae),it=ke(q.top,q.bottom,Ie.top,Ie.bottom)):W==="above"?(ut=Je<ae,ft=Math.max(0,q.top-Ie.bottom),ht=Math.abs(Ye-se),it=ke(q.left,q.right,Ie.left,Ie.right)):(ut=Je>ae,ft=Math.max(0,Ie.top-q.bottom),ht=Math.abs(Ye-se),it=ke(q.left,q.right,Ie.left,Ie.right)),!ut)return Number.POSITIVE_INFINITY;const We=it>0?0:120;return ft*3+ht+We};let De=null,Te=Number.POSITIVE_INFINITY;for(const Oe of ne){if(Oe.id===$.id)continue;const Ie=_e(Oe);Number.isFinite(Ie)&&(Ie>=Te||(Te=Ie,De=Oe))}return De||void 0},[]),D=i.useCallback(W=>{var ne;const V=ie(W);if(!V)return;const J=V.activePanel||V.panels[0];J&&(V.model.openPanel(J),J.api.setActive(),Rt(J.id)||le(J.id,"dockview-focus"),fa((ne=V.element)==null?void 0:ne.ownerDocument))},[ie,le]),z=i.useCallback((W,V)=>{const J=j.current,ne=J==null?void 0:J.activePanel,$=(J==null?void 0:J.activeGroup)||(ne==null?void 0:ne.group);if(!J||!ne||!$)return;let q=ie(W);!q&&(V!=null&&V.createGroupIfMissing)&&(q=J.addGroup({referenceGroup:$,direction:W})),q&&(ne.api.moveTo({group:q,position:"center"}),ne.group.model.openPanel(ne),ne.api.setActive(),Rt(ne.id)||le(ne.id,V!=null&&V.createGroupIfMissing?"dockview-split":"dockview-move"))},[ie,le]),{isMac:ce,tabShortcuts:re,shortcutListening:G,setShortcutListening:je,saveShortcuts:ge}=kd({sortedTabKeys:e.map(W=>W.tabKey),onFocus:ye,onSelectTab:oe}),Ae=i.useCallback(()=>{var J;const W=j.current;if(!W)return;const V=W.activePanel;if(V){if(Rt(V.id)){const ne=((J=V.params)==null?void 0:J.routeId)||V.id.slice(7),$=Dt(e,ne);$!=null&&$.tabKey&&je($.tabKey);return}U.has(V.id)&&je(V.id)}},[U,oe,je,e]),Me=i.useCallback(W=>{const V=[];return W.metaKey&&V.push(ce?"⌘":"Meta"),W.ctrlKey&&V.push("Ctrl"),W.altKey&&V.push(ce?"⌥":"Alt"),W.shiftKey&&W.key.length!==1&&V.push(ce?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(W.key)?null:(V.push(Id(W.key)),V.join("+"))},[ce]),O=i.useCallback(W=>{var V,J;switch(W){case"splitActiveTabRight":z("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":z("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const ne=pe();ne&&fe(ne);return}case"popoutActiveTab":{const ne=pe();ne&&we(ne);return}case"dockActiveTab":{const ne=pe();if(!ne)return;X(ne)?be(ne):ve(ne)&&Se(ne);return}case"focusLeftPane":D("left");return;case"focusRightPane":D("right");return;case"focusUpPane":D("above");return;case"focusDownPane":D("below");return;case"moveActiveTabToLeftPane":z("left");return;case"moveActiveTabToRightPane":z("right");return;case"moveActiveTabToUpPane":z("above");return;case"moveActiveTabToDownPane":z("below");return;case"selectPreviousGroupTab":me(-1);return;case"selectNextGroupTab":me(1);return;case"setActiveTabShortcut":Ae();return;case"hideCurrentTab":{const ne=(J=(V=j.current)==null?void 0:V.activePanel)==null?void 0:J.id;ne&&!Rt(ne)&&ue(ne);return}default:return}},[me,Se,D,fe,pe,ue,ve,X,be,z,we,Ae]);i.useEffect(()=>{if(!I)return;const W=I.sourceDocument,V=W.defaultView??window,J=ne=>{const $=W.querySelector("[data-dockview-tab-context-menu]");$&&$.contains(ne.target)||N(null)};return V.addEventListener("mousedown",J,!0),V!==window&&window.addEventListener("mousedown",()=>N(null),!0),()=>{V.removeEventListener("mousedown",J,!0),V!==window&&window.removeEventListener("mousedown",()=>N(null),!0)}},[I]);const Ne=i.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:U,hasDetachedConversationPanels:ee,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:h,liveSessionInboxState:S,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:ue,userName:m,scrollToBottomRequest:C,tabShortcuts:re,openTabContextMenu:({x:W,y:V,tabKey:J,sourceDocument:ne})=>N({x:W,y:V,tabKey:J,sourceDocument:ne??document}),popoutTab:we,moveTabBackToMain:be,isTabInPopout:X,floatTab:fe,isTabFloating:ve}),[n,t,U,ee,r,c,l,h,S,a,o,ue,m,C,re,we,be,X,fe,ve]),Re=I?Eg({isTabInPopout:X(I.tabKey),isTabFloating:ve(I.tabKey),tabShortcut:re[I.tabKey],actionShortcuts:f}):[],Fe=i.useCallback(W=>{var ne;const V=j.current;if((((ne=V==null?void 0:V.activePanel)==null?void 0:ne.id)??null)===W.id){W.group.model.openPanel(W);return}W.group.model.openPanel(W),W.api.setActive()},[]),He=i.useCallback((W,V="requested-tab")=>{if(!W)return!1;const J=j.current;if(!J)return!1;const ne=J.getPanel(W);return ne?(Fe(ne),le(W,V),x==null||x(),!0):!1},[Fe,x,le]),Ge=i.useCallback(()=>{if(F.current)return!1;const W=He(H.current,"stored-layout-restore");return W&&(F.current=!0),W},[He]),qe=i.useCallback(()=>{var V;const W=j.current;W&&mb(w,{activeTabId:((V=W.activePanel)==null?void 0:V.id)??null,layout:W.toJSON()})},[w]),et=i.useCallback(()=>{fb(w,E.current)},[w]),dt=i.useCallback(W=>{var ne,$,q,se;const V=j.current;if(!V)return{kind:"grid"};const J=V.toJSON();for(const ae of J.floatingGroups||[])if(($=(ne=ae.data)==null?void 0:ne.views)!=null&&$.includes(W)&&ae.position)return{kind:"floating",position:ae.position};for(const ae of J.popoutGroups||[])if((se=(q=ae.data)==null?void 0:q.views)!=null&&se.includes(W))return{kind:"popout",position:ae.position,popoutUrl:ae.url};return{kind:"grid"}},[]),pt=i.useCallback(W=>{const V=j.current;if(!V)return;const J=V.getPanel(W),ne=E.current[W];if(!J||!ne||ne.kind==="grid")return;if(J.group.model.location.type===ne.kind){delete E.current[W],et();return}if(ne.kind==="floating"){V.addFloatingGroup(J,{x:ne.position.left??24,y:ne.position.top??24,width:ne.position.width,height:ne.position.height}),delete E.current[W],et();return}delete E.current[W],et()},[et]);i.useEffect(()=>(b==null||b({setShortcutForActiveTab:Ae,restoreHiddenTabToSavedLocation:pt,activateConversationTab:oe,resetAllPanelsToMain:Z,activatePreviousTabInGroup:()=>me(-1),activateNextTabInGroup:()=>me(1),floatActiveTab:()=>{const W=pe();W&&fe(W)},popoutActiveTab:()=>{const W=pe();W&&we(W)},dockActiveTab:()=>{const W=pe();W&&(X(W)?be(W):ve(W)&&Se(W))},splitActiveTabRight:()=>z("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>z("below",{createGroupIfMissing:!0}),focusLeftPane:()=>D("left"),focusRightPane:()=>D("right"),focusUpPane:()=>D("above"),focusDownPane:()=>D("below"),moveActiveTabToLeftPane:()=>z("left"),moveActiveTabToRightPane:()=>z("right"),moveActiveTabToUpPane:()=>z("above"),moveActiveTabToDownPane:()=>z("below")}),()=>b==null?void 0:b(null)),[me,Se,fe,D,pe,ve,X,z,be,we,b,Z,pt,oe,Ae]),i.useEffect(()=>()=>{var W;(W=B.current)==null||W.call(B),B.current=null},[]);const bt=i.useCallback(W=>{var J,ne;j.current=W.api,(J=B.current)==null||J.call(B),B.current=null;const V=ub(w);if(H.current=(V==null?void 0:V.activeTabId)??null,V!=null&&V.layout&&W.api.fromJSON(V.layout,{reuseExistingPanels:!1}),T.current=Zi({hasStoredLayout:!!(V!=null&&V.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),T.current||(ac(W.api,e),oc(W.api,e,y)),W.api.totalPanels===0&&e.length>0){const $=Ug(W.api,e,g);if($){const q=W.api.getPanel($);q&&Fe(q)}}else!T.current&&!He(g)&&Ge();if(_.current=!0,W.api.onDidActivePanelChange($=>{var se;if(H.current=($==null?void 0:$.id)??null,F.current=!0,de(),$&&Rt($.id)){const ae=((se=$.params)==null?void 0:se.routeId)||$.id.slice(7),ke=Dt(e,ae);v((ke==null?void 0:ke.tabKey)??null),qe();return}if(v(($==null?void 0:$.id)??null),qe(),!$)return;const q=U.get($.id);(q==null?void 0:q.streamSource)==="agent-stream"&&q.agentType&&L(q.routeId,pl(),{agentType:q.agentType,...q.sessionId&&{targetSessionId:q.sessionId}}).catch(()=>{})}),W.api.onDidLayoutChange(()=>{qe(),de(),P($=>$+1)}),Kg()){const $=Te=>({clientX:Te.clientX,clientY:Te.clientY}),q=Te=>{const Ee=Te==null?void 0:Te.getBoundingClientRect();return Ee?{left:Ee.left,right:Ee.right,top:Ee.top,bottom:Ee.bottom}:null},se=Te=>{var Oe;const Ee=(Oe=k.current)==null?void 0:Oe.getBoundingClientRect();return Ee?Te.clientX<Ee.left||Te.clientX>Ee.right||Te.clientY<Ee.top||Te.clientY>Ee.bottom:!1},ae=Og({detachDelayMs:Md,onDetach:({panelId:Te,clientX:Ee,clientY:Oe})=>{var it,ut;const Ie=W.api.getPanel(Te);if(!Ie)return;try{if(Ie.group.model.location.type!=="grid")return}catch{return}const Ye=(it=k.current)==null?void 0:it.getBoundingClientRect(),Je=(ut=Ie.group.element)==null?void 0:ut.getBoundingClientRect(),ft=Math.round(Math.min(Math.max((Je==null?void 0:Je.width)??600,360),720)),ht=Math.round(Math.min(Math.max((Je==null?void 0:Je.height)??500,260),640));W.api.addFloatingGroup(Ie,{x:Ye?Math.max(0,Ee-Ye.left-32):void 0,y:Ye?Math.max(0,Oe-Ye.top-18):void 0,width:ft,height:ht}),Ie.api.setActive(),qe(),de(),P(We=>We+1)}}),ke=[W.api.onWillDragPanel(Te=>{if(!(Te.nativeEvent.defaultPrevented||Te.nativeEvent.shiftKey)){try{if(Te.panel.group.model.location.type!=="grid")return}catch{return}ae.startDrag({panelId:Te.panel.id,selfPanelBounds:q(Te.panel.group.element),...$(Te.nativeEvent)})}}),W.api.onWillShowOverlay(Te=>{if(ae.hasDetached()){Te.preventDefault();return}ae.markDockTarget($(Te.nativeEvent))}),W.api.onWillDrop(Te=>{if(ae.hasDetached()){Te.preventDefault(),ae.endDrag();return}ae.markDockTarget($(Te.nativeEvent))}),W.api.onDidDrop(()=>ae.endDrag()),W.api.onUnhandledDragOverEvent(Te=>{ae.isDragging()&&ae.markSelfPanel($(Te.nativeEvent))})],_e=Te=>{if(!ae.isDragging())return;const Ee=$(Te);se(Ee)&&ae.markNonSelfPanel(Ee)},De=()=>ae.endDrag();window.addEventListener("dragover",_e,!0),window.addEventListener("drop",De,!0),window.addEventListener("dragend",De,!0),B.current=()=>{ae.dispose();for(const Te of ke)Te.dispose();window.removeEventListener("dragover",_e,!0),window.removeEventListener("drop",De,!0),window.removeEventListener("dragend",De,!0)}}W.api.onDidAddGroup($=>{requestAnimationFrame(()=>{var q,se;try{const ae=(q=$.element)==null?void 0:q.ownerDocument;if(!ae||ae===document)return;(se=ae.getElementById("dv-popout-window"))==null||se.classList.add("adhdev-dockview");const ke=document.documentElement.getAttribute("data-theme");ke&&ae.documentElement.setAttribute("data-theme",ke),ae.body.className=document.body.className;const _e=document.documentElement.getAttribute("style");_e&&ae.documentElement.setAttribute("style",_e)}catch{}de(),P(ae=>ae+1)})}),v(((ne=W.api.activePanel)==null?void 0:ne.id)??null)},[Fe,He,U,r,d,w,v,qe,g,y,L,de,e]);i.useLayoutEffect(()=>{const W=j.current;if(!W||!_.current||T.current&&Zi({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const V=R.current,J=new Set(V),ne=e.map(De=>De.tabKey),$=new Set(ne),q=$g({previousVisibleConversationCount:V.length,visibleConversationCount:e.length,ides:r});let se=!1;for(const De of V)$.has(De)||q||(E.current[De]=dt(De),se=!0);se&&et(),q||(ac(W,e),oc(W,e,y));const ae=ne.filter(De=>!J.has(De));let ke=!1;for(const De of ae){const Te=W.getPanel(De),Ee=E.current[De];if(!Te||!Ee||Ee.kind==="grid")continue;if(Te.group.model.location.type===Ee.kind){delete E.current[De],ke=!0;continue}if(Ee.kind==="floating"){W.addFloatingGroup(Te,{x:Ee.position.left??24,y:Ee.position.top??24,width:Ee.position.width,height:Ee.position.height}),delete E.current[De],ke=!0;continue}}if(ke&&et(),R.current=ne,g&&He(g))return;!W.activePanel&&W.panels[0]&&Fe(W.panels[0]),!!(W.activePanel&&W.getPanel(W.activePanel.id))||Ge()},[Fe,He,Ge,r,d,et,dt,g,y,e]),i.useEffect(()=>{_.current&&He(g)},[He,g]),i.useEffect(()=>{const W=J=>{const ne=J.target;if(!ne)return;const $=ne.querySelector("[data-tab-key]")||ne.closest("[data-tab-key]");if($){const q=$.getAttribute("data-tab-key");if(q&&J.dataTransfer){const se=ne.closest(".dv-tab")||$.closest(".dv-tab")||$;J.dataTransfer.effectAllowed="move",J.dataTransfer.setData("text/tab-key",q),se instanceof HTMLElement&&J.dataTransfer.setDragImage(se,Math.max(12,Math.round(se.clientWidth/2)),Math.max(10,Math.round(se.clientHeight/2)))}}};window.addEventListener("dragstart",W);const V=nc(j.current);for(const J of V)J.addEventListener("dragstart",W);return()=>{window.removeEventListener("dragstart",W);for(const J of V)J.removeEventListener("dragstart",W)}},[K]),i.useEffect(()=>{var V;const W=(V=k.current)==null?void 0:V.querySelector(".adhdev-dockview");W instanceof HTMLElement&&ha(W,M),xe(),de()},[de,xe,M]),i.useEffect(()=>{de()},[de]),i.useEffect(()=>{const W=V=>{if(V.defaultPrevented||G)return;const J=Me(V);if(!J)return;const ne=V.metaKey||V.ctrlKey||V.altKey;Xa(V.target)&&!ne||kn(ce).setActiveTabShortcut!==J||(V.preventDefault(),V.stopPropagation(),Ae())};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[Me,ce,G,Ae]),i.useEffect(()=>{const W=k.current;if(!W)return;const V=J=>{var ae,ke;if(!J.isTrusted)return;const ne=(ke=(ae=J.target)==null?void 0:ae.closest)==null?void 0:ke.call(ae,".dv-scrollable");if(!ne)return;J.preventDefault(),J.stopPropagation();const $=Math.abs(J.deltaX),q=Math.abs(J.deltaY),se=$>q?J.deltaX:J.deltaY;ne.dispatchEvent(new WheelEvent("wheel",{deltaY:se,deltaMode:J.deltaMode,bubbles:!1,cancelable:!0}))};return W.addEventListener("wheel",V,{passive:!1,capture:!0}),()=>W.removeEventListener("wheel",V,{capture:!0})},[]),i.useEffect(()=>{const W=nc(j.current);if(W.length===0)return;const V=W.map(J=>{let ne=[],$=null;const q=()=>{$!=null&&J.clearTimeout($),$=null,ne=[]},se=()=>{$!=null&&J.clearTimeout($),$=J.setTimeout(()=>{$=null,ne=[]},1200)},ae=_e=>{if(!_e.ctrlKey&&!_e.metaKey&&!_e.altKey)return;const De=Me(_e);if(!De)return;const Te=jd();for(const[Ee,Oe]of Object.entries(Te))if(e.some(Ie=>Ie.tabKey===Ee)&&Oe===De){_e.preventDefault(),oe(Ee);return}},ke=_e=>{if(_e.defaultPrevented||G)return;const De=Me(_e);if(!De)return;const Te=_e.metaKey||_e.ctrlKey||_e.altKey;if(Xa(_e.target))return;const Ee=kn(ce),Oe=Object.entries(Ee).filter(([We,Et])=>!!Et&&(We==="splitActiveTabRight"||We==="splitActiveTabDown"||We==="floatActiveTab"||We==="popoutActiveTab"||We==="dockActiveTab"||We==="focusLeftPane"||We==="focusRightPane"||We==="focusUpPane"||We==="focusDownPane"||We==="moveActiveTabToLeftPane"||We==="moveActiveTabToRightPane"||We==="moveActiveTabToUpPane"||We==="moveActiveTabToDownPane"||We==="selectPreviousGroupTab"||We==="selectNextGroupTab"||We==="setActiveTabShortcut"||We==="hideCurrentTab")),Ie=Te?[De]:[...ne.slice(-1),De].slice(-2),Ye=Ie.join(" "),Je=Ie[Ie.length-1],ft=Oe.find(([,We])=>We===Ye);if(ft){_e.preventDefault(),q(),O(ft[0]);return}if(Oe.some(([,We])=>We.startsWith(`${Ye} `))){_e.preventDefault(),ne=Ie,se();return}const it=Oe.find(([,We])=>We===Je);if(it){_e.preventDefault(),q(),O(it[0]);return}if(Oe.some(([,We])=>We.startsWith(`${Je} `))){_e.preventDefault(),ne=[Je],se();return}q()};return J.addEventListener("keydown",ae),J.addEventListener("keydown",ke),()=>{q(),J.removeEventListener("keydown",ae),J.removeEventListener("keydown",ke)}});return()=>{for(const J of V)J()}},[Me,ce,K,oe,G,O,e]);const Ce=M==="light"?Aa:La,Ue=((rt=(ze=(Qe=j.current)==null?void 0:Qe.activePanel)==null?void 0:ze.group.element)==null?void 0:rt.ownerDocument)??document;return s.jsxs(Ad.Provider,{value:Ne,children:[s.jsx("div",{ref:k,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(ju,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:zg,remote:Vg},defaultTabComponent:qg,watermarkComponent:Gg,onReady:bt,singleTabMode:"default",tabAnimation:"smooth",theme:Ce,popoutUrl:"/popout.html"})}),I&&xr.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:I.x,top:I.y},children:Re.map(W=>{if(W.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},W.id);let V=s.jsx(km,{size:13,className:"shrink-0 opacity-70"}),J=()=>{};switch(W.id){case"dockInWindow":case"dockBackToGrid":V=s.jsx(Nm,{size:13,className:"shrink-0 opacity-70"}),J=()=>{Se(I.tabKey),N(null)};break;case"moveBackToMain":V=s.jsx(jm,{size:13,className:"shrink-0 opacity-70"}),J=()=>{be(I.tabKey),N(null)};break;case"floatAsPanel":V=s.jsx(Sm,{size:13,className:"shrink-0 opacity-70"}),J=()=>{fe(I.tabKey),N(null)};break;case"openInNewWindow":V=s.jsx(wm,{size:13,className:"shrink-0 opacity-70"}),J=()=>{we(I.tabKey),N(null)};break;case"setShortcut":J=ne=>{ne.stopPropagation(),je(I.tabKey),N(null)};break;case"removeShortcut":V=s.jsx(gt,{size:13,className:"shrink-0 opacity-70"}),J=()=>{const ne={...re};delete ne[I.tabKey],ge(ne),N(null)};break;case"hideTab":V=s.jsx(oo,{size:13,className:"shrink-0 opacity-70"}),J=()=>{ue(I.tabKey),N(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:Wg,onClick:J,children:[V,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)})}),I.sourceDocument.body),G&&xr.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:()=>je(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. ",ce?"⌘+1":"Ctrl+1",", ",ce?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),Ue.body)]})}const Ld="adhdev-recent-launch-args-v1",Xg=8;function Rd(e){return String(e||"").trim().replace(/\s+/g," ")}function Ko(e,t){return`${e.trim()}::${t.trim()}`}function Fo(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Ld)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function _d(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Ld,JSON.stringify(e))}catch{}}function Ja(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=Fo().byKey[Ko(r,n)])==null?void 0:o.items)||[]}function Pd(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=Rd(r);if(!n||!a||!o)return;const c=Fo(),l=Ko(n,a),d=((u=c.byKey[l])==null?void 0:u.items)||[],m=[o,...d.filter(f=>f!==o)].slice(0,Xg);c.byKey[l]={items:m},_d(c)}function Jg(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=Rd(r);if(!n||!a||!o)return;const c=Fo(),l=Ko(n,a),m=(((u=c.byKey[l])==null?void 0:u.items)||[]).filter(f=>f!==o);m.length>0?c.byKey[l]={items:m}:delete c.byKey[l],_d(c)}function Dd(e){return!e.hasLoadedInitialResults&&!e.isLoading}function nn({title:e,description:t,action:r,children:n,className:a="",contentClassName:o=""}){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 ${o}`.trim():o,children:n}):null]})}function Qg({savedSessionsLoading:e,savedSessionsLoaded:t,savedSessionsCount:r=0}){return e?"Refreshing saved history…":t?r>0?`${r} saved ${r===1?"history":"histories"} loaded. Open saved history to choose one.`:"No saved history found yet. New Hermes CLI conversations will appear here after ADHDev captures provider history.":"Start fresh, or open saved history when you want continuity."}function Ed({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:c,onOpenHistory:l,onClearSelection:d}){const m=o?yd(o):null,u=Qg({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(nn,{title:"Saved history",description:Co(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:c,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:l,children:Bh()})]}),children:[m?s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:m.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:m.providerSessionId}),s.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:d,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:u}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function $d({setup:e,providerName:t,className:r=""}){return e?s.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${r}`,children:[s.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",t?` for ${t}`:""]}),e.instructions&&s.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&s.jsxs("span",{children:["Server: ",s.jsx("code",{children:e.serverName})]}),e.configFormat&&s.jsxs("span",{children:["Format: ",s.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&s.jsxs("span",{children:["Config path: ",s.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&s.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&s.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}function Zg({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:c}){return e==="mesh"?null:s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:r},{id:"ide",label:"IDE",enabled:n},{id:"acp",label:"ACP",enabled:a}].map(l=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===l.id?"btn-primary":"btn-secondary"}`,onClick:()=>c(l.id),disabled:!l.enabled||o,children:l.label},l.id))})]})}function xa(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>ys(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>ys(a,"acp"))?"acp":null}function Gr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ey({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:c,onListMeshes:l,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var We,Et;const u=Sr(),f=i.useMemo(()=>[...e].sort(ho),[e]),[b,v]=i.useState(((We=f[0])==null?void 0:We.id)||""),h=i.useMemo(()=>f.find(te=>te.id===b)||f[0],[b,f]),p=i.useMemo(()=>((h==null?void 0:h.workspaces)||[]).map(te=>({id:te.id,path:te.path,label:te.label})),[h]),g=(h==null?void 0:h.defaultWorkspaceId)||null,[y,x]=i.useState("workspace"),[C,S]=i.useState(""),[w,M]=i.useState(""),[L,j]=i.useState([]),[k,B]=i.useState(""),[_,T]=i.useState(!1),[F,H]=i.useState(null),[R,I]=i.useState(""),[N,K]=i.useState(xa(f[0])),[P,E]=i.useState(""),[U,ee]=i.useState(""),[ye,le]=i.useState([]),[Q,xe]=i.useState(""),[we,be]=i.useState([]),[X,ue]=i.useState(!1),[fe,ve]=i.useState(!1),[pe,Se]=i.useState(""),[Z,de]=i.useState(!1),[oe,me]=i.useState(()=>jt()),[ie,D]=i.useState(null),[z,ce]=i.useState(!1),[re,G]=i.useState(""),[je,ge]=i.useState(null),[Ae,Me]=i.useState(!1),[O,Ne]=i.useState(""),[Re,Fe]=i.useState([]),[He,Ge]=i.useState(!1),[qe,et]=i.useState(""),[dt,pt]=i.useState(!1),bt=i.useRef(null),Ce=i.useRef(0);i.useEffect(()=>{var te;!b&&((te=f[0])!=null&&te.id)&&v(f[0].id)},[b,f]),i.useEffect(()=>{!h||!(!h.workspaces||!h.availableProviders||!h.detectedIdes||!h.recentLaunches)||u(h.id,{minFreshMs:3e4}).catch(()=>{})},[u,h]);const Ue=i.useMemo(()=>((h==null?void 0:h.availableProviders)||[]).filter(te=>ys(te,"cli")),[h]),Qe=i.useMemo(()=>((h==null?void 0:h.availableProviders)||[]).filter(te=>ys(te,"acp")),[h]),ze=i.useMemo(()=>((h==null?void 0:h.detectedIdes)||[]).map(te=>({id:te.type,label:te.name||te.type,meta:te.running?"Detected locally":"Available to open"})),[h]),rt=i.useMemo(()=>N==="cli"?Ue.map(te=>({id:te.type,label:te.displayName||te.type,meta:"CLI provider"})):N==="acp"?Qe.map(te=>({id:te.type,label:te.displayName||te.type,meta:"ACP provider"})):ze,[Qe,N,Ue,ze]),W=i.useMemo(()=>L.find(te=>te.id===k)||null,[L,k]),V=i.useMemo(()=>Ue.find(te=>te.type===P)||null,[Ue,P]),J=i.useMemo(()=>md(V==null?void 0:V.meshCoordinator,{meshId:(W==null?void 0:W.id)||"",workspace:(W==null?void 0:W.workspace)||""}),[V,W]),ne=je||J,$=i.useCallback(async te=>{T(!0),I("");try{const Pe=await l(te);j(Pe),B(A=>{var Y;return Pe.some(he=>he.id===A)?A:((Y=Pe[0])==null?void 0:Y.id)||""}),H(te)}catch(Pe){j([]),B(""),H(te),I(Pe instanceof Error?Pe.message:"Could not load meshes")}finally{T(!1)}},[l]);i.useEffect(()=>{var Pe;if(!h)return;if(bt.current!==h.id){bt.current=h.id,x("workspace"),S(g||((Pe=p[0])==null?void 0:Pe.id)||"__home__"),M(""),j([]),B(""),H(null),I(""),K(xa(h)),E(""),ee(""),xe(""),be([]),ve(!1),Se(""),me(jt()),G(""),ge(null);return}S(A=>{var Y;return A==="__custom__"||A==="__home__"||p.some(he=>he.id===A)?A:g||((Y=p[0])==null?void 0:Y.id)||"__home__"}),K(A=>A==="ide"&&ze.length>0||A==="cli"&&Ue.length>0||A==="acp"&&Qe.length>0?A:xa(h))},[Qe.length,Ue.length,g,ze.length,h,p]),i.useEffect(()=>{!h||y!=="mesh"||F===h.id||_||$(h.id)},[$,F,_,h,y]),i.useEffect(()=>{y==="mesh"&&N!=="cli"&&Ue.length>0&&K("cli")},[N,Ue.length,y]),i.useEffect(()=>{var te;N&&(rt.some(Pe=>Pe.id===P)||E(((te=rt[0])==null?void 0:te.id)||""))},[N,rt,P]),i.useEffect(()=>{ge(null)},[h==null?void 0:h.id,k,P,y]);const q=i.useCallback(async(te,Pe)=>{const A=Ce.current+1;return Ce.current=A,ue(!0),Se(""),m(te,Pe).then(Y=>{Ce.current===A&&be(Y)}).catch(Y=>{Ce.current===A&&(be([]),Se(Y instanceof Error?Y.message:"Could not load saved sessions"))}).finally(()=>{Ce.current===A&&(ue(!1),ve(!0))})},[m]),se=i.useCallback((te,Pe)=>{le(Ja(te,Pe))},[]);i.useEffect(()=>{Ce.current+=1,xe(""),me(jt()),!h||!P||N==="ide"?le([]):se(h.id,P),ve(!1),be([]),Se(""),ue(!1)},[N,se,q,h,P]),i.useEffect(()=>{if(!Q)return;const te=we.find(Pe=>Pe.providerSessionId===Q);te!=null&&te.canResume||xe("")},[we,Q]);const ae=C==="__custom__"?w.trim():C==="__home__"?"":((Et=p.find(te=>te.id===C))==null?void 0:Et.path)||"",ke=i.useMemo(()=>h?t.filter(te=>te.id!==h.id&&te.daemonId===h.id).map(te=>te.workspace):[],[t,h]),_e=i.useMemo(()=>((h==null?void 0:h.recentLaunches)||[]).map(te=>te.workspace),[h]),De=i.useCallback(te=>{const Pe=String(te.workspace||"").trim();if(!Pe)return;const A=p.find(Y=>Gr(Y.path)===Gr(Pe));if(A){S(A.id),M("");return}S("__custom__"),M(Pe)},[p]),Te=i.useCallback(te=>{const Pe=String(te.workspace||"").trim();if(!Pe)return{workspaceId:null,workspacePath:null};const A=p.find(Y=>Gr(Y.path)===Gr(Pe));return A?{workspaceId:A.id,workspacePath:null}:{workspaceId:null,workspacePath:Pe}},[p]),Ee=i.useMemo(()=>we.find(te=>te.providerSessionId===Q)||null,[we,Q]),Oe=i.useMemo(()=>{var Pe;if(N!=="cli"||!h||!P)return null;const te=((Pe=Ue.find(A=>A.type===P))==null?void 0:Pe.displayName)||P;return{routeId:h.id,daemonId:h.id,providerSessionId:Q||void 0,transport:"pty",mode:"chat",agentName:te,agentType:P,status:"idle",title:te,messages:[],ideType:P,workspaceName:ae,workspacePath:ae,displayPrimary:te,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${h.id}:${P}`,machineName:Ct(h,{fallbackId:h.id})}},[N,Ue,ae,h,Q,P]),Ie=i.useCallback(()=>{var Pe;if(!h)return;S("__custom__"),Me(!0),et("");const te=Dn(h.platform,Pn(w.trim(),ae,ke,_e,h.defaultWorkspacePath,(Pe=p.find(A=>A.id===g))==null?void 0:Pe.path,p.map(A=>A.path)));Ge(!0),n(h.id,te).then(A=>{Ne(A.path),M(A.path),Fe(A.directories)}).catch(A=>{et(A instanceof Error?A.message:"Could not load folder")}).finally(()=>Ge(!1))},[w,g,_e,ke,n,ae,h,p]),Ye=i.useCallback(te=>{h&&(Ge(!0),et(""),n(h.id,te).then(Pe=>{Ne(Pe.path),M(Pe.path),Fe(Pe.directories)}).catch(Pe=>{et(Pe instanceof Error?Pe.message:"Could not load folder")}).finally(()=>Ge(!1)))},[n,h]),Je=i.useCallback(async()=>{if(!h||!ae)return;pt(!0),G("");const te=await a(h.id,ae);if(pt(!1),!te.ok){G(te.error||"Could not save workspace");return}G("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,ae,h]),ft=i.useCallback(async()=>{if(!h)return;if(y==="mesh"){if(!k||!P)return;ce(!0),G(""),ge(null);const A=await d(h.id,k,P);if(ce(!1),!A.ok){if(A.code==="mesh_coordinator_manual_mcp_setup_required"&&A.manualSetup){ge(A.manualSetup),G("Manual MCP setup required before this provider can act as mesh coordinator.");return}G(A.error||"Could not start mesh coordinator");return}r();return}if(!N||!P)return;ce(!0),G("");const te=U.trim()?U.trim().split(/\s+/).filter(Boolean):[],Pe=N==="ide"?await o(h.id,P,{workspacePath:ae||null}):await c(h.id,N,P,{workspaceId:C!=="__home__"&&C!=="__custom__"?C:null,workspacePath:C==="__custom__"&&ae||null,resumeSessionId:N==="cli"&&Q?Q:null,cliArgs:te});if(ce(!1),!Pe.ok){G(Pe.error||"Could not start session");return}N!=="ide"&&U.trim()&&(Pd(h.id,P,U),se(h.id,P)),r()},[N,U,se,r,o,d,c,ae,h,k,Q,P,C,y]),ht=y==="mesh"?"Start mesh coordinator":N?_l(N,N==="cli"&&!!Q):"Start",it=y==="mesh"?"Starting coordinator…":N?Pl(N,N==="cli"&&!!Q):"Starting…",ut=f.length>5;return h?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(gt,{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(nn,{title:"Machine",children:ut?s.jsx("select",{"aria-label":"Machine",value:h.id,onChange:te=>v(te.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:z,children:f.map(te=>s.jsx("option",{value:te.id,children:Ct(te,{fallbackId:te.id})},te.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:f.map(te=>{const Pe=Ct(te,{fallbackId:te.id}),A=h.id===te.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${Pe}`,"aria-pressed":A,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${A?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>v(te.id),disabled:z,title:Pe,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${te.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Pe})]},te.id)})})}),s.jsxs(nn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:y==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ie,disabled:z,children:"Browse…"}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":"Launch target type",children:[{id:"workspace",label:"Workspace",desc:"Normal session"},{id:"mesh",label:"Mesh",desc:"Coordinator session"}].map(te=>s.jsxs("button",{type:"button",role:"radio","aria-checked":y===te.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${y===te.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{x(te.id),G(""),te.id==="mesh"&&h&&F!==h.id&&!_&&$(h.id)},disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold",children:te.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:te.desc})]},te.id))}),y==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:C,onChange:te=>{const Pe=te.target.value;S(Pe),Pe==="__custom__"?Ie():G("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:z,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),p.map(te=>s.jsxs("option",{value:te.id,children:[te.id===g?"⭐ ":"",Mn(te.path,te.label)||te.path]},te.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:C==="__home__"?"Launch without a workspace.":ae||"Select a workspace folder."}),C==="__custom__"&&ae&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ie,disabled:z,children:[s.jsx(xs,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Je,disabled:z||dt,children:dt?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[_&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!_&&R&&s.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:R}),!_&&!R&&L.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker."}),L.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:L.map(te=>s.jsxs("button",{type:"button",role:"radio","aria-checked":k===te.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${k===te.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>B(te.id),disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:te.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[te.repoIdentity||"Repo mesh",typeof te.nodesCount=="number"?` · ${te.nodesCount} node${te.nodesCount===1?"":"s"}`:""]}),te.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",te.workspace]})]},te.id))}),W&&s.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),s.jsx(Zg,{workspaceMode:y,activeKind:N,cliEnabled:Ue.length>0,ideEnabled:ze.length>0,acpEnabled:Qe.length>0,busy:z,onSelect:K}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:N==="ide"?"Choose IDE":N==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[rt.map(te=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${P===te.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>E(te.id),disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:te.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:te.meta})]},te.id)),rt.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."})]})]}),y==="mesh"&&ne&&s.jsx($d,{setup:ne,providerName:(V==null?void 0:V.displayName)||(V==null?void 0:V.name)||P}),y!=="mesh"&&N!=="ide"&&s.jsxs(nn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:U,onChange:te=>ee(te.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:z}),ye.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:ye.map(te=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>ee(te),disabled:z,title:te,children:te},te))})]}),y!=="mesh"&&N==="cli"&&s.jsx(Ed,{busy:z,savedSessionsLoading:X,savedSessionsError:pe,selectedSession:Ee,onRefresh:()=>{!h||!P||q(h.id,P)},onOpenHistory:()=>{!h||!P||(de(!0),Dd({hasLoadedInitialResults:fe,isLoading:X})&&q(h.id,P))},onClearSelection:()=>xe("")}),re&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${re.includes("saved")||re.includes("requested")||re.includes("Manual MCP setup")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:re})]}),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:z,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:ft,disabled:z||(y==="mesh"?!k||!P||N!=="cli"||_:!N||!P||C==="__custom__"&&!ae),children:[s.jsx(co,{size:14}),z?it:ht]})]})]})}),Ae&&s.jsx($n,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:O,directories:Re,busy:He,error:qe,onClose:()=>Me(!1),onNavigate:Ye,onConfirm:te=>{M(te),Ne(te),S("__custom__"),Me(!1)}}),Z&&Oe&&s.jsx(Mo,{activeConv:Oe,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:we,isSavedSessionsLoading:X,isResumingSavedSessionId:ie,savedHistoryFilters:oe,missingWorkspaceResumePath:ae||null,onSavedHistoryFiltersChange:me,onClose:()=>de(!1),onNewChat:()=>{xe(""),de(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!h||!P||q(h.id,P)},onResumeSavedSession:te=>{if(!h||!P||ie||!te.canResume)return;const Pe=Te(te);xe(te.providerSessionId),De(te),D(te.providerSessionId),de(!1),ce(!0),G(""),c(h.id,"cli",P,{workspaceId:Pe.workspaceId,workspacePath:Pe.workspacePath,resumeSessionId:te.providerSessionId}).then(A=>{if(!A.ok){G(A.error||"Could not resume session");return}r()}).finally(()=>{ce(!1),D(A=>A===te.providerSessionId?null:A)})}})]}):null}function ty(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function sy(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function ic(e){switch(e){case"online":return 0;case"dirty":return 1;case"degraded":return 2;case"wrong_branch":return 3;case"offline":return 4;case"unknown":default:return 5}}function cc(e){return e.length===0?"unknown":e.reduce((t,r)=>ic(r)>ic(t)?r:t)}function ry(e){var o,c,l,d,m;const t=new Map,r=new Map;for(const u of e){const f=(c=(o=u.git)==null?void 0:o.branch)==null?void 0:c.trim();f&&(r.set(f,(r.get(f)??0)+1),(l=u.git)!=null&&l.upstream&&t.set(f,(t.get(f)??0)+1))}const n=[...t.entries()].sort((u,f)=>{if(f[1]!==u[1])return f[1]-u[1];const b=["main","master","develop","dev"],v=b.indexOf(u[0]),h=b.indexOf(f[0]);return v!==-1||h!==-1?v===-1?1:h===-1?-1:v-h:u[0].localeCompare(f[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,f)=>f[1]-u[1])[0])==null?void 0:m[0])??null}function ny(e,t){const r=[],n=e.git;return n?n.isGitRepo?(!n.branch&&n.headCommit&&r.push("Detached HEAD"),n.hasConflicts&&r.push("Merge conflicts need resolution"),n.branch&&t&&n.branch!==t&&!n.upstream&&r.push(`No upstream tracking for ${n.branch}`),e.error&&r.push(e.error),r):(r.push("Not a git repository"),r):(r.push("No git status available"),r)}function Bd(e){var u;const t=ry(e.nodes),r=[],n=[],a=[],o=new Map;for(const f of e.nodes){const b=f.git,v=(b==null?void 0:b.branch)??null,h=ty(b),p=ny(f,t),g={id:f.nodeId,type:p.length>0?"orphanNode":"worktreeNode",label:f.machineLabel||f.nodeId.slice(0,8),workspace:f.workspace,branch:v,machineLabel:f.machineLabel||null,health:f.health,ahead:(b==null?void 0:b.ahead)??0,behind:(b==null?void 0:b.behind)??0,dirty:h,dirtyFiles:sy(b),hasConflicts:(b==null?void 0:b.hasConflicts)??!1,activeSessionCount:((u=f.activeSessions)==null?void 0:u.length)??0,activeSessions:f.activeSessions??[],providers:f.providers??[],isOrphan:p.length>0,orphanReasons:p,error:f.error,nextStepHint:p[0],source:f};if(r.push(g),v){const y=o.get(v)??[];y.push(g.id),o.set(v,y)}}const c=t?`__branch_${t}`:null;if(c&&t){const b=(o.get(t)??[]).map(h=>r.find(p=>p.id===h)).filter(Boolean),v={id:c,type:"defaultBranchNode",label:t,workspace:e.repoIdentity,branch:t,machineLabel:"default branch",health:cc(b.map(h=>h.health)),ahead:0,behind:0,dirty:b.some(h=>h.dirty),dirtyFiles:b.reduce((h,p)=>h+p.dirtyFiles,0),hasConflicts:b.some(h=>h.hasConflicts),activeSessionCount:b.reduce((h,p)=>h+p.activeSessionCount,0),activeSessions:b.flatMap(h=>h.activeSessions),providers:[...new Set(b.flatMap(h=>h.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:b.length>0?`${b.length} workspace(s) currently on ${t}`:"No workspaces currently checked out to the default branch",source:{nodeId:c,machineLabel:t,workspace:e.repoIdentity,health:cc(b.map(h=>h.health)),providers:[],activeSessions:[]}};r.push(v);for(const h of r)if(h.id!==c){if(h.branch===t){n.push({id:`${c}--${h.id}`,source:c,target:h.id,type:"parentBranch",label:"checked out"});continue}if(h.branch){n.push({id:`${c}--${h.id}`,source:c,target:h.id,type:h.isOrphan?"orphanLink":"parentBranch",label:h.branch});continue}h.isOrphan&&n.push({id:`${c}--${h.id}`,source:c,target:h.id,type:"orphanLink",label:"detached"})}}for(const[f,b]of o){if(b.length<2)continue;const v=b.map(h=>r.find(p=>p.id===h)).filter(Boolean);v.sort((h,p)=>h.label.localeCompare(p.label));for(let h=1;h<v.length;h+=1)n.push({id:`wt_${v[h-1].id}--${v[h].id}`,source:v[h-1].id,target:v[h].id,type:"worktreeLink",label:h===1?`${f} peers`:void 0})}const l=r.filter(f=>f.isOrphan).length,d=r.filter(f=>f.hasConflicts).length,m=r.filter(f=>f.health==="offline").length;return l>0&&a.push(`${l} workspace(s) need attention before safe coordination`),d>0&&a.push(`${d} workspace(s) report merge conflicts`),m>0&&a.push(`${m} node(s) are currently offline`),t||a.push("Could not infer a default branch from live mesh status"),{meshId:e.meshId,meshName:e.meshName,repoIdentity:e.repoIdentity,refreshedAt:e.refreshedAt,nodes:r,edges:n,stats:{totalNodes:e.nodes.length,onlineNodes:e.nodes.filter(f=>f.health==="online").length,dirtyNodes:r.filter(f=>f.dirty).length,orphanNodes:l,errorNodes:e.nodes.filter(f=>!!f.error).length,offlineNodes:m,totalActiveSessions:e.nodes.reduce((f,b)=>{var v;return f+(((v=b.activeSessions)==null?void 0:v.length)??0)},0)},warnings:a}}function rs({label:e,value:t}){return t==null||t===""?null:s.jsxs("div",{className:"flex justify-between text-[11px] py-0.5 border-b border-border-subtle/50",children:[s.jsx("span",{className:"text-text-muted",children:e}),s.jsx("span",{className:"text-text-secondary font-medium",children:String(t)})]})}function ay({health:e}){const t={online:"bg-green-500/10 text-green-400 border-green-500/20",dirty:"bg-yellow-500/10 text-yellow-400 border-yellow-500/20",degraded:"bg-red-500/10 text-red-400 border-red-500/20",wrong_branch:"bg-purple-500/10 text-purple-400 border-purple-500/20",offline:"bg-gray-500/10 text-gray-400 border-gray-500/20",unknown:"bg-gray-500/10 text-gray-400 border-gray-500/20"};return s.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] border ${t[e]||t.unknown}`,children:e})}function Od({node:e,onClose:t}){return e?s.jsxs("div",{className:"w-64 rounded-xl border border-border-subtle bg-bg-panel p-4 flex flex-col gap-2 shadow-lg",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary truncate",children:e.label}),t&&s.jsx("button",{onClick:t,className:"text-text-muted hover:text-text-primary text-xs",children:"✕"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ay,{health:e.health}),e.dirty&&s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-yellow-500/10 text-yellow-400 border border-yellow-500/20",children:"Dirty"}),e.hasConflicts&&s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-red-500/10 text-red-400 border border-red-500/20",children:"Conflict"}),e.isOrphan&&s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-red-500/10 text-red-400 border border-red-500/20",children:"Orphan"})]}),s.jsxs("div",{className:"flex flex-col gap-0.5 mt-1",children:[s.jsx(rs,{label:"Workspace",value:e.workspace}),s.jsx(rs,{label:"Branch",value:e.branch}),s.jsx(rs,{label:"Ahead",value:e.ahead>0?`+${e.ahead}`:null}),s.jsx(rs,{label:"Behind",value:e.behind>0?`-${e.behind}`:null}),s.jsx(rs,{label:"Dirty files",value:e.dirtyFiles>0?e.dirtyFiles:null}),s.jsx(rs,{label:"Active sessions",value:e.activeSessionCount>0?e.activeSessionCount:null}),s.jsx(rs,{label:"Providers",value:e.providers.join(", ")||null})]}),e.orphanReasons.length>0&&s.jsxs("div",{className:"mt-1",children:[s.jsx("div",{className:"text-[10px] font-semibold text-red-400 mb-1",children:"Orphan reasons"}),s.jsx("ul",{className:"list-disc list-inside text-[10px] text-red-300 space-y-0.5",children:e.orphanReasons.map((r,n)=>s.jsx("li",{children:r},n))})]}),e.nextStepHint&&s.jsxs("div",{className:"mt-1 px-2 py-1.5 rounded bg-blue-500/10 border border-blue-500/20 text-[10px] text-blue-300",children:["💡 ",e.nextStepHint]})]}):s.jsx("div",{className:"w-64 rounded-xl border border-border-subtle bg-bg-panel p-4 text-text-muted text-xs",children:"Select a node to view details."})}const lc=280,dc=170;function oy(e,t){const r=t?"border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":"border-border-subtle shadow-[0_18px_48px_rgba(3,7,18,0.22)]";switch(e){case"online":return`${r} bg-emerald-500/8`;case"dirty":return`${r} bg-amber-500/8`;case"degraded":return`${r} bg-rose-500/10`;case"wrong_branch":return`${r} bg-violet-500/10`;case"offline":return`${r} bg-slate-500/12`;default:return`${r} bg-bg-panel`}}function rr(e){switch(e){case"health":return"border-white/10 bg-white/6 text-text-secondary";case"dirty":return"border-amber-400/25 bg-amber-500/10 text-amber-200";case"conflict":return"border-rose-400/25 bg-rose-500/10 text-rose-200";case"orphan":return"border-fuchsia-400/25 bg-fuchsia-500/10 text-fuchsia-200";case"meta":default:return"border-cyan-400/20 bg-cyan-500/8 text-cyan-100"}}function Kd(e){switch(e){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":return"#fb7185";case"wrong_branch":return"#a78bfa";case"offline":return"#94a3b8";default:return"#64748b"}}function iy(e){return e.replace(/_/g," ")}function cy({data:e,selected:t}){const r=e.graphNode,n=r.type==="defaultBranchNode"?"default branch anchor":r.machineLabel||r.workspace;return s.jsxs("div",{className:`w-[240px] rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${oy(r.health,t)}`,children:[s.jsx(Zo,{type:"target",position:ei.Top,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),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:"truncate text-sm font-semibold text-text-primary",children:r.label}),s.jsx("div",{className:"truncate text-[11px] text-text-muted",children:n})]}),s.jsx("span",{className:"mt-0.5 h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:Kd(r.health)},"aria-hidden":!0})]}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-1.5 text-[10px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${rr("health")}`,children:iy(r.health)}),r.branch&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${rr("meta")}`,children:r.branch}),r.dirty&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 ${rr("dirty")}`,children:[r.dirtyFiles," dirty"]}),r.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${rr("conflict")}`,children:"conflicts"}),r.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${rr("orphan")}`,children:"needs attention"})]}),s.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-2 text-[11px] text-text-secondary",children:[s.jsxs("div",{className:"rounded-xl border border-white/6 bg-black/10 px-2.5 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.12em] text-text-muted",children:"Sessions"}),s.jsx("div",{className:"mt-1 font-medium text-text-primary",children:r.activeSessionCount})]}),s.jsxs("div",{className:"rounded-xl border border-white/6 bg-black/10 px-2.5 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.12em] text-text-muted",children:"Git drift"}),s.jsxs("div",{className:"mt-1 font-medium text-text-primary",children:["+",r.ahead," / -",r.behind]})]})]}),r.nextStepHint&&s.jsx("div",{className:"mt-3 rounded-xl border border-cyan-400/15 bg-cyan-500/8 px-3 py-2 text-[10px] leading-4 text-cyan-50/90",children:r.nextStepHint}),s.jsx(Zo,{type:"source",position:ei.Bottom,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const ly={meshNode:cy};function uc(e,t){return e.type==="defaultBranchNode"&&t.type!=="defaultBranchNode"?-1:t.type==="defaultBranchNode"&&e.type!=="defaultBranchNode"?1:e.branch&&t.branch&&e.branch!==t.branch?e.branch.localeCompare(t.branch):e.branch&&!t.branch?-1:!e.branch&&t.branch?1:e.label.localeCompare(t.label)}function dy(e){const t=[...e.nodes].sort(uc),r=t.find(v=>v.type==="defaultBranchNode")??null,n=t.filter(v=>v.id!==(r==null?void 0:r.id)),a=new Map,o=[];for(const v of n){if(v.isOrphan||!v.branch){o.push(v);continue}const h=v.branch,p=a.get(h)??[];p.push(v),a.set(h,p)}const c=[...a.entries()].sort(([v],[h])=>r!=null&&r.branch&&v===r.branch&&h!==r.branch?-1:r!=null&&r.branch&&h===r.branch&&v!==r.branch?1:v.localeCompare(h));o.length>0&&c.push(["__orphans__",[...o].sort(uc)]),c.length===0&&c.push(["__nodes__",[]]);const l=[],d=c.length,m=Math.max(1,d-1)*lc,u=r?0:80,f=r?dc:0;r&&l.push({id:r.id,type:"meshNode",position:{x:m/2,y:u},data:{graphNode:r},selected:!1,draggable:!1,selectable:!0}),c.forEach(([v,h],p)=>{const g=p*lc;(h.length>0?h:n.length>0?n:[]).forEach((x,C)=>{const S=f+C*dc;l.push({id:x.id,type:"meshNode",position:{x:g,y:S},data:{graphNode:x},selected:!1,draggable:!1,selectable:!0})}),v==="__nodes__"&&n.length===0&&r&&l.push({id:`${r.id}__placeholder`,type:"meshNode",position:{x:g,y:f},data:{graphNode:{id:`${r.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:e.repoIdentity,branch:r.branch,machineLabel:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:"Waiting for worktree nodes to report live mesh status.",source:{nodeId:`${r.id}__placeholder`,machineLabel:null,workspace:e.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}},selected:!1,draggable:!1,selectable:!1})});const b=e.edges.map(v=>({id:v.id,source:v.source,target:v.target,label:v.label,type:v.type==="worktreeLink"?"smoothstep":"bezier",animated:v.type==="orphanLink",markerEnd:{type:Tu.ArrowClosed,width:18,height:18,color:mc(v)},style:{stroke:mc(v),strokeWidth:v.type==="orphanLink"?2.25:v.type==="worktreeLink"?1.8:2,strokeDasharray:v.type==="orphanLink"?"5 4":void 0},labelStyle:{fill:"var(--text-secondary, #cbd5e1)",fontSize:10,fontWeight:600},labelBgStyle:{fill:"rgba(2, 6, 23, 0.86)",fillOpacity:1,stroke:"rgba(148, 163, 184, 0.2)"},labelBgPadding:[5,3],labelBgBorderRadius:6}));return{nodes:l,edges:b}}function mc(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";default:return"#64748b"}}function Fd({data:e,selectedNodeId:t=null,onNodeClick:r}){const n=i.useMemo(()=>dy(e),[e]),a=i.useMemo(()=>n.nodes.map(o=>({...o,selected:o.id===t})),[n.nodes,t]);return s.jsxs("div",{className:"relative h-full min-h-[480px] overflow-hidden rounded-2xl border border-border-subtle bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",children:[s.jsxs("div",{className:"absolute left-4 top-4 z-10 flex flex-wrap gap-2 text-[11px] text-text-secondary",children:[s.jsxs("span",{className:"rounded-full border border-white/10 bg-black/25 px-3 py-1",children:[e.stats.totalNodes," node",e.stats.totalNodes===1?"":"s"]}),s.jsxs("span",{className:"rounded-full border border-white/10 bg-black/25 px-3 py-1",children:[e.stats.totalActiveSessions," active session",e.stats.totalActiveSessions===1?"":"s"]}),e.stats.orphanNodes>0&&s.jsxs("span",{className:"rounded-full border border-orange-400/25 bg-orange-500/12 px-3 py-1 text-orange-100",children:[e.stats.orphanNodes," need attention"]})]}),s.jsxs(ku,{nodes:a,edges:n.edges,nodeTypes:ly,fitView:!0,fitViewOptions:{padding:.2,maxZoom:1.05},minZoom:.25,maxZoom:1.6,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,onNodeClick:(o,c)=>r==null?void 0:r(c.data.graphNode),className:"h-full w-full",colorMode:"dark",proOptions:{hideAttribution:!0},children:[s.jsx(Su,{pannable:!0,zoomable:!0,className:"!bottom-4 !right-4 !bg-slate-950/85 !border !border-white/10 !rounded-xl",nodeColor:o=>Kd(o.data.graphNode.health)}),s.jsx(Nu,{className:"!bottom-4 !left-4 !shadow-lg",showInteractive:!1}),s.jsx(Cu,{variant:Iu.Dots,gap:18,size:1.2,color:"rgba(148, 163, 184, 0.22)"})]})]})}function uy(e){const t=(e==null?void 0:e.result)??e,r=[e==null?void 0:e.status,t==null?void 0:t.status,t,e];for(const n of r)if(n&&Array.isArray(n.nodes)&&typeof n.meshId=="string")return n;return null}function my({activeConv:e,sendDaemonCommand:t,onClose:r}){var C;const n=typeof((C=e.settings)==null?void 0:C.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null,a=e.daemonId??null,[o,c]=i.useState(null),[l,d]=i.useState(null),[m,u]=i.useState(!1),[f,b]=i.useState(null),[v,h]=i.useState(null),p=i.useCallback(async()=>{if(!a||!n){b("This coordinator does not expose a live mesh id."),c(null);return}u(!0),b(null);try{const S=await t(a,"mesh_status",{meshId:n}),w=uy(S);if(!w){c(null),b("mesh_status returned an unexpected payload.");return}const M=Bd(w);c(M),d(L=>{var j,k;return L?M.nodes.some(B=>B.id===L)?L:((k=M.nodes[0])==null?void 0:k.id)??null:((j=M.nodes[0])==null?void 0:j.id)??null}),h(new Date().toISOString())}catch(S){c(null),b(S instanceof Error?S.message:"Failed to load live mesh status")}finally{u(!1)}},[a,n,t]);i.useEffect(()=>{p()},[p]),i.useEffect(()=>{const S=w=>{w.key==="Escape"&&r()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[r]);const g=i.useMemo(()=>!o||!l?null:o.nodes.find(S=>S.id===l)??null,[o,l]),y=(o==null?void 0:o.meshName)||n||"Repo Mesh",x=v?new Date(v).toLocaleTimeString():null;return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center bg-[#030617]/[0.58] p-0 md:p-4 backdrop-blur-md",onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:"flex h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-[min(88vh,920px)] md:max-w-[min(1280px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",onClick:S=>S.stopPropagation(),children:[s.jsxs("div",{className:"flex shrink-0 flex-col gap-3 border-b border-white/10 bg-slate-950/92 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:s.jsx(Is,{size:18})}),s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("h2",{className:"truncate text-lg font-semibold text-white md:text-xl",children:y}),s.jsx("span",{className:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",children:"Coordinator graph"})]}),s.jsxs("p",{className:"mt-1 truncate text-sm text-slate-400",children:[ct(e),e.workspaceName?` · ${e.workspaceName}`:"",o!=null&&o.repoIdentity?` · ${o.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[x&&s.jsxs("span",{className:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",children:["Refreshed ",x]}),s.jsx("button",{type:"button",onClick:p,disabled:m,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:m?"Refreshing…":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white","aria-label":"Close mesh graph",children:s.jsx(gt,{size:16})})]})]}),f&&s.jsx("div",{className:"shrink-0 border-b border-rose-400/20 bg-rose-500/12 px-4 py-2 text-sm text-rose-200 md:px-5",children:f}),s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] md:flex-row",children:[s.jsxs("div",{className:"flex min-h-[360px] min-w-0 flex-1 flex-col gap-3 overflow-hidden px-4 py-4 md:px-5 md:py-5",children:[(o==null?void 0:o.warnings)&&o.warnings.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:o.warnings.map(S=>s.jsx("span",{className:"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1.5 text-xs text-amber-100",children:S},S))}),s.jsx("div",{className:"min-h-0 flex-1",children:o?s.jsx(Fd,{data:o,selectedNodeId:l,onNodeClick:S=>d(S.id)}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",children:m?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet."})})]}),s.jsx("div",{className:"w-full shrink-0 border-t border-white/10 px-4 py-4 md:w-[320px] md:border-l md:border-t-0 md:px-5 md:py-5",children:s.jsx(Od,{node:g,onClose:g?()=>d(null):void 0})})]})]})})}function py(e,t){const{sendCommand:r}=yt(),[n,a]=i.useState(null),[o,c]=i.useState(!1);i.useEffect(()=>{if(!e||!t){a(null);return}c(!0),r(e,"git_remote_url",{workspace:t}).then(d=>{const m=(d==null?void 0:d.result)??d;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>c(!1))},[e,t,r]);const l=fy(n);return{remoteUrl:n,githubUrl:l,loading:o}}function fy(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const r=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return r?`https://github.com/${r[1]}`:null}const Wd=5e3;function hy(e){return`git:${e}`}function xy({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Wd}){return{type:"subscribe",topic:"workspace.git",key:hy(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function Wo(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function vs(e,t){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const r=e;if(typeof r.error=="string"&&r.error.trim())return r.error;if(typeof r.message=="string"&&r.message.trim())return r.message}return t}function by(e){const t=Wo(e);return(t==null?void 0:t.success)===!1?{status:null,error:vs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:vs(t,"Git status response did not include status")}}function gy(e){const t=Wo(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:vs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:vs(t,"Git diff summary response did not include diffSummary")}}function ba(e){return e===void 0||typeof e=="boolean"}function yy(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&ba(t.binary)&&ba(t.truncated)&&ba(t.staged)}function vy(e){const t=Wo(e);return(t==null?void 0:t.success)===!1?{diff:null,error:vs(t,"Git file diff request failed")}:yy(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:vs(t,"Git file diff response did not include a valid diff object")}}function wy({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Wd}){const{sendCommand:o,sendData:c}=yt(),l=typeof t=="string"?t.trim():"",d=!!(r&&e&&l),[m,u]=i.useState(null),[f,b]=i.useState(null),[v,h]=i.useState(!1),[p,g]=i.useState(null),y=i.useCallback(async()=>{if(!(!d||!e||!l)){h(!0),g(null);try{const C=by(await o(e,"git_status",{workspace:l}));if(C.error){u(null),b(null),g(C.error);return}if(u(C.status),!n){b(null);return}const S=gy(await o(e,"git_diff_summary",{workspace:l}));if(S.error){b(null),g(S.error);return}b(S.diffSummary)}catch(C){g(vs(C,"Git status request failed"))}finally{h(!1)}}},[d,e,n,o,l]),x=i.useMemo(()=>l?xy({workspace:l,includeDiffSummary:n,intervalMs:a}):null,[n,a,l]);return i.useEffect(()=>{if(!d||!e||!l||!x){u(null),b(null),h(!1),g(null);return}const C=c?Ut.subscribe({sendData:c},e,x,S=>{var w,M;S.workspace===l&&(u(S.status),b(S.diffSummary??null),g(((w=S.status)==null?void 0:w.error)||((M=S.diffSummary)==null?void 0:M.error)||null),h(!1))},{retryIntervalMs:1e3}):null;return y(),()=>{C==null||C()}},[d,e,y,x,c,l]),{status:m,diffSummary:f,loading:v,error:p,refresh:y}}const jy={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},ky={added:"text-emerald-400",modified:"text-orange-400",deleted:"text-red-400",renamed:"text-sky-400",copied:"text-sky-400",untracked:"text-zinc-400",conflict:"text-red-400 font-bold"};function pc(e){return e.split("/").pop()??e}function Sy(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Ny({files:e,truncated:t,onFileClick:r,selectedPath:n,className:a=""}){return e.length===0?s.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):s.jsxs("div",{className:`flex flex-col ${a}`,children:[s.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(o=>{const c=n===o.path,l=jy[o.status]??"?",d=ky[o.status]??"text-zinc-400",m=Sy(o.path),u=pc(o.path),f=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${c?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:o.status,children:l}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&s.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),s.jsx("span",{className:"text-text-primary",children:u}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",pc(o.oldPath)]}),f]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function Cy(e,t){let r="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?r="bg-emerald-500/10 text-emerald-300":e.startsWith("-")&&!e.startsWith("---")?r="bg-red-500/10 text-red-300":e.startsWith("@@")?r="text-sky-400":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(r="text-text-secondary"),s.jsx("div",{className:`px-3 ${r}`,children:s.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function Iy({diff:e,binary:t,truncated:r,loading:n,error:a,className:o=""}){const c=i.useRef(null);if(i.useEffect(()=>{c.current&&(c.current.scrollTop=0)},[e]),n)return s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${o}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${o}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"No diff available."});const l=e.split(`
65
- `);return s.jsxs("div",{ref:c,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:l.map((d,m)=>Cy(d,m))}),r&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",s.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function Ty(e,t){const r=[`Branch: ${e||"unknown"}`];r.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const n={};for(const a of t.files)n[a.status]||(n[a.status]=[]),n[a.status].push(a.path);for(const[a,o]of Object.entries(n))r.push(`${a}: ${o.slice(0,5).join(", ")}${o.length>5?` (+${o.length-5} more)`:""}`);return r.join(`
66
- `)}function Hd({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=yt(),{status:a,diffSummary:o,loading:c,error:l,refresh:d}=wy({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=i.useState(null),[f,b]=i.useState(null),[v,h]=i.useState(""),[p,g]=i.useState(!1),[y,x]=i.useState(!1),[C,S]=i.useState(null),[w,M]=i.useState(null),{githubUrl:L}=py(e,t),j=i.useCallback(async H=>{if(!((m==null?void 0:m.path)===H.path&&!m.loading)){u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const R=await n(e,"git_diff_file",{workspace:t,path:H.path,staged:H.staged}),I=vy(R);if(I.error||!I.diff){u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!1,error:I.error??"Failed to load diff"});return}u({path:H.path,diff:I.diff.diff,binary:I.diff.binary??!1,truncated:I.diff.truncated??!1,loading:!1,error:null})}catch(R){const I=R instanceof Error?R.message:"Failed to load diff";u({path:H.path,diff:"",binary:!1,truncated:!1,loading:!1,error:I})}}},[e,n,m,t]),k=i.useCallback(H=>{h(""),g(!1),S(null),M(null),b(H)},[]),B=i.useCallback(()=>{b(null),S(null),x(!1)},[]),_=i.useCallback(async()=>{var H,R,I;if(f){x(!0),S(null);try{let N;f==="checkpoint"?N=await n(e,"git_checkpoint",{workspace:t,message:v,includeUntracked:p}):f==="stash"?N=await n(e,"git_stash_push",{workspace:t,message:v,includeUntracked:p}):f==="stash_pop"?N=await n(e,"git_stash_pop",{workspace:t}):f==="checkout_files"&&m&&(N=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const K=(N==null?void 0:N.result)??N;if((K==null?void 0:K.success)===!1||K!=null&&K.error){S((K==null?void 0:K.error)??"Action failed"),x(!1);return}f==="checkpoint"?M(`Checkpoint created: ${((R=(H=K==null?void 0:K.checkpoint)==null?void 0:H.commit)==null?void 0:R.slice(0,7))??"done"}`):f==="stash"?M(`Stashed as ${((I=K==null?void 0:K.stash)==null?void 0:I.stashRef)??"stash@{0}"}`):f==="stash_pop"?M("Stash restored"):(M("File reverted"),u(null)),b(null),await d()}catch(N){S(N instanceof Error?N.message:"Action failed")}finally{x(!1)}}},[f,n,e,t,v,p,m,d]),T=!!(a!=null&&a.hasConflicts),F=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:H=>{H.target===H.currentTarget&&r()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),L&&s.jsx("a",{href:`${L}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:d,disabled:c,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(gt,{className:"h-4 w-4"})})]}),a&&s.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[a.headCommit&&s.jsxs("span",{title:a.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&s.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&s.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&s.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&s.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&s.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&s.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),F===0&&!a.error&&s.jsx("span",{className:"text-emerald-500",children:"clean"}),o&&o.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[o.files.length," file",o.files.length!==1?"s":"",o.totalInsertions>0&&s.jsxs("span",{className:"text-emerald-500",children:[" +",o.totalInsertions]}),o.totalDeletions>0&&s.jsxs("span",{className:"text-red-400",children:[" -",o.totalDeletions]})]})]}),l&&s.jsx("div",{className:"shrink-0 border-b border-border/50 bg-red-500/10 px-4 py-2 text-xs text-red-400",children:l}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[c&&!o&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&s.jsx(Ny,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:j}),!c&&!o&&!l&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?s.jsx(Iy,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),w&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-emerald-500/10 px-4 py-2 text-xs text-emerald-400 flex items-center justify-between",children:[s.jsx("span",{children:w}),s.jsx("button",{onClick:()=>M(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>k("checkpoint"),disabled:T,title:T?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>k("stash"),disabled:T,title:T?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>k("stash_pop"),disabled:T||!(a!=null&&a.stashCount),title:T?"Resolve conflicts before restoring a stash":a!=null&&a.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>k("checkout_files"),disabled:!m,title:m?`Revert changes to ${m.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),o&&o.files.length>0&&s.jsx("button",{onClick:()=>{const H=Ty((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(H),M("Copied to clipboard"),setTimeout(()=>M(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),f&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[f==="checkpoint"&&"Create checkpoint commit",f==="stash"&&"Stash changes",f==="stash_pop"&&"Restore latest stash?",f==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(f==="checkpoint"||f==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:v,onChange:H=>h(H.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-alt px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:p,onChange:H=>g(H.target.checked)}),"Include untracked files"]})]}),C&&s.jsx("p",{className:"text-xs text-red-400",children:C}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:B,disabled:y,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:_,disabled:y||(f==="checkpoint"||f==="stash")&&!v.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:y?"Working…":"Confirm"})]})]})})]})})}function My({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=i.useState(!1),[o,c]=i.useState(!1),[l,d]=i.useState(!1),[m,u]=i.useState(!1),[f,b]=i.useState(!1),[v,h]=i.useState("quickstart"),[p,g]=i.useState("workspace"),y=i.useMemo(()=>!t&&!e,[t,e]),x=i.useCallback(j=>{a(j),j&&c(!1)},[]),C=i.useCallback(j=>{c(j),j&&a(!1)},[]),S=i.useCallback(()=>{h(r===0?"quickstart":"shortcuts"),g("workspace"),d(!0),a(!1),c(!1)},[r]),w=i.useCallback(()=>{d(!1)},[]),M=i.useCallback(()=>{u(!0)},[]),L=i.useCallback(()=>{u(!1)},[]);return i.useEffect(()=>{if(!y){b(!1);return}b(!0);const j=window.setTimeout(()=>{b(!1)},1e4);return()=>window.clearTimeout(j)},[y]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:l,newSessionOpen:m,guideNudgeVisible:f,guideTab:v,shortcutSection:p,isDesktopDashboard:y,setGuideTab:h,setShortcutSection:g,handleInboxOpenChange:x,handleHiddenOpenChange:C,handleOpenShortcutHelp:S,closeShortcutHelp:w,openNewSession:M,closeNewSession:L}}function Ay(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 Ly(e){return e instanceof Error?e.message:String(e||"")}function Ry(e){const t=Ly(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function _y({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:c,onStopCli:l,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:f,ides:b,actionLogs:v,sendDaemonCommand:h,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:y,initialDataLoaded:x,userName:C,requestedMobileTabKey:S,onRequestedMobileTabConsumed:w,requestedMachineId:M,onRequestedMachineConsumed:L,requestedMobileSection:j,onRequestedMobileSectionConsumed:k,containerRef:B,isSplitMode:_,numGroups:T,groupSizes:F,groupedConvs:H,clearedTabs:R,focusedGroup:I,focusGroup:N,moveTabToGroup:K,splitTabRelative:P,closeGroup:E,handleResizeStart:U,groupActiveTabIds:ee,setGroupActiveTab:ye,groupTabOrders:le,setGroupTabOrder:Q,toggleHiddenTab:xe,visibleConversations:we,requestedDesktopTabKey:be,onRequestedDesktopTabConsumed:X,onDesktopActiveTabChange:ue,onRequestScrollToBottom:fe,onHideConversation:ve,onShowHiddenConversation:pe,onShowAllHiddenConversations:Se,scrollToBottomRequest:Z,machineEntries:de,layoutProfile:oe,onBrowseMachineDirectory:me,onSaveMachineWorkspace:ie,onLaunchMachineIde:D,onLaunchMachineProvider:z,onListMachineMeshes:ce,onLaunchMeshCoordinator:re,onListMachineSavedSessions:G,notifications:je,notificationUnreadCount:ge,liveSessionInboxState:Ae,onMarkNotificationRead:Me,onMarkNotificationUnread:O,onDeleteNotification:Ne}){const Re=wt.useRef(null),{inboxOpen:Fe,hiddenOpen:He,shortcutHelpOpen:Ge,newSessionOpen:qe,guideNudgeVisible:et,guideTab:dt,shortcutSection:pt,isDesktopDashboard:bt,setGuideTab:Ce,setShortcutSection:Ue,handleInboxOpenChange:Qe,handleHiddenOpenChange:ze,handleOpenShortcutHelp:rt,closeShortcutHelp:W,openNewSession:V,closeNewSession:J}=My({isMobile:t,showMobileChatMode:e,visibleConversationCount:we.length}),[ne,$]=wt.useState(null),[q,se]=wt.useState(null),ae=wt.useCallback((A,Y)=>{$({daemonId:A,workspace:Y})},[]),ke=wt.useCallback(A=>{se(A)},[]),_e=wt.useCallback(A=>{var Y;xr.flushSync(()=>{pe(A)}),(Y=Re.current)==null||Y.restoreHiddenTabToSavedLocation(A.tabKey)},[pe]),De=wt.useCallback(A=>{var he;const Y=u.find($e=>Ka($e,A))||f.find($e=>Ka($e,A));Y&&(f.some($e=>$e.tabKey===Y.tabKey)&&_e(Y),ue(Y.tabKey),(he=Re.current)==null||he.activateConversationTab(Y.tabKey),fe(Y.tabKey,"notification-open")),Me(A.id),Qe(!1)},[_e,f,u,ue,Me,fe]),Te=wt.useCallback(()=>{var Y;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Y=Re.current)==null||Y.resetAllPanelsToMain(),ze(!1))},[ze]),Ee=wt.useCallback(async A=>{var Be;if(!r)return;const Y=(Be=r.modalButtons)==null?void 0:Be[A];if(!Y)return;const he=$s(r);if(!he)return;const $e=Y.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Le=/^(run|approve|accept|yes|allow|always|proceed|save)/.test($e);try{await h(he,"resolve_action",{button:Y,action:Le?"approve":"reject",buttonIndex:A,...is(r)})}catch(tt){Ry(tt)||console.error("[Shortcut approval] Failed:",tt)}},[r,h]),{isMac:Oe,actionDefinitions:Ie,actionShortcuts:Ye,shortcutListening:Je,shortcutListeningDraft:ft,setShortcutListening:ht,setShortcutListeningDraft:it,saveShortcuts:ut}=Dg({enabled:bt&&!Ge,onTrigger:A=>{var Y,he,$e,Le,Be,tt,Nt,mt,Gt,Ir,Tr,Mr,Ar,Lr,Rr,_r;if(A==="openShortcutHelp"){rt();return}if(A==="openNewSession"){V();return}if(A==="hideCurrentTab"){r&&ve(r);return}if(A==="toggleHiddenTabs"){ze(!He);return}if(A==="openHistoryForActiveTab"){r&&!Ze(r)&&o(r);return}if(A==="openRemoteForActiveTab"){r&&!st(r)&&!Ze(r)&&c(r);return}if(A==="splitActiveTabRight"){(Y=Re.current)==null||Y.splitActiveTabRight();return}if(A==="splitActiveTabDown"){(he=Re.current)==null||he.splitActiveTabDown();return}if(A==="floatActiveTab"){($e=Re.current)==null||$e.floatActiveTab();return}if(A==="popoutActiveTab"){(Le=Re.current)==null||Le.popoutActiveTab();return}if(A==="dockActiveTab"){(Be=Re.current)==null||Be.dockActiveTab();return}if(A==="focusLeftPane"){(tt=Re.current)==null||tt.focusLeftPane();return}if(A==="focusRightPane"){(Nt=Re.current)==null||Nt.focusRightPane();return}if(A==="focusUpPane"){(mt=Re.current)==null||mt.focusUpPane();return}if(A==="focusDownPane"){(Gt=Re.current)==null||Gt.focusDownPane();return}if(A==="moveActiveTabToLeftPane"){(Ir=Re.current)==null||Ir.moveActiveTabToLeftPane();return}if(A==="moveActiveTabToRightPane"){(Tr=Re.current)==null||Tr.moveActiveTabToRightPane();return}if(A==="moveActiveTabToUpPane"){(Mr=Re.current)==null||Mr.moveActiveTabToUpPane();return}if(A==="moveActiveTabToDownPane"){(Ar=Re.current)==null||Ar.moveActiveTabToDownPane();return}if(A==="triggerPrimaryApprovalAction"){Ee(0);return}if(A==="triggerSecondaryApprovalAction"){Ee(1);return}if(A==="triggerTertiaryApprovalAction"){Ee(2);return}if(A==="setActiveTabShortcut"){(Lr=Re.current)==null||Lr.setShortcutForActiveTab();return}if(A==="selectPreviousGroupTab"){(Rr=Re.current)==null||Rr.activatePreviousTabInGroup();return}if(A==="selectNextGroupTab"){(_r=Re.current)==null||_r.activateNextTabInGroup();return}!r||!st(r)||Ze(r)||A==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),We=wt.useCallback(()=>{W(),ht(null),it([])},[W,ht,it]),Et=wt.useMemo(()=>pt==="all"?Ie:Ie.filter(A=>Ay(A)===pt),[Ie,pt]),te=wt.useCallback(()=>{const A=Object.fromEntries(Ie.map(Y=>[Y.id,""]));ut(A)},[Ie,ut]),Pe=wt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const A=Object.fromEntries(Ie.map(Y=>[Y.id,Y.defaultShortcut]));ut(A)},[Ie,ut]);return wt.useEffect(()=>{const A=Y=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Y.metaKey&&Y.key.toLowerCase()==="w":Y.ctrlKey&&Y.key.toLowerCase()==="w")&&(Y.preventDefault(),r&&ve&&ve(r))};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[r,ve]),wt.useEffect(()=>{if(!Ge||Je)return;const A=Y=>{Y.key==="Escape"&&(Y.preventDefault(),We())};return window.addEventListener("keydown",A,!0),()=>window.removeEventListener("keydown",A,!0)},[We,Ge,Je]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Rh,{activeConv:r,wsStatus:n,isConnected:a,conversations:we,hiddenConversations:f,onOpenHistory:o,onHideConversation:ve,onShowConversation:_e,onShowAllHidden:Se,onResetPanelsToMain:Te,notifications:je,notificationUnreadCount:ge,onOpenNotification:De,onMarkNotificationRead:Me,onMarkNotificationUnread:O,onDeleteNotification:Ne,inboxOpen:Fe,onInboxOpenChange:Qe,hiddenOpen:He,onHiddenOpenChange:ze,onOpenNewSession:t?void 0:V,onOpenDashboardGuide:rt,guideNudgeVisible:et,actionShortcuts:Ye,onOpenRemote:()=>{!r||st(r)||Ze(r)||c(r)},onStopCli:l,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:ae,onOpenMeshGraph:ke}),e?s.jsx(kg,{conversations:u,hiddenConversations:f,ides:b,actionLogs:v,sendDaemonCommand:h,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:y,userName:C,requestedActiveTabKey:S,onRequestedActiveTabConsumed:w,requestedMachineId:M,onRequestedMachineConsumed:L,requestedMobileSection:j,onRequestedMobileSectionConsumed:k,onOpenHistory:o,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Se,onHideConversation:ve,onOpenNewSession:V,liveSessionInboxState:Ae}):t?s.jsx(Lg,{containerRef:B,isSplitMode:_,numGroups:T,groupSizes:F,groupedConvs:H,clearedTabs:R,ides:b,actionLogs:v,sendDaemonCommand:h,setActionLogs:p,isStandalone:y,hasRegisteredMachines:de.length>0,userName:C,focusedGroup:I,focusGroup:N,moveTabToGroup:K,splitTabRelative:P,closeGroup:E,handleResizeStart:U,groupActiveTabIds:ee,setGroupActiveTab:ye,groupTabOrders:le,setGroupTabOrder:Q,toggleHiddenTab:xe,onOpenNewSession:V,allowTabShortcuts:!1,liveSessionInboxState:Ae}):s.jsx(Yg,{visibleConversations:we,clearedTabs:R,ides:b,actionLogs:v,sendDaemonCommand:h,setActionLogs:p,isStandalone:y,hasRegisteredMachines:de.length>0,initialDataLoaded:x,userName:C,toggleHiddenTab:xe,actionShortcuts:Ye,registerActionHandlers:A=>{Re.current=A},onActiveTabChange:ue,requestedActiveTabKey:be,onRequestedActiveTabConsumed:X,onRequestScrollToBottom:fe,scrollToBottomRequest:Z,onOpenNewSession:V,liveSessionInboxState:Ae,layoutProfile:oe}),qe&&s.jsx(ey,{machines:de,ides:b,onClose:J,onBrowseDirectory:me,onSaveWorkspace:ie,onLaunchIde:D,onLaunchProvider:z,onListMeshes:ce,onLaunchMeshCoordinator:re,onListSavedSessions:G}),q&&s.jsx(my,{activeConv:q,sendDaemonCommand:h,onClose:()=>se(null)}),ne&&s.jsx(Hd,{daemonId:ne.daemonId,workspace:ne.workspace,onClose:()=>$(null)}),Ge&&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:We,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:A=>A.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:We,"aria-label":"Close dashboard guide",children:s.jsx(gt,{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(A=>s.jsx("button",{type:"button",className:`btn btn-sm ${dt===A.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ce(A.id),children:A.label},A.id))}),dt==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Oe?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),dt==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),dt==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(A=>s.jsx("button",{type:"button",className:`btn btn-sm ${pt===A.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ue(A.id),children:A.label},A.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:te,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:Pe,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Et.map(A=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Je===A.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:A.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:A.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:A.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:Je===A.id?ft.length>0?`${ft.join(" ")} ...`:"Listening...":Ye[A.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{ht(A.id),it([])},children:Je===A.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Y={...Ye};Y[A.id]="",ut(Y)},children:"Disable"})]})]})},A.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Oe?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const ga=[{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 Py({onClose:e}){const[t,r]=i.useState(0),n=ga[t],a=t===ga.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:o=>{o.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(gt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:ga.map((o,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(o=>o+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
67
- @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
68
- @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
69
- `})]})}function Dy({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(o=>{const c=r===o.tabKey,l=o.status==="waiting_approval",d=o.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(o.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),o.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:"!"})]},o.tabKey)})]}):null}function Ey({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,c]=i.useState(()=>a||"native"),l=i.useMemo(()=>El(t),[t]),d=i.useMemo(()=>e?Ao(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),m=i.useMemo(()=>d.find(p=>p.streamSource==="native"),[d]),u=i.useMemo(()=>d.filter(p=>p.streamSource==="agent-stream"),[d]),f=i.useMemo(()=>e?Dt(d,e.id):null,[d,e]);i.useEffect(()=>{a&&c(a)},[a]),i.useEffect(()=>{if(a||!f)return;const p=f.streamSource==="native"?"native":f.tabKey;!p||o===p||o==="native"&&c(p)},[o,f,a]),i.useEffect(()=>{var p;o!=="native"&&(u.some(g=>g.tabKey===o)||c(((p=u[0])==null?void 0:p.tabKey)||"native"))},[o,u]),i.useEffect(()=>{o==="native"&&(m||u[0]&&c(u[0].tabKey))},[o,m,u]);const b=i.useMemo(()=>o==="native"&&m?m:u.find(p=>p.tabKey===o)||f||m||u[0],[o,m,f,u]),v=i.useMemo(()=>u.map(p=>({tabKey:p.tabKey,title:Ml(p)||n,status:p.status})),[u,n]),h=i.useCallback(p=>{if(p)return d.find(g=>Ka(g,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[d]);return{activeChatTab:o,setActiveChatTab:c,activeConv:b,conversations:d,extensionTabs:v,hasExtensions:v.length>0,resolveConversationByTarget:h}}function $y({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:c,isStandalone:l,userName:d,onOpenHistory:m,onConversationChange:u,onClose:f}){const[b,v]=i.useState("split"),[h,p]=i.useState(()=>Qt(e)?"native":e.tabKey),g=i.useRef(null),y=i.useMemo(()=>t||r.find(N=>N.id===e.routeId),[e.routeId,t,r]),x=i.useMemo(()=>ot((y==null?void 0:y.type)||""),[y==null?void 0:y.type]),{conversations:C,extensionTabs:S,hasExtensions:w}=Ey({ideData:y,allIdes:r,connectionStates:n,ideName:x||"IDE",preferredTabKey:Qt(e)?void 0:e.tabKey}),M=i.useMemo(()=>y?Dt(C,y.id):null,[y,C]);i.useEffect(()=>{const N=g.current,K={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(g.current=K,!(N&&N.routeId===K.routeId&&N.tabKey===K.tabKey&&N.streamSource===K.streamSource)){if(Qt(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(h==="native"){if(C.some(N=>N.streamSource==="native"))return;(M==null?void 0:M.streamSource)==="agent-stream"&&p(M.tabKey);return}if(!C.some(N=>N.tabKey===h)){if((M==null?void 0:M.streamSource)==="agent-stream"){p(M.tabKey);return}p("native")}},[C,h,M]);const L=i.useMemo(()=>h==="native"?C.find(N=>N.streamSource==="native")||e:C.find(N=>N.tabKey===h)||e,[e,C,h]),j=Yl(L),k=i.useMemo(()=>j.status||j.modalMessage||j.modalButtons?{...L,...j.status?{status:j.status}:{},...j.modalMessage!==void 0?{modalMessage:j.modalMessage}:{},...j.modalButtons!==void 0?{modalButtons:j.modalButtons}:{}}:L,[L,j]),B=kr(k),_=Ln({sendDaemonCommand:o,activeConv:k,setActionLogs:c,isStandalone:l}),{connScreenshot:T,screenshotUsage:F,handleRemoteAction:H}=Sd({doId:B,targetSessionId:ml(k),connState:k.connectionState||"new",viewMode:b}),R=i.useMemo(()=>a.filter(N=>N.routeId===k.tabKey),[a,k.tabKey]);i.useEffect(()=>{u==null||u(k)},[k,u]),i.useEffect(()=>{const N=K=>{K.key==="Escape"&&f()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[f]);const I=i.useCallback(N=>{N.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:f,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:I,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(It,{size:16})}),s.jsx("span",{className:"truncate",children:go(L)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:f,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(N=>{const K=b===N;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${K?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>v(N),title:N==="split"?"Split view":"Remote only",children:N==="split"?s.jsx(lm,{size:15}):s.jsx(It,{size:15})},N)})}),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(L),title:"Chat History",children:[s.jsx(ao,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:f,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${b==="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:[b!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${b==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(Dy,{hasExtensions:w,ideName:x||"IDE",activeChatTab:h,extensionTabs:S,onSelectTab:p}),s.jsx(Qc,{activeConv:k,onModalButton:_.handleModalButton}),s.jsx(Wa,{activeConv:k,ideEntry:y,showMetaChips:!1,handleSendChat:_.handleSendChat,isSendingChat:_.isSendingChat,sendFeedbackMessage:_.sendFeedbackMessage,handleFocusAgent:_.handleFocusAgent,isFocusingAgent:_.isFocusingAgent,actionLogs:R,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${b==="split"?"order-1 md:order-2":""}`,children:s.jsx(Xc,{addLog:()=>{},connState:k.connectionState||"new",connScreenshot:T,screenshotUsage:F,transportType:k.transport,onAction:H})})]})]})})}function By({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=wh(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 ",o,"?"]}),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 Oy({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(Ch,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(Mo,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,missingWorkspaceResumePath:e.missingWorkspaceResumePath,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),t.conversation&&s.jsx($y,{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&&(st(r.targetConv)||Ze(r.targetConv))&&s.jsx(By,{activeConv:r.targetConv,canSaveAndStop:st(r.targetConv)&&!Ze(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(Dl,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&s.jsx(Py,{onClose:o.onClose})]})}function Ky({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:o}){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(wr,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[r?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(c=>{const l=Ct(c,{fallbackId:c.id}),d=n[c.id],m=c.version||c.daemonVersion||"unknown",u=c.versionUpdateRequired===!0,b=ld(c)==="preview"?"Update to preview":u?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:l}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),u&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:b})]},c.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:s.jsx(gt,{size:16})})]})}function Fy(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Wy(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 Hy(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>Wy(t)).map(t=>t.id)}}function Uy(){var Yo,Xo,Jo,Qo;const{sendCommand:e}=yt(),t=Sr(),r=ql(),n=so(),a=Ws(),[o,c]=Mu(),l=o.get("activeTab"),d=((Yo=n.state)==null?void 0:Yo.openRemoteForTabKey)||null,m=((Xo=n.state)==null?void 0:Xo.openMachineId)||null,u=((Jo=n.state)==null?void 0:Jo.mobileSection)||null,f=Nl(),b=f.ides||[],v=f.initialLoaded??!0,{updateRouteChats:h,setToasts:p}=f,[g,y]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),x=f.toasts||[],C=f.wsStatus||"connected",S=f.isConnected??!0,w=f.connectionStates||{},M=f.showReconnected||!1,{layoutProfile:L,groupAssignments:j,updateGroupAssignments:k,focusedGroup:B,updateFocusedGroup:_,focusGroup:T,groupActiveTabIds:F,updateGroupActiveTabIds:H,setGroupActiveTab:R,groupTabOrders:I,updateGroupTabOrders:N,setGroupTabOrder:K,groupSizes:P,updateGroupSizes:E,isMobile:U,hasHydratedStoredLayout:ee,hydrateStoredLayout:ye,focusConversationTab:le}=bb(),[Q,xe]=i.useState(()=>Po());i.useEffect(()=>Mx(xe),[]);const we=i.useMemo(()=>Fy({isMobile:U,mobileViewMode:Q}),[U,Q]),[be,X]=i.useState([]),[ue,fe]=i.useState({}),[ve,pe]=i.useState({});jr("Dashboard",{ideCount:b.length,toastCount:x.length,focusedGroup:B,groupCount:Object.keys(j).length,actionLogCount:be.length});const Se=i.useMemo(()=>b.filter(Ve=>Ve.type==="adhdev-daemon").sort(ho),[b]),Z=Se[0],de=!!Z;i.useEffect(()=>{const{metadataDaemonIds:Ve,runtimeDaemonIds:Lt}=Hy(Se);for(const zs of Ve)t(zs,{minFreshMs:3e4}).catch(()=>{});for(const zs of Lt)r(zs,{minFreshMs:3e4}).catch(()=>{})},[t,r,Se]);const oe=(Z==null?void 0:Z.terminalBackend)||null,me=Z?Ct(Z,{fallbackId:Z.id}):null,ie=(Z==null?void 0:Z.id)||null,D=i.useMemo(()=>Hx(b,ue),[b,ue]),{hiddenTabs:z,autoHiddenTabs:ce,autoHideTarget:re,hideTarget:G,toggleTarget:je,showTarget:ge,showAllTabs:Ae}=Wx(),{conversations:Me,visibleConversations:O,visibleTabKeys:Ne,resolveConversationBySessionId:Re,resolveConversationByTarget:Fe}=sb({ides:D,connectionStates:w,clearedTabs:ve,hiddenTabs:z}),He=i.useMemo(()=>new Map(Me.map(Ve=>[Ve.tabKey,Ve])),[Me]),Ge=i.useMemo(()=>Fx(Me,z,ce),[Me,z,ce]);i.useEffect(()=>{for(const Ve of Ge)re(Ve)},[Ge,re]),Qf(O,we),i.useEffect(()=>{Object.keys(ue).length!==0&&fe(Ve=>Ux(Ve,b))},[b,ue]);const qe=i.useMemo(()=>ap(b),[b]),{notifications:et,unreadCount:dt}=_b({conversations:Me,liveSessionInboxState:qe}),{handleMarkDashboardNotificationRead:pt,handleMarkDashboardNotificationUnread:bt,handleDeleteDashboardNotification:Ce}=Pb({notifications:et,sendDaemonCommand:e}),{containerRef:Ue,normalizedGroupAssignments:Qe,numGroups:ze,isSplitMode:rt,groupedConvs:W,moveTabToGroup:V,closeGroup:J,handleResizeStart:ne,splitTabRelative:$}=Sb({groupAssignments:j,updateGroupAssignments:k,updateFocusedGroup:_,updateGroupActiveTabIds:H,updateGroupTabOrders:N,groupSizes:P,updateGroupSizes:E,isMobile:U,visibleConversations:O,visibleTabKeys:Ne}),{activeConv:q,openDesktopConversation:se,requestScrollToBottom:ae,scrollToBottomRequest:ke,setDesktopActiveTab:_e}=Yb({isMobile:U,conversations:Me,visibleConversations:O,groupActiveTabIds:F,focusedGroup:B,groupedConvs:W,setSearchParams:c});Qb({activeConv:q,isMobile:U,liveSessionInboxState:qe,sendDaemonCommand:e});const{requestedDesktopTabKey:De,requestedMobileTabKey:Te,consumeRequestedActiveTab:Ee}=rb({isMobile:U,urlActiveTab:l,resolveConversationBySessionId:Re,setSearchParams:c}),{remoteDialogConv:Oe,remoteDialogIdeEntry:Ie,remoteDialogActiveConv:Ye,setRemoteDialogActiveConv:Je,openRemoteDialog:ft,closeRemoteDialog:ht,cliStopDialogOpen:it,cliStopTargetConv:ut,requestCliStop:We,cancelCliStop:Et,confirmCliStop:te}=tg({isMobile:U,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:De,conversations:Me,ides:b,resolveConversationByTarget:Fe,activeConv:q,sendDaemonCommand:e}),{historyModalOpen:Pe,openHistoryModal:A,closeHistoryModal:Y,historyTargetConv:he,isSavedSessionHistoryTarget:$e,isHistoryCreatingChat:Le,isHistoryRefreshingHistory:Be,handleHistorySwitchSession:tt,handleHistoryNewChat:Nt,handleHistoryRefresh:mt,savedHistorySessions:Gt,savedHistoryFilters:Ir,setSavedHistoryFilters:Tr,missingWorkspaceResumePath:Mr,isSavedHistoryLoading:Ar,resumingSavedHistorySessionId:Lr,handleRefreshSavedHistory:Rr,handleResumeSavedHistorySession:_r}=Zb({activeConv:q,remoteDialogConv:Oe,remoteDialogActiveConv:Ye,ides:b,sendDaemonCommand:e,updateRouteChats:h,setToasts:p,setClearedTabs:pe,setSearchParams:c}),qd=i.useMemo(()=>O,[O]),Pr=U&&Q==="chat",Yd=i.useMemo(()=>Me.filter(Ve=>_n(z,Ve)),[Me,z]),Vo=i.useCallback(Ve=>{const Lt=new URLSearchParams(o);Lt.set("activeTab",Ve),c(Lt,{replace:!0})},[o,c]),{trackPendingLaunch:Xd}=zb({ides:b,conversations:Me,onOpenSession:Vo}),{handleBrowseMachineDirectory:Jd,handleSaveMachineWorkspace:Qd,handleLaunchMachineIde:Zd,handleLaunchMachineProvider:eu,handleListMachineMeshes:tu,handleLaunchMeshCoordinator:su,handleListMachineSavedSessions:ru,setActiveCliViewMode:nu}=Vb({sendDaemonCommand:e,trackPendingLaunch:Xd,onOpenSession:Vo,activeConv:q,ides:b,setCliViewModeOverrides:fe});zx({visibleConversations:O,clearedTabs:ve,setClearedTabs:pe,setActionLogs:X}),nb({ides:b,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Fe});const{isRefreshingHistory:au,handleRefreshHistory:ou}=cd({sendDaemonCommand:e,activeConv:q,chats:(Qo=b.find(Ve=>Ve.id===(q==null?void 0:q.routeId)))==null?void 0:Qo.chats,updateRouteChats:h,setToasts:p,setClearedTabs:pe});yb({urlActiveTab:U&&!Pr?l:null,conversations:Me,resolveConversationBySessionId:Re,normalizedGroupAssignments:Qe,hasHydratedStoredLayout:U&&!Pr?ee:!0,hydrateStoredLayout:U&&!Pr?ye:()=>{},focusConversationTab:le,setSearchParams:c,historyModalOpen:Pe,activeConv:q,isRefreshingHistory:au,ides:b,handleRefreshHistory:ou});const iu=i.useMemo(()=>!q||!st(q)||Ze(q)?null:Us(q),[q]),{versionMismatchDaemons:cu,hasRequiredVersionDaemons:Go,targetVersion:lu,versionBannerDismissed:du,setVersionBannerDismissed:uu,upgradingDaemons:mu,handleBannerUpgrade:pu}=Cb({ides:b,sendDaemonCommand:e}),qo=i.useCallback(Ve=>{ge(Ve),se(Ve)},[se,ge]),fu=i.useCallback(Ve=>{G(Ve)},[G]);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(Ih,{terminalBackend:oe,isStandalone:de,machineLabel:me,machineKey:ie}),(!du||Go)&&s.jsx(Ky,{daemons:cu,targetVersion:lu,required:Go,upgradingDaemons:mu,onUpgrade:pu,onDismiss:()=>uu(!0)}),s.jsx(_y,{showMobileChatMode:Pr,isMobile:U,activeConv:q,wsStatus:C,isConnected:S,onOpenHistory:Ve=>{Ve&&Je(Ve),A()},onOpenRemote:ft,onStopCli:We,activeCliViewMode:iu,onSetActiveCliViewMode:nu,mobileChatConversations:qd,ides:b,actionLogs:be,sendDaemonCommand:e,setActionLogs:X,setCliViewModeOverrides:fe,isStandalone:de,initialDataLoaded:v,userName:f.userName,requestedMobileTabKey:Te,onRequestedMobileTabConsumed:Ee,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:u,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Ue,isSplitMode:rt,numGroups:ze,groupSizes:P,groupedConvs:W,clearedTabs:ve,focusedGroup:B,focusGroup:T,moveTabToGroup:V,splitTabRelative:$,closeGroup:J,handleResizeStart:ne,groupActiveTabIds:F,setGroupActiveTab:R,groupTabOrders:I,setGroupTabOrder:K,toggleHiddenTab:Ve=>je(He.get(Ve)||{tabKey:Ve}),visibleConversations:O,hiddenConversations:Yd,requestedDesktopTabKey:De,onRequestedDesktopTabConsumed:Ee,onDesktopActiveTabChange:_e,onRequestScrollToBottom:ae,onHideConversation:fu,onShowHiddenConversation:qo,onShowAllHiddenConversations:Ae,scrollToBottomRequest:ke,machineEntries:Se,layoutProfile:L,onBrowseMachineDirectory:Jd,onSaveMachineWorkspace:Qd,onLaunchMachineIde:Zd,onLaunchMachineProvider:eu,onListMachineMeshes:tu,onLaunchMeshCoordinator:su,onListMachineSavedSessions:ru,notifications:et,notificationUnreadCount:dt,liveSessionInboxState:qe,onMarkNotificationRead:pt,onMarkNotificationUnread:bt,onDeleteNotification:Ce}),s.jsx("style",{children:`
70
- body { overflow: hidden; overscroll-behavior: none; }
71
- `}),s.jsx(Oy,{historyModal:{open:Pe,targetConv:he,ides:b,isCreatingChat:Le,isRefreshingHistory:$e?!1:Be,savedSessions:Gt,savedHistoryFilters:Ir,missingWorkspaceResumePath:Mr||null,onSavedHistoryFiltersChange:Tr,isSavedSessionsLoading:Ar,isResumingSavedSessionId:Lr,onClose:Y,onNewChat:Nt,onSwitchSession:tt,onRefreshHistory:$e?Rr:mt,onResumeSavedSession:_r},remoteDialog:{conversation:Oe,ideEntry:Ie,ides:b,connectionStates:w,actionLogs:be,sendDaemonCommand:e,setActionLogs:X,isStandalone:de,userName:f.userName,onOpenHistory:Ve=>{Ve&&Je(Ve),A()},onConversationChange:Je,onClose:ht},cliStopDialog:{open:it,targetConv:ut,onCancel:Et,onStopNow:async()=>{await te("hard")},onSaveAndStop:async()=>{await te("save")}},connectionBanner:{wsStatus:C,showReconnected:M,loginUrl:f.connectionLoginUrl,onReconnect:f.retryServerConnection},toastOverlay:{toasts:x,onDismiss:Ve=>p(Lt=>Lt.filter(zs=>zs.id!==Ve)),onClick:Ve=>{if(Ve.targetKey){const Lt=Fe(Ve.targetKey);Lt&&(le(Lt.tabKey,Qe),qo(Lt),ae(Lt.tabKey,"toast-open"))}}},onboarding:{open:g,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}y(!1)}}})]})}function zy({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[o,c]=i.useState([]),[l,d]=i.useState(null),[m,u]=i.useState(null),[f,b]=i.useState(!1),[v,h]=i.useState(null),[p,g]=i.useState(!1),[y,x]=i.useState(""),C=i.useRef(null),S=i.useCallback(P=>{C.current=P},[]),w=i.useCallback((P,E,U=!1)=>{c(ee=>[...ee.slice(-100),{timestamp:Date.now(),level:P,message:E}]),setTimeout(()=>{var ee;return(ee=a.current)==null?void 0:ee.scrollIntoView({behavior:"smooth"})},100),U&&nt.showToast(E,P==="error"||P==="warn"?"warning":"success")},[a]),M=i.useCallback(P=>{const E=P instanceof Error?P.message:String(P||"");return E.includes("P2P command timeout")||E.includes("P2P not connected")||E.includes("P2P not available")},[]),L=i.useCallback(async(P,E)=>{var U;if(!e||l)return!1;d(P),w("info",`Launching ${ot(P)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const ee={ideType:P,enableCdp:!0};(U=E==null?void 0:E.workspace)!=null&&U.trim()?ee.workspace=E.workspace.trim():E!=null&&E.useDefaultWorkspace&&(ee.useDefaultWorkspace=!0);const ye=await r(e,"launch_ide",ee);return w(ye!=null&&ye.success?"info":"error",ye!=null&&ye.success?`${ot(P)} launched`:`Failed: ${ye==null?void 0:ye.error}`,!0),!!(ye!=null&&ye.success)}catch(ee){return w("error",`Launch error: ${ee.message}`,!0),!1}finally{d(null)}},[e,l,w,r]),j=i.useCallback(async P=>{if(!e)return{success:!1};const{cliType:E,dir:U,workspaceId:ee,useDefaultWorkspace:ye,useHome:le,argsStr:Q,model:xe,resumeSessionId:we}=P;if(!E)return w("warn","Select a CLI or ACP provider first",!0),{success:!1};const be=Q?Q.split(/\s+/).filter(Boolean):void 0,X=(U==null?void 0:U.trim())||(ee?"(saved id)":ye?"(default workspace)":le?"(home)":"");w("info",`Launching ${E}${X?` in ${X}`:""}${xe?` (model: ${xe})`:""}...`),u(E);try{const ue={cliType:E,cliArgs:be,initialModel:xe||void 0};U!=null&&U.trim()?ue.dir=U.trim():ee?ue.workspaceId=ee:ye?ue.useDefaultWorkspace=!0:le&&(ue.useHome=!0),we&&(ue.resumeSessionId=we);const fe=await r(e,"launch_cli",ue),ve=(fe==null?void 0:fe.result)||fe;return fe!=null&&fe.success?(w("info",`${E} launched`,!0),(ve==null?void 0:ve.launchSource)==="home"?w("info","📂 Running in home directory (explicit choice)"):(ve==null?void 0:ve.launchSource)==="defaultWorkspace"&&w("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ve==null?void 0:ve.sessionId}):(w("error",`Failed: ${(fe==null?void 0:fe.error)||(ve==null?void 0:ve.error)}`,!0),(fe==null?void 0:fe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&h({cliType:E,argsStr:Q,model:xe}),{success:!1,sessionId:ve==null?void 0:ve.sessionId})}catch(ue){return M(ue)?(w("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(w("error",`Launch error: ${ue.message}`,!0),{success:!1})}finally{u(null)}},[e,w,M,r]),k=i.useCallback(async(P,E,U,ee)=>e?P?E.trim()?j({cliType:P,dir:E,argsStr:U,model:ee}):(h({cliType:P,argsStr:U,model:ee}),{success:!1}):(w("warn","Select a provider",!0),{success:!1}):{success:!1},[e,w,j]),B=i.useCallback(async(P,E,U)=>{if(e&&window.confirm(`Stop ${P}?
72
- This will terminate the process.`))try{const ee=await r(e,"stop_cli",{cliType:P,dir:E,targetSessionId:U});ee!=null&&ee.success?w("info",`${P} stopped`,!0):w("error",`Stop failed: ${(ee==null?void 0:ee.error)||"Unknown error"}`,!0)}catch(ee){w("error",`Stop failed: ${ee.message}`,!0)}},[e,w,r]),_=i.useCallback(async P=>{try{await r(P.daemonId,"restart_ide",{ideType:P.type}),w("info",`${ot(P.type)} restart initiated`,!0)}catch(E){w("error",`Restart failed: ${E.message}`,!0)}},[w,r]),T=i.useCallback(async P=>{if(window.confirm(`Stop ${ot(P.type)}?
73
- This will disconnect CDP and optionally kill the process.`))try{const E=await r(P.daemonId,"stop_ide",{ideType:P.type,killProcess:!0});E!=null&&E.success?w("info",`${ot(P.type)} stopped`,!0):w("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){w("error",`Stop failed: ${E.message}`,!0)}},[w,r]),F=i.useCallback(async()=>{if(e)try{const P=await r(e,"detect_ides",{});w("info",`Found ${((P==null?void 0:P.result)||[]).length} IDE(s)`,!0)}catch(P){w("error",`Detection failed: ${P.message}`,!0)}},[e,w,r]),H=i.useCallback(async P=>{if(!e||!P.trim())return!1;b(!0);try{const E=await r(e,"workspace_add",{path:P.trim()});return E!=null&&E.success?(w("info",`Workspace added: ${P.trim()}`),!0):(w("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return w("error",E.message),!1}finally{b(!1)}},[e,w,r]),R=i.useCallback(async P=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){b(!0);try{const E=await r(e,"workspace_remove",{id:P});E!=null&&E.success?w("info","Workspace removed",!0):w("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){w("error",E.message,!0)}finally{b(!1)}}},[e,w,r]),I=i.useCallback(async P=>{var E;if(e){b(!0);try{const U=await r(e,"workspace_set_default",P===null?{clear:!0}:{id:P});if(U!=null&&U.success){w("info",P?"Default workspace updated":"Default workspace cleared",!0);const ee=typeof U.defaultWorkspacePath=="string"?U.defaultWorkspacePath:"";ee&&((E=C.current)==null||E.call(C,ee))}else w("error",(U==null?void 0:U.error)||"workspace_set_default failed",!0)}catch(U){w("error",U.message,!0)}finally{b(!1)}}},[e,w,r]),N=i.useCallback(async P=>{var U;if(!e||!P.trim())return;const E=P.trim();b(!0);try{const ee=await r(e,"workspace_set_default",{path:E});ee!=null&&ee.success?(w("info","Default workspace set from history"),(U=C.current)==null||U.call(C,E)):w("error",(ee==null?void 0:ee.error)||"Could not set default (path missing on disk?)")}catch(ee){w("error",ee.message)}finally{b(!1)}},[e,w,r]),K=i.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(P){w("warn",`Live nickname updated, but account sync failed: ${P.message}`)}w("info",`Nickname set to "${y||"(cleared)"}"`),g(!1)}catch(P){w("error",`Failed: ${P.message}`)}},[e,y,t,w,n,r]);return{logs:o,launchingIde:l,launchingAgentType:m,workspaceBusy:f,launchPick:v,setLaunchPick:h,editingNickname:p,setEditingNickname:g,nicknameInput:y,setNicknameInput:x,addLog:w,handleLaunchIde:L,runLaunchCliCore:j,handleLaunchCli:k,handleStopCli:B,handleRestartIde:_,handleStopIde:T,handleDetectIdes:F,handleWorkspaceAdd:H,handleWorkspaceRemove:R,handleWorkspaceSetDefault:I,handleWorkspaceResumePath:N,handleSaveNickname:K,setOnDefaultWorkspaceChanged:S}}function Vy({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:c}){var _;const{workspaceBusy:l,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=o,[f,b]=i.useState(!1),[v,h]=i.useState(""),[p,g]=i.useState([]),[y,x]=i.useState(!1),[C,S]=i.useState(""),w=i.useCallback(async T=>{x(!0),S("");try{const F=await En(c,e,T);h(F.path),g(F.directories)}catch(F){S(F instanceof Error?F.message:"Could not load folder")}finally{x(!1)}},[e,c]),M=i.useCallback(()=>{b(!0);const T=[...r.map(H=>H.workspace),...n.map(H=>H.workspace),...a.map(H=>H.workspace)],F=Dn(t.platform,Pn(T,t.defaultWorkspacePath,(t.workspaces||[]).map(H=>H.path)));w(F)},[a,n,r,w,t.defaultWorkspacePath,t.platform,t.workspaces]),L=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,j=t.availableMem??t.freeMem??t.totalMem,k=L&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-j)/t.totalMem*100))):0,B=((_=t.loadavg)==null?void 0:_[0])||0;return s.jsxs("div",{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[s.jsx(Er,{icon:s.jsx(Fc,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?up(t.uptime):"Waiting…"}),s.jsx(Er,{icon:s.jsx(It,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(Er,{icon:s.jsx(io,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(Er,{icon:s.jsx(um,{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(fi,{value:L?Math.min(Math.round(B/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:L?`${B.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(fi,{value:k,max:100,label:"Memory",color:"#3b82f6",detail:L?`${Gn(t.totalMem-j)} / ${Gn(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Gn(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(xs,{size:14})," Workspaces"]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),s.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:l,value:t.defaultWorkspaceId||"",onChange:T=>void u(T.target.value===""?null:T.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(T=>s.jsx("option",{value:T.id,children:T.label||T.path},T.id))]}),t.defaultWorkspacePath&&s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:t.defaultWorkspacePath,children:t.defaultWorkspacePath})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:l,onClick: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(T=>s.jsxs("li",{className:"flex items-start gap-2 text-[11px] text-text-muted rounded-lg border border-border-subtle bg-bg-primary px-2.5 py-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[T.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:Mn(T.path,T.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:T.path,children:T.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void m(T.id),children:"Remove"})]},T.id))})]}),f&&s.jsx($n,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:v,directories:p,busy:y,error:C,confirmLabel:"Add workspace",onClose:()=>b(!1),onNavigate:T=>{w(T)},onConfirm:T=>{(async()=>{if(!T)return;await d(T)&&b(!1)})()}})]})}function Gy(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 qy(e,t,r){const n=[];for(const[a,o]of Object.entries(e.settings)){const c=r!=null&&r.filterSchema?r.filterSchema(o):o;if(c.length===0)continue;const l=t.find(d=>d.type===a);n.push({type:a,displayName:(l==null?void 0:l.displayName)||a,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[a]||{}})}return n}function ya(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 fc(e){if(!e||typeof e!="object")return null;if(ya(e))return e;const t=e,r=t.result;return ya(r)?r:ya(t.sourceConfig)?t.sourceConfig:null}function Yy(e){const t=e.trim();return t||null}const hc=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Xy=[{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 Jy({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,o]=i.useState("config"),[c,l]=i.useState("codex-cli"),[d,m]=i.useState([]),[u,f]=i.useState(""),[b,v]=i.useState([]),[h,p]=i.useState(""),g=i.useRef(null),y=i.useRef(null),x=j=>{m(k=>k.includes(j)?k.filter(B=>B!==j):[...k,j])},C=()=>m([...hc]),S=()=>m([]);i.useEffect(()=>{var j;(j=g.current)==null||j.scrollIntoView({behavior:"smooth"})},[b]),i.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const w=i.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const j=await r(e,"provider_auto_fix_status",{providerType:t.type});(j==null?void 0:j.running)===!1&&a==="running"&&(o("done"),v(k=>[...k,`
74
- ✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[e,t.type,r,a]),M=async()=>{if(d.length!==0){o("running"),v(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${d.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),p("");try{const j=await r(e,"provider_auto_fix",{providerType:t.type,functions:d,agent:c,...u?{comment:u}:{}});j!=null&&j.success&&(j!=null&&j.started||j!=null&&j.running)?(v(k=>[...k,"✅ Agent started. Monitoring progress..."]),w()):(o("error"),p((j==null?void 0:j.error)||"Failed to start auto-fix"))}catch(j){o("error"),p((j==null?void 0:j.message)||"Connection failed")}}},L=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),v(j=>[...j,`
75
- ⚠️ Auto-fix cancelled.`]),o("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:j=>j.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:Xy.map(j=>s.jsxs("button",{onClick:()=>l(j.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===j.value?j.color+"66":"var(--border-subtle)",background:c===j.value?j.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===j.value?j.color:"var(--text-primary)"},children:j.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:j.desc})]},j.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:S,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:hc.map(j=>s.jsxs("button",{onClick:()=>x(j),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(j)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(j)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(j)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(j)?"☑ ":"☐ ",j]},j))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",s.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:u,onChange:j=>f(j.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:[b.map((j,k)=>s.jsx("div",{className:j.startsWith("✅")?"text-green-400":"",style:j.startsWith("❌")||j.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:j},k)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:g})]}),h&&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:h})]})]}),s.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[s.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&d.length>0&&`${d.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),s.jsxs("div",{className:"flex gap-2",children:[a==="config"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:M,disabled:d.length===0,className:"machine-btn",style:{background:d.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:d.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:d.length>0?"#a78bfa":void 0,opacity:d.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&s.jsx("button",{onClick:L,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:()=>{o("config"),v([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Qy({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var w;const o=t.filter(M=>M.category==="ide"),[c,l]=i.useState(((w=o[0])==null?void 0:w.type)||""),[d,m]=i.useState(""),[u,f]=i.useState(""),[b,v]=i.useState(!1),[h,p]=i.useState(""),[g,y]=i.useState(!1),x=M=>{const L=M.toLowerCase().replace(/[^a-z0-9-]/g,"");m(L),(!u||u===C(d))&&f(C(L))},C=M=>M.split("-").map(L=>L.charAt(0).toUpperCase()+L.slice(1)).join(" "),S=async()=>{if(!(!d||!u||!c)){v(!0),p("");try{const M=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:c});M!=null&&M.success||M!=null&&M.created?(y(!0),a==null||a(d)):p((M==null?void 0:M.error)||"Failed to create provider")}catch(M){p((M==null?void 0:M.message)||"Connection failed")}v(!1)}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick: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:g?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:d})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:o.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:d,onChange:M=>x(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/",d||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:u,onChange:M=>f(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"})]}),h&&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:h})]})}),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:g?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:S,disabled:!d||!u||b,className:"machine-btn",style:{background:d&&u?"rgba(34,197,94,0.12)":void 0,borderColor:d&&u?"rgba(34,197,94,0.3)":void 0,color:d&&u?"#86efac":void 0,opacity:!d||!u||b?.4:1},children:b?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function xc(e){return e==="cli"||e==="acp"}function Zy(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 e0(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 bc(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 t0({machineId:e,providers:t,sendDaemonCommand:r}){var H;const[n,a]=i.useState([]),[o,c]=i.useState(!1),[l,d]=i.useState(null),[m,u]=i.useState("all"),[f,b]=i.useState(null),[v,h]=i.useState(!1),[p,g]=i.useState(null),[y,x]=i.useState("normal"),[C,S]=i.useState(""),[w,M]=i.useState(!1),L=i.useCallback(async()=>{if(e)try{const R=await r(e,"get_provider_source_config",{}),I=fc(R);I&&(g(I),x(I.sourceMode),S(I.explicitProviderDir||""))}catch{}},[e,r]),j=i.useCallback(async()=>{if(e){c(!0);try{const R=await r(e,"get_provider_settings",{}),I=Gy(R);if(I){const N=qy(I,t,{filterSchema:K=>K.filter(P=>P.key!=="enabled")});N.sort((K,P)=>K.category.localeCompare(P.category)||K.displayName.localeCompare(P.displayName)),a(N)}}catch{}c(!1)}},[e,t,r]);i.useEffect(()=>{n.length===0&&j(),p||L()},[]);const k=async(R,I,N)=>{d(`${R}.${I}`),a(K=>K.map(P=>P.type===R?{...P,values:{...P.values,[I]:N}}:P));try{const K=await r(e,"set_provider_setting",{providerType:R,key:I,value:N});K!=null&&K.success||j()}catch{j()}d(null)},B=async(R,I)=>{await k(R,"enabled",I),await j()},_=async R=>{d(`${R}.detect`);try{await r(e,"detect_provider",{providerType:R})}finally{await j(),d(null)}},T=async R=>{await k(R,"executablePath",""),await k(R,"executableArgs",""),await j()},F=async()=>{M(!0);try{const R=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:Yy(C)}),I=fc(R);I?(g(I),x(I.sourceMode),S(I.explicitProviderDir||"")):await L(),await j()}catch{await L()}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(R=>s.jsx("button",{onClick:()=>u(R),className:`machine-btn text-[10px] px-2 py-0.5 ${m===R?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:R.toUpperCase()},R))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>h(!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:j,disabled:o,className:"machine-btn",children:o?"⏳ Loading...":"↻ Refresh"})]})]}),s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Running CLI sessions refresh provider scripts/config; process binary changes still apply on next launch."})]}),s.jsx("button",{onClick:L,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:R=>x(R.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:R=>S(R.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void F(),disabled:w,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:w?"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:"})," ",((H=p==null?void 0:p.providerRoots)==null?void 0:H.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(R=>R.category===m).length>1&&(()=>{const R=n.filter(P=>P.category===m),I=new Map;for(const P of R)for(const E of P.schema){if(E.type!=="boolean")continue;const U=I.get(E.key),ee=!!(P.values[E.key]??E.default);U?(U.onCount+=ee?1:0,U.total+=1):I.set(E.key,{label:E.label||E.key,onCount:ee?1:0,total:1})}const N=[...I.entries()].filter(([,P])=>P.total===R.length);if(N.length===0)return null;const K=async(P,E)=>{for(const U of R)await k(U.type,P,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 (",R.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:N.map(([P,E])=>{const U=E.onCount===E.total,ee=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 K(P,!0),disabled:U,className:`machine-btn text-[9px] px-1.5 py-px ${U?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void K(P,!1),disabled:ee,className:`machine-btn text-[9px] px-1.5 py-px ${ee?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},P)})})]})})(),o&&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(R=>m==="all"||R.category===m).map(R=>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:R.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:R.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:R.category==="acp"?"rgba(139,92,246,0.08)":R.category==="cli"?"rgba(59,130,246,0.08)":R.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:R.category==="acp"?"#a78bfa":R.category==="cli"?"#60a5fa":R.category==="ide"?"#86efac":"var(--status-warning)"},children:R.category}),xc(R.category)&&(()=>{const I=t.find(P=>P.type===R.type),N=(I==null?void 0:I.enabled)===!0||R.values.enabled===!0,K=(I==null?void 0:I.machineStatus)||(N?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${e0(K)}`,children:Zy(K)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void B(R.type,!N),disabled:l===`${R.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${N?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:N?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void _(R.type),disabled:!N||l===`${R.type}.detect`,title:N?"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 ${N?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void T(R.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),R.category==="ide"&&s.jsx("button",{onClick:()=>b(t.find(I=>I.type===R.type)||{type:R.type,name:R.displayName,displayName:R.displayName,icon:R.icon,category:R.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"})]}),xc(R.category)&&(()=>{const I=t.find(N=>N.type===R.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:"})," ",bc(I==null?void 0:I.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",bc(I==null?void 0:I.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:R.schema.map(I=>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:[I.label||I.key,l===`${R.type}.${I.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),I.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:I.description})]}),s.jsx("div",{className:"shrink-0",children:I.type==="boolean"?s.jsx("button",{onClick:()=>k(R.type,I.key,!(R.values[I.key]??I.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:R.values[I.key]??I.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:R.values[I.key]??I.default?21:3}})}):I.type==="number"?s.jsx("input",{type:"number",value:Number(R.values[I.key]??I.default??0)||0,min:I.min,max:I.max,onChange:N=>{const K=parseInt(N.target.value)||0;I.min!==void 0&&K<I.min||I.max!==void 0&&K>I.max||k(R.type,I.key,K)},className:"machine-input w-20 text-center text-[11px]"}):I.type==="select"&&I.options?s.jsx("select",{value:String(R.values[I.key]??I.default??""),onChange:N=>k(R.type,I.key,N.target.value),className:"machine-input text-[11px]",children:I.options.map(N=>s.jsx("option",{value:N,children:N},N))}):s.jsx("input",{type:"text",value:String(R.values[I.key]??I.default??""),onBlur:N=>k(R.type,I.key,N.target.value),className:"machine-input w-[120px] text-[11px]"})})]},I.key))})]},R.type))}),f&&s.jsx(Jy,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>b(null)}),v&&s.jsx(Qy,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>h(!1),onCreated:()=>{h(!1),j()}})]})}const s0=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function r0({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function n0(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function a0(e){return e.trim().toLowerCase()}function On(e,t){const r=a0(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Ho(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Fs(e,t=220){const r=Ho(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function o0(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 i0(e,t){return e.filter(r=>On([r.level,r.message],t))}function gc(e){return`${e.timestamp}:${e.level}:${e.message}`}function c0(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const c of e.entries)n.set(gc(c),c);for(const c of t.entries)n.set(gc(c),c);const a=Array.from(n.values()).sort((c,l)=>c.timestamp-l.timestamp).slice(-r),o=a.reduce((c,l)=>Math.max(c,Number(l.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:o}}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 l0(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,o)=>a.ts-o.ts).slice(-r)}function d0(e,t){return e.split(`
76
- `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>On([r],t))}function u0(e,t){return e.filter(r=>On([r.level,r.category,r.stage,r.interactionId,Ho(r.payload)],t))}function m0(e,t){return e.filter(r=>On([r.kind,r.topic,r.interactionId,Ho(r.payload)],t))}function yc(e){return e==="warn"||e==="error"}function p0({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=>yc(a.level)).length+r.filter(a=>yc(a.level)).length}}function f0({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(o=>`${new Date(o.timestamp).toISOString()} ${o.level.toUpperCase()} ${o.message}`)].join(`
77
- `)):t.length>0&&a.push(["[daemon logs]",...t].join(`
78
- `)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${Fs(o.payload,500)}`.trim())].join(`
79
- `)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${Fs(o.payload,500)}`.trim())].join(`
80
- `)),a.join(`
81
-
82
- `)}function h0({machineId:e,sendDaemonCommand:t}){const[r,n]=i.useState([]),[a,o]=i.useState("empty"),[c,l]=i.useState(""),[d,m]=i.useState([]),[u,f]=i.useState([]),[b,v]=i.useState(null),[h,p]=i.useState(!0),[g,y]=i.useState("info"),[x,C]=i.useState("all"),[S,w]=i.useState(!0),[M,L]=i.useState(!0),[j,k]=i.useState(""),[B,_]=i.useState(""),[T,F]=i.useState(0),H=i.useRef(0),R=i.useRef(0),I=i.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),N=i.useRef([]),K=i.useCallback(()=>{const Q={entries:[],kind:"empty",rawText:"",lastTs:0};I.current=Q,H.current=0,n([]),l(""),o("empty"),w(!0)},[]),P=i.useCallback(()=>{N.current=[],R.current=0,m([]),L(!0)},[]),E=i.useCallback(Q=>{Q!==g&&(K(),y(Q))},[g,K]),U=i.useCallback(Q=>{C(xe=>xe===Q?xe:Q)},[]),ee=i.useCallback(()=>{K(),P(),f([]),v(null),k(""),_(""),_s.clear()},[K,P]),ye=i.useCallback(()=>{F(Q=>Q+1)},[]),le=i.useCallback(async()=>{if(!e)return;const Q=H.current,xe=R.current,[we,be]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:g,since:Q}),t(e,"get_debug_trace",r0({count:120,since:xe,category:x}))]);if(we.status==="fulfilled"){const X=we.value,ue=(X==null?void 0:X.result)||X,fe=o0(ue),ve=c0(I.current,fe,300);I.current=ve,H.current=ve.lastTs,w(!1),k((X==null?void 0:X.success)===!1?String((X==null?void 0:X.error)||"Could not load daemon logs"):""),o(ve.kind),l(ve.rawText),n(ve.entries)}else w(!1),k(we.reason instanceof Error?we.reason.message:"Could not load daemon logs");if(be.status==="fulfilled"){const X=be.value,ue=(X==null?void 0:X.result)||X;if((X==null?void 0:X.success)===!1)_(String((X==null?void 0:X.error)||"Could not load daemon trace"));else if(Array.isArray(ue==null?void 0:ue.trace)){const fe=ue.trace,ve=l0(N.current,fe,120),pe=fe.reduce((Se,Z)=>Math.max(Se,Number(Z.ts||0)),xe);N.current=ve,pe>xe&&(R.current=pe),_(""),m(ve)}else _("");L(!1)}else L(!1),_(be.reason instanceof Error?be.reason.message:"Could not load daemon trace");f(_s.list({limit:120})),v(Date.now())},[g,e,t,x]);return i.useEffect(()=>{P()},[P,x]),i.useEffect(()=>{if(!e||(le(),!h))return;const Q=setInterval(()=>{le()},3e3);return()=>clearInterval(Q)},[h,le,e,T]),{daemonLogs:r,daemonLogKind:a,daemonRawText:c,debugTrace:d,webEvents:u,lastUpdatedAt:b,autoRefresh:h,logLevel:g,traceCategory:x,daemonLoading:S,traceLoading:M,daemonFetchError:j,traceFetchError:B,setAutoRefresh:p,setLogLevel:E,setTraceCategory:U,refresh:ye,clear:ee}}function x0({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:c,traceCount:l,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":o>0||c>0?"ok":"empty",detail:r||(a==="text"?`${c} raw file-fallback line(s)`:`${o} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":t?"loading":l>0?"ok":"empty",detail:n||`${l} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function vc(e){return e==="warn"||e==="error"}function b0(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 g0(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 wc(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function y0(e){const t=Fs(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function v0(e){const t=Fs(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function w0({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.forEach((o,c)=>{a.push({id:`daemon-log-${o.timestamp}-${c}`,source:"daemon_log",ts:Number(o.timestamp||0),severity:o.level,message:o.message,raw:o.message})}),n.forEach(o=>{a.push({id:`browser-event-${o.id}`,source:"browser_event",ts:Number(o.ts||0),severity:"info",message:v0(o),topic:o.topic,interactionId:o.interactionId,payload:o.payload})}),r.forEach(o=>{a.push({id:`daemon-trace-${o.id}`,source:"daemon_trace",ts:Number(o.ts||0),severity:o.level,message:y0(o),category:o.category,stage:o.stage,interactionId:o.interactionId,payload:o.payload})}),t.forEach((o,c)=>{a.push({id:`raw-file-${c}`,source:"raw_file",ts:g0(o,c),severity:b0(o),message:o,raw:o})}),a.sort((o,c)=>o.ts!==c.ts?o.ts-c.ts:wc(o.source)-wc(c.source))}function j0(e){return`${e.source}:${e.severity}:${e.message}`}function k0(e){const t=e.filter(n=>vc(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!vc(n.severity))continue;const a=j0(n),o=r.get(a);o?(o.count+=1,o.firstTs=Math.min(o.firstTs,n.ts),o.lastTs=Math.max(o.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 S0(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function jc(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${S0(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function N0({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
83
- `)),a.push(["[source status]",...r.map(c=>`${c.label}: ${c.status} - ${c.detail}`)].join(`
84
- `)),t.latestIssue&&a.push(["[latest issue]",jc(t.latestIssue)].join(`
85
- `)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(c=>`${c.count}x ${c.severity.toUpperCase()} ${c.source} ${c.message}`)].join(`
86
- `));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(jc):["No diagnostic events captured."]].join(`
87
- `)),a.join(`
88
-
89
- `)}function C0(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function I0(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function T0({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:c,searchQuery:l,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f}){const b=n0(n,o),v=i0(e,l),h=d0(t,l),p=u0(b,l),g=m0(a,l),y=C0(v,c),x=c==="all"?h:[],C=I0(p,c),S=c==="issues"?[]:g,w=p0({daemonLogs:v,daemonRawLines:h,trace:p,webEvents:g}),M=w0({daemonLogs:y,daemonRawLines:x,trace:C,webEvents:S}),L=k0(M),j=x0({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f,daemonLogKind:r,daemonLogsCount:v.length,daemonRawLineCount:h.length,traceCount:p.length,webEventCount:g.length});return{filteredDaemonLogs:v,filteredDaemonRawLines:h,filteredTraceEntries:p,filteredWebEvents:g,visibleDaemonLogs:y,visibleDaemonRawLines:x,visibleTraceEntries:C,visibleWebEvents:S,quickFilterCounts:w,diagnosticEvents:M,diagnosticsSummary:L,sourceStates:j}}function M0(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Ud(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Qa(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 va(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 Uo(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function A0({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Qa(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Ud(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Uo(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 L0({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:c,onCopyVisible:l,onToggleAutoRefresh:d,onRefresh:m,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(f=>s.jsx("button",{type:"button",onClick:()=>a(f.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===f.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:f.label},f.id))}),s.jsx("input",{value:r,onChange:f=>o(f.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:l,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function R0({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:s0.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 _0({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:c,traceFetchError:l}){var u,f;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((f=e.latestIssue)==null?void 0:f.severity)==="warn"?"warning":"good",m=c||l?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${va(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 ${va(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[Uo(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:Ud(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 ${va(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":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",M0(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(b=>s.jsxs("div",{children:[b.label,": ",b.status]},b.id))})]})]})}function P0({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()," · ",Uo(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function D0({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:c,visibleWebEvents:l,quickFilter:d,searchQuery:m}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,timeline:!u.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(u=>s.jsx(A0,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,daemon:!u.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.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&&o.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"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,f)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${f}`)),e.daemonLogKind!=="text"&&a.map((u,f)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Qa(u.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:u.message})]},`log-${f}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,trace:!u.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&c.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&c.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),c.map(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Qa(u.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.level.toUpperCase()}),s.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Fs(u.payload,360)||"No payload"})]},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,web:!u.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[l.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),l.map(u=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.kind}),u.topic&&s.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Fs(u.payload,360)||"No payload"})]},u.id))]})]})]})}function E0({machineId:e,sendDaemonCommand:t}){const r=h0({machineId:e,sendDaemonCommand:t}),[n,a]=i.useState("info"),[o,c]=i.useState(""),[l,d]=i.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=i.useRef(null),u=i.useRef(!1),f=i.useMemo(()=>T0({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:o,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,o,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);i.useEffect(()=>{if(r.autoRefresh&&f.diagnosticEvents.length>0){const h=u.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:h}),u.current=!0},50)}},[f.diagnosticEvents.length,r.autoRefresh]);const b=i.useCallback(async()=>{var p;const h=f0({daemonLogs:f.visibleDaemonLogs,daemonRawLines:f.visibleDaemonRawLines,trace:f.visibleTraceEntries,webEvents:f.visibleWebEvents});if(!h.trim()){nt.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(h)),nt.showToast("Copied visible logs to clipboard.","success")}catch(g){nt.showToast(g instanceof Error?g.message:"Could not copy visible logs","warning")}},[f.visibleDaemonLogs,f.visibleDaemonRawLines,f.visibleTraceEntries,f.visibleWebEvents]),v=i.useCallback(async()=>{var p;const h=N0({events:f.diagnosticEvents,summary:f.diagnosticsSummary,sources:f.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(h)),nt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(g){nt.showToast(g instanceof Error?g.message:"Could not copy diagnostic bundle","warning")}},[f.diagnosticEvents,f.diagnosticsSummary,f.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(L0,{quickFilter:n,quickFilterCounts:f.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{v()},onCopyVisible:()=>{b()},onToggleAutoRefresh:()=>r.setAutoRefresh(h=>!h),onRefresh:r.refresh,onClear:r.clear}),s.jsx(R0,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(_0,{diagnosticsSummary:f.diagnosticsSummary,diagnosticEventsCount:f.diagnosticEvents.length,sourceStates:f.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(P0,{patterns:f.diagnosticsSummary.repeatedPatterns}),s.jsx(D0,{streams:r,sectionsOpen:l,setSectionsOpen:d,diagnosticEvents:f.diagnosticEvents,visibleDaemonLogs:f.visibleDaemonLogs,visibleDaemonRawLines:f.visibleDaemonRawLines,visibleTraceEntries:f.visibleTraceEntries,visibleWebEvents:f.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function $0(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 zd(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 B0(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const c=String((o==null?void 0:o.lifecycle)||"").trim(),l=zd((o==null?void 0:o.meta)||void 0),d=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?t.push(o):(c==="stopped"||c==="failed")&&(d||l)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function O0(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function wa(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 ja(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function ka(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function kc(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 K0(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function F0(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 W0(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 o=`${n.providerType}::${n.workspace}::${a}`;t.set(o,(t.get(o)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function H0({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,c]=i.useState(null),[l,d]=i.useState(!1),m=Ex(e,{enabled:!!e,includeSessions:!0,limit:Si,intervalMs:Rf}),u=m.diagnostics,f=m.loading,b=m.applyDiagnostics,v=i.useMemo(()=>$0({diagnostics:u,loading:f,refreshing:l,error:n}),[u,f,l,n]),h=i.useMemo(()=>new Map(t.map(_=>[_.sessionId||_.id,_])),[t]),p=i.useCallback(async()=>{if(e){d(!0);try{const _=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Si}),T=ja(_);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");b(T.diagnostics||T.result||null),a("")}catch(_){const T=_ instanceof Error?_.message:"Could not load hosted runtime diagnostics";a(T)}finally{d(!1)}}},[b,e,r]);i.useEffect(()=>{!e||u||f||l||p()},[u,f,e,p,l]);const g=i.useCallback(async(_,T)=>{const F=`${_}:${T.sessionId}`;if(!(_==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
90
- This will terminate the hosted runtime.`))){c(F);try{const H=await r(e,_,{sessionId:T.sessionId}),R=ja(H);if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Session host action failed");const I=_==="session_host_resume_session"?"resumed":_==="session_host_restart_session"?"restarted":"stopped";nt.showToast(`Session host ${I}: ${T.displayName}`,"success"),await p()}catch(H){const R=H instanceof Error?H.message:"Session host action failed";nt.showToast(R,"warning"),a(R)}finally{c(H=>H===F?null:H)}}},[e,p,r]),y=i.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
91
- The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const T=await r(e,"session_host_prune_duplicate_sessions",{}),F=ja(T);if(!(F!=null&&F.success))throw new Error((F==null?void 0:F.error)||"Duplicate prune failed");const H=F.result||{},R=Array.isArray(H.prunedSessionIds)?H.prunedSessionIds.length:0,I=typeof H.duplicateGroupCount=="number"?H.duplicateGroupCount:0;nt.showToast(`Pruned ${R} duplicate runtime(s) across ${I} group(s)`,"success"),await p()}catch(T){const F=T instanceof Error?T.message:"Duplicate prune failed";nt.showToast(F,"warning"),a(F)}finally{c(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,p,r]),x=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((_,T)=>(T.lastActivityAt||0)-(_.lastActivityAt||0)),[u==null?void 0:u.sessions]),C=i.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:B0(x),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,x]),S=C.liveRuntimes,w=C.recoverySnapshots,M=C.inactiveRecords,L=i.useMemo(()=>W0(S),[S]),j=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),k=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(_=>_.level==="warn"||_.level==="error")||null,[u==null?void 0:u.recentLogs]),B=(_,T)=>{var U;const F=o===`session_host_resume_session:${_.sessionId}`,H=o===`session_host_restart_session:${_.sessionId}`,R=o===`session_host_stop_session:${_.sessionId}`,I=zd(_.meta),N=h.get(_.sessionId),K=_.attachedClients.length===1?"1 client":`${_.attachedClients.length} clients`,P=T==="recovery"?"Recover":"Resume",E=O0(T);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:_.displayName||(N==null?void 0:N.cliName)||_.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${F0(_.lifecycle)}`,children:_.lifecycle}),I&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:I})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:_.workspaceLabel||(N==null?void 0:N.runtimeWorkspaceLabel)||_.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:_.runtimeKey}),_.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",_.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((U=_.writeOwner)==null?void 0:U.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:K0(_.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($c,{size:11})," ",K]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",kc(_.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:[T==="recovery"&&(_.lifecycle==="interrupted"||_.lifecycle==="failed"||_.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{g("session_host_resume_session",_)},children:F?`${P}ing…`:P}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{g("session_host_restart_session",_)},children:H?"Restarting…":"Restart"}),T==="live"&&(_.lifecycle==="running"||_.lifecycle==="starting"||_.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{g("session_host_stop_session",_)},children:R?"Stopping…":"Stop"})]})]})},_.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(Jt,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:$h()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[L>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${L})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${v.toneClass}`,children:v.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:f||l,children:[s.jsx(wr,{size:13}),f||l?"Refreshing…":"Refresh"]})]})]}),n&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(gr,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:w.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:kc(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:ka(u.hostStartedAt)})]})]}),k&&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(gr,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:k.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[ka(k.timestamp),k.sessionId?` · ${k.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(io,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:wa("live")}),S.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:S.map(_=>B(_,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Jt,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:wa("recovery")}),w.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:w.map(_=>B(_,"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:wa("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:M.map(_=>B(_,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),j.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:j.map(_=>{var F;const T=x.find(H=>H.sessionId===_.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(T==null?void 0:T.displayName)||((F=h.get(_.sessionId))==null?void 0:F.cliName)||_.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[_.action,_.lifecycle?` · ${_.lifecycle}`:"",_.detail?` · ${_.detail}`:"",_.error?` · ${_.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${_.success===!1?"text-red-300":"text-text-secondary"}`,children:ka(_.timestamp)})]},`${_.sessionId}:${_.timestamp}:${_.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function U0({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(o=>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:o.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:o.label||o.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:o.path})]},o.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 Sa({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function Na({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function z0({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:c}){const l=n.slice(0,6),d=r.slice(0,4),m="0.9.81",u=ld(e),f=Cs(e,m),b=pr(e,f),v=u==="preview"?"Update to preview":"Update daemon";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(Sa,{icon:s.jsx(zt,{size:13}),children:"Current Chats"}),s.jsx(Na,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const p=qa(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:ct(h)}),p>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:In(p)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:gs(h)})]},h.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Sa,{icon:s.jsx(Fc,{size:13}),children:"Recent Launches"}),s.jsx(Na,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(h=>{const{metaText:p,updatedLabel:g}=vd(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:()=>o(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}),g&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:g})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:p})]},h.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Sa,{icon:s.jsx(gr,{size:13}),children:"Daemon Update"}),s.jsx(Na,{className:"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:b?"Daemon update required":"Version mismatch detected"}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[b?"This machine is on an incompatible daemon version. Update it before starting more sessions.":u==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",f&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",f,u?` (${u})`:""]})]}),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(wr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:v})]})]})})]})]})}function V0(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function G0({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:o,onCustomPathChange:c,onOpenBrowseDialog:l}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,onChange:d=>{const m=d.target.value;if(o(m),m==="__custom__"&&a){l();return}m!=="__custom__"&&c("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(e.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(d=>s.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",Mn(d.path,d.label)]},d.id)),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),t==="__custom__"&&(a?s.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:l,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:d=>c(d.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:t==="__custom__"?r?s.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:t===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const q0={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 qr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ca({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const f=Ws(),{handleLaunchIde:b,handleStopCli:v,handleRestartIde:h,handleStopIde:p,handleDetectIdes:g,launchingIde:y,launchingAgentType:x,addLog:C}=c,[S,w]=i.useState(null),M=i.useCallback(A=>{A&&f(Zt(A))},[f]),L=q0[e],j=e==="ide",k=e==="acp",B=i.useMemo(()=>n.filter(A=>ys(A,e)),[e,n]),_=i.useMemo(()=>new Map(B.map(A=>[A.type,A.displayName||A.type])),[B]),[T,F]=i.useState(""),[H,R]=i.useState(""),[I,N]=i.useState([]),[K,P]=i.useState(""),[E,U]=i.useState(""),[ee,ye]=i.useState([]),[le,Q]=i.useState(!1),[xe,we]=i.useState(!1),[be,X]=i.useState(""),[ue,fe]=i.useState(!1),[ve,pe]=i.useState(()=>jt()),[Se,Z]=i.useState(null),[de,oe]=i.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[me,ie]=i.useState(m||""),[D,z]=i.useState([]),[ce,re]=i.useState(!1),[G,je]=i.useState(""),[ge,Ae]=i.useState([]),[Me,O]=i.useState(!1),[Ne,Re]=i.useState(""),Fe=i.useRef(null),[He,Ge]=i.useState(null),qe=i.useRef("__home__"),[et,dt]=i.useState("__home__"),[pt,bt]=i.useState(!1),Ce=i.useRef(0),Ue=D.filter(A=>!a.some(Y=>Y.type===A&&xt(Y.status)!=="stopped")),Qe=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!de&&oe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(m){oe("__custom__"),ie(m);return}d&&(oe(d),ie(""))},[d,m]),i.useEffect(()=>{j||T&&(B.some(A=>A.type===T)||(F(""),U("")))},[B,j,T]);const ze=(()=>{if(de==="__custom__")return me.trim();if(!de)return"";const A=(t.workspaces||[]).find(Y=>Y.id===de);return(A==null?void 0:A.path)||""})(),rt=i.useCallback(A=>{const Y=Qe.current[A];Y&&(clearTimeout(Y),delete Qe.current[A]),z(he=>he.includes(A)?he.filter($e=>$e!==A):he)},[]),W=i.useRef(new Set),V=i.useCallback(async A=>{if(l){O(!0),Re("");try{const Y=await En(l,r,A);je(Y.path),ie(Y.path),Ae(Y.directories)}catch(Y){Re(Y instanceof Error?Y.message:"Could not load folder")}finally{O(!1)}}},[r,l]),J=i.useCallback(()=>{if(!l)return;oe("__custom__"),re(!0);const A=a.map(he=>he.workspace),Y=Dn(t.platform,Pn(me.trim(),ze,m,A,t.defaultWorkspacePath,(t.workspaces||[]).map(he=>he.path)));V(Y)},[me,m,V,t.defaultWorkspacePath,t.platform,t.workspaces,a,ze,l]),ne=i.useCallback(A=>{const Y=String(A.workspace||"").trim();if(!Y)return;const he=(t.workspaces||[]).find($e=>qr($e.path)===qr(Y));if(he){oe(he.id),ie("");return}oe("__custom__"),ie(Y)},[t.workspaces]),$=i.useCallback(A=>{const Y=String(A.workspace||"").trim();if(!Y)return{workspaceId:null,workspacePath:"",useHome:!0};const he=(t.workspaces||[]).find($e=>qr($e.path)===qr(Y));return he?{workspaceId:he.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Y,useHome:!1}},[t.workspaces]),q=i.useCallback(async A=>{if(!l||!A||e!=="cli"){ye([]),Q(!1),we(!1),X("");return}const Y=Ce.current+1;Ce.current=Y,Q(!0),X("");try{const he=await l(r,"list_saved_sessions",{providerType:A,kind:"cli",limit:30});if(Ce.current!==Y)return;const $e=(he==null?void 0:he.result)??he;ye(Array.isArray($e==null?void 0:$e.sessions)?$e.sessions:[])}catch(he){if(Ce.current!==Y)return;ye([]),X(he instanceof Error?he.message:"Could not load saved sessions")}finally{Ce.current===Y&&(Q(!1),we(!0))}},[e,r,l]),se=i.useMemo(()=>{if(e!=="cli"||!T)return null;const A=_.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:E||void 0,transport:"pty",mode:"chat",agentName:A,agentType:T,status:"idle",title:A,messages:[],ideType:T,workspaceName:ze,workspacePath:ze,displayPrimary:A,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,_,ze,E,T]),ae=i.useCallback(A=>{if(e==="ide"||!A){N([]);return}N(Ja(r,A))},[e,r]),ke=i.useCallback((A,Y)=>{e==="ide"||!A||(Jg(r,A,Y),N(Ja(r,A)))},[e,r]);i.useEffect(()=>{Ce.current+=1,U(""),ae(T),we(!1),ye([]),X(""),Q(!1)},[e,ae,q,T]);const _e=i.useMemo(()=>ee.find(A=>A.providerSessionId===E)||null,[ee,E]);i.useEffect(()=>{if(!E)return;const A=ee.find(Y=>Y.providerSessionId===E);A!=null&&A.canResume||U("")},[ee,E]);const De=i.useCallback((A,Y)=>{Fe.current=Y,qe.current=A.selectedWorkspaceKey||"__home__",dt(A.selectedWorkspaceKey||"__home__"),Ge(A)},[]),Te=i.useCallback(()=>{Fe.current&&(bt(!0),Fe.current().finally(()=>{Fe.current=null,bt(!1),Ge(null)}))},[]),Ee=i.useCallback(A=>{if(!A)return;z(he=>he.includes(A)?he:[...he,A]);const Y=Qe.current[A];Y&&clearTimeout(Y),Qe.current[A]=setTimeout(()=>{z(he=>he.includes(A)?he.filter($e=>$e!==A):he),delete Qe.current[A]},2e4)},[]);i.useEffect(()=>{for(const Y of a)xt(Y.status)!=="stopped"&&(D.includes(Y.type)&&!W.current.has(Y.type)&&(W.current.add(Y.type),C("info",`${_.get(Y.type)||Y.type} launched`,!0)),rt(Y.type));const A=new Set(a.filter(Y=>xt(Y.status)!=="stopped").map(Y=>Y.type));W.current.forEach(Y=>{!D.includes(Y)&&!A.has(Y)&&W.current.delete(Y)})},[C,rt,a,D,_]),i.useEffect(()=>()=>{Object.values(Qe.current).forEach(clearTimeout),Qe.current={}},[]);const[Oe,Ie]=i.useState({}),[Ye,Je]=i.useState(null);i.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const Y=await l(r,"get_ide_extensions",{}),he=(Y==null?void 0:Y.result)||Y;he!=null&&he.success&&(he!=null&&he.ideExtensions)&&Ie(he.ideExtensions)}catch{}})()},[j,r,l]);const ft=A=>j?ot(A.type):e==="cli"?A.cliName:A.acpName,ht=j?t.detectedIdes||[]:[],it=i.useCallback(async A=>{const Y=(A==null?void 0:A.type)||T,he=(A==null?void 0:A.workspacePath)??ze;if(j){await b(Y,he?{workspace:he}:void 0)&&Ee(Y);return}const $e=await c.runLaunchCliCore({cliType:Y,dir:A!=null&&A.workspaceId?void 0:he||void 0,workspaceId:(A==null?void 0:A.workspaceId)||void 0,useHome:(A==null?void 0:A.useHome)||!(A!=null&&A.workspaceId)&&!he,argsStr:(A==null?void 0:A.argsStr)??(H||void 0),model:(A==null?void 0:A.model)??(k&&K||void 0),resumeSessionId:(A==null?void 0:A.resumeSessionId)||!k&&e==="cli"&&Y===T&&E||void 0});if($e.success||$e.pending){const Le=(A==null?void 0:A.argsStr)??H;!j&&(Le!=null&&Le.trim())&&(Pd(r,Y,Le),ae(Y)),Ee(Y),$e.success&&$e.sessionId&&M($e.sessionId)}},[c,b,k,j,H,K,ae,Ee,r,M,ze,E,T]),ut=_l(j?"ide":k?"acp":"cli",!j&&!k&&!!E),We=Pl(j?"ide":k?"acp":"cli",!j&&!k&&!!E),Et=()=>{var Le;const A=j?ot(T):_.get(T)||T,Y=!j&&!k&&!!E,{options:he,selectedKey:$e}=fs({machine:t,currentWorkspaceId:de&&de!=="__custom__"?de:null,currentWorkspacePath:ze});De({title:Y?Io(A):ls("start-fresh",A),description:Y?To():ds("start-fresh"),confirmLabel:ut,busyLabel:We,workspaceOptions:he,selectedWorkspaceKey:$e,details:[{label:"Mode",value:L.label},{label:"Provider",value:A},...!j&&e==="cli"&&E?[{label:"Resume",value:((Le=ee.find(Be=>Be.providerSessionId===E))==null?void 0:Le.title)||E}]:[],...!j&&H.trim()?[{label:"Arguments",value:H.trim()}]:[],...k&&K.trim()?[{label:"Model",value:K.trim()}]:[]]},async()=>{const Be=he.find(tt=>tt.key===qe.current);Be!=null&&Be.workspaceId?(oe(Be.workspaceId),ie("")):Be!=null&&Be.workspacePath?(oe("__custom__"),ie(Be.workspacePath)):(oe(""),ie("")),await it({workspaceId:(Be==null?void 0:Be.workspaceId)??null,workspacePath:(Be==null?void 0:Be.workspacePath)??"",useHome:!(Be!=null&&Be.workspaceId)&&!(Be!=null&&Be.workspacePath)})})},te=A=>{j?p(A):v(A.type,A.workspace,A.id)},Pe=i.useCallback(async(A,Y,he=!1)=>{if(A.mode===Y){he&&A.sessionId&&M(A.sessionId);return}if(!l||!A.sessionId){he&&A.sessionId&&M(A.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:A.sessionId,cliType:A.type,mode:Y}),he&&M(A.sessionId)}catch($e){const Le=ed($e);Zl($e)?console.warn(Le?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",$e instanceof Error?$e.message:String($e)):console.error("Failed to switch CLI view mode:",$e)}},[r,M,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${L.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 ",L.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?ht.length>0?ht.map(A=>{const Y=a.find(tt=>(tt.type||"").toLowerCase()===(A.type||"").toLowerCase()&&xt(tt.status)!=="stopped"),he=A.running||!!Y,$e=!!Y&&Y.cdpConnected,Le=D.includes(A.type||A.id||""),Be=T===(A.type||"");return s.jsxs("button",{onClick:()=>{if($e&&Y){const tt=Y.sessionId;tt?f(Zt(tt),{state:{openRemoteForTabKey:tt}}):f("/dashboard",{state:{openRemoteForTabKey:Y.id}});return}Le||F(tt=>tt===(A.type||"")?"":A.type||"")},disabled:!!y||Le,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${$e?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Be?"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:y&&y!==A.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:o(A.type)}),he&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${$e?"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:A.name||ot(A.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${$e?"text-green-400":Le?"text-orange-400":Be?"text-accent-primary":"text-text-muted"}`,children:$e?"Open Session":Le?"Starting...":Be?"Configure":"Select"})]})]},A.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:g,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(om,{size:14})," Scan System"]})]}):B.length>0?B.map(A=>{const Y=T===A.type,he=D.includes(A.type),Le=!!a.find(Be=>Be.type===A.type&&xt(Be.status)!=="stopped");return s.jsxs("button",{onClick:()=>F(Be=>Be===A.type?"":A.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Y?"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:A.icon}),Le&&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:A.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${he?"text-orange-400":Y?"text-accent-primary":"text-text-muted"}`,children:he?"Starting...":Y?"Configure":"Select"})]})]},A.type)}):s.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),T&&(j?ht.find(A=>A.type===T):B.find(A=>A.type===T))&&s.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:j?ot(T):_.get(T)||T})]}),s.jsx(G0,{machine:t,selectedWorkspace:de,resolvedWorkspacePath:ze,customPath:me,canBrowse:!!l,onWorkspaceChange:oe,onCustomPathChange:ie,onOpenBrowseDialog:J}),!j&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!k&&e==="cli"&&s.jsx(Ed,{busy:!!x||!!y||D.includes(T),savedSessionsLoading:le,savedSessionsError:be,savedSessionsLoaded:xe,savedSessionsCount:ee.length,selectedSession:_e,onRefresh:()=>void q(T),onOpenHistory:()=>{T&&(fe(!0),Dd({hasLoadedInitialResults:xe,isLoading:le})&&q(T))},onClearSelection:()=>U("")}),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:K,onChange:A=>P(A.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:A=>R(A.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"}),I.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:I.map(A=>s.jsxs("div",{className:"inline-flex max-w-full items-stretch overflow-hidden rounded-md border border-[#ffffff1a] bg-bg-tertiary text-xs text-text-secondary transition-colors hover:border-accent-primary/40 hover:text-text-primary",title:A,children:[s.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>R(A),children:A}),s.jsx("button",{type:"button",className:"flex items-center justify-center border-l border-[#ffffff1a] px-1.5 text-text-muted transition-colors hover:bg-status-error/10 hover:text-status-error focus:outline-none focus:ring-1 focus:ring-status-error/50",onClick:()=>ke(T,A),"aria-label":`Remove startup arguments: ${A}`,title:"Remove startup arguments",children:s.jsx(gt,{size:12})})]},A))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:Et,disabled:!!x||!!y||D.includes(T),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:x===T||y===T?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+D.filter(A=>!a.some(Y=>Y.type===A&&xt(Y.status)!=="stopped")).length,")"]}),a.length===0&&Ue.length===0?s.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",L.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ue.map(A=>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:o(A)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?ot(A):_.get(A)||A}),s.jsx("div",{className:"text-[11px] text-text-muted",children:x===A?"Launching process...":"Waiting for process and session to register..."})]})]}),s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${A}`)),a.map(A=>{const Y=j?A:null,he=!j&&!k?A:null,$e=xt(A.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:o(A.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[ft(A),(Y==null?void 0:Y.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Y.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[s.jsx("span",{className:"truncate",children:A.workspace||"—"}),u&&A.git&&A.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:Le=>{Le.stopPropagation(),u(A.daemonId??r,A.workspace)},children:s.jsx(Bs,{git:A.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Bs,{git:A.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(he==null?void 0:he.mode)&&s.jsx("span",{className:he.mode==="chat"?"text-violet-400":"text-text-secondary",children:he.mode==="chat"?"Chat view":"Terminal view"})]}),he&&(he.runtimeKey||he.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[he.runtimeKey&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),s.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",he.runtimeKey]}),s.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Le;(Le=navigator.clipboard)==null||Le.writeText(`adhdev attach ${he.runtimeKey}`),w(he.runtimeKey||null),window.setTimeout(()=>{w(Be=>Be===he.runtimeKey?null:Be)},1200)},children:S===he.runtimeKey?"Copied":"Copy"})]}),he.runtimeWriteOwner&&s.jsx("span",{style:{color:he.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:he.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:V0(he.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${$e==="stopped"?"bg-red-500/[0.08] text-red-500":$e==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:$e}),j&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Le=A.sessionId;if(Le){f(Zt(Le),{state:{openRemoteForTabKey:Le}});return}f("/dashboard",{state:{openRemoteForTabKey:A.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(It,{size:13})}),s.jsx("button",{onClick:()=>{const Le=A.workspace||"",{options:Be,selectedKey:tt}=fs({machine:t,currentWorkspacePath:Le});De({title:ls("restart-ide",ot(A.type)),description:ds("restart-ide"),confirmLabel:Os("restart-ide"),busyLabel:Ks("restart-ide"),workspaceOptions:Be,selectedWorkspaceKey:tt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ot(A.type)}]},async()=>{const Nt=Be.find(Gt=>Gt.key===qe.current),mt=(Nt==null?void 0:Nt.workspacePath)??"";if(mt&&mt!==Le){await it({type:A.type,workspacePath:mt});return}await h(A)})},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(wr,{size:14})})]}),k&&s.jsx("button",{onClick:()=>{const Le=A.sessionId;Le&&M(Le)},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:!A.sessionId,children:s.jsx(zt,{size:14})}),he&&$e!=="stopped"&&s.jsxs(s.Fragment,{children:[he.mode&&s.jsx(So,{mode:he.mode,onChange:Le=>void Pe(he,Le,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Le=A.sessionId;Le&&M(Le)},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:!A.sessionId,children:he.mode==="chat"?s.jsx(zt,{size:14}):s.jsx(It,{size:13})})]}),$e==="stopped"?s.jsx("button",{onClick:()=>{const Le=A.workspace||"",Be=j?ot(A.type):ft(A),{options:tt,selectedKey:Nt}=fs({machine:t,currentWorkspacePath:Le});De({title:ls("restart-stopped",Be),description:ds("restart-stopped"),confirmLabel:Os("restart-stopped"),busyLabel:Ks("restart-stopped"),workspaceOptions:tt,selectedWorkspaceKey:Nt,details:[{label:"Mode",value:L.label},{label:"Provider",value:Be}]},async()=>{const mt=tt.find(Gt=>Gt.key===qe.current);await it({type:A.type,workspaceId:(mt==null?void 0:mt.workspaceId)??null,workspacePath:(mt==null?void 0:mt.workspacePath)??"",useHome:!(mt!=null&&mt.workspaceId)&&!(mt!=null&&mt.workspacePath)})})},disabled:D.includes(A.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:D.includes(A.type)?"⏳":s.jsx(co,{size:14})}):s.jsx("button",{onClick:()=>te(A),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(gt,{size:14})})]})]}),Y&&Y.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Y.aiAgents.map(Le=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${pn(Le.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Le.name," · ",xt(Le.status)]},Le.id))}),Y&&(Oe[Y.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:(Oe[Y.type]||[]).map(Le=>s.jsxs("button",{disabled:Ye===`${Y.type}.${Le.type}`,onClick:async()=>{const Be=`${Y.type}.${Le.type}`;Je(Be);try{await l(r,"set_ide_extension",{ideType:Y.type,extensionType:Le.type,enabled:!Le.enabled}),Ie(tt=>({...tt,[Y.type]:(tt[Y.type]||[]).map(Nt=>Nt.type===Le.type?{...Nt,enabled:!Nt.enabled}:Nt)}))}catch(tt){console.error("Extension toggle failed:",tt)}finally{Je(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 ${Le.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 ${Le.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Le.name,s.jsx("span",{className:"text-[9px] font-normal",children:Le.enabled?"ON":"OFF"})]},Le.type))})]})]},A.id)})]}),ce&&l&&s.jsx($n,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:G,directories:ge,busy:Me,error:Ne,confirmLabel:"Use this folder",onClose:()=>re(!1),onNavigate:A=>{V(A)},onConfirm:A=>{ie(A),oe("__custom__"),re(!1)}}),He&&s.jsx(Bo,{title:He.title,description:He.description,details:He.details,workspaceOptions:He.workspaceOptions,selectedWorkspaceKey:et,onWorkspaceChange:A=>{qe.current=A,dt(A)},confirmLabel:He.confirmLabel,busyLabel:He.busyLabel,busy:pt,onConfirm:Te,onCancel:()=>{Fe.current=null,Ge(null)}}),ue&&se&&s.jsx(Mo,{activeConv:se,ides:[],isCreatingChat:!1,isRefreshingHistory:le,savedSessions:ee,isSavedSessionsLoading:le,isResumingSavedSessionId:Se,savedHistoryFilters:ve,missingWorkspaceResumePath:ze||null,onSavedHistoryFiltersChange:pe,onClose:()=>fe(!1),onNewChat:()=>{U(""),fe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{q(T)},onResumeSavedSession:A=>{if(!A.canResume||Se)return;const Y=$(A);U(A.providerSessionId),ne(A),Z(A.providerSessionId),fe(!1),it({type:A.providerType,workspaceId:Y.workspaceId,workspacePath:Y.workspacePath,useHome:Y.useHome,resumeSessionId:A.providerSessionId}).finally(()=>{Z(he=>he===A.providerSessionId?null:he)})}})]})}const Sc=[{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 Y0({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:c,getIcon:l,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:f,onOpenGitDialog:b}){var g;const[v,h]=i.useState(d);i.useEffect(()=>{h(d)},[d]);const p=i.useMemo(()=>({ide:n.length,cli:a.length,acp:o.length}),[n.length,a.length,o.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:Sc.map(y=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${v===y.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>h(y.id),children:[s.jsx("span",{children:y.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${v===y.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:p[y.id]})]},y.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(g=Sc.find(y=>y.id===v))==null?void 0:g.helper})]}),v==="ide"&&s.jsx(Ca,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:b}),v==="cli"&&s.jsx(Ca,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:b}),v==="acp"&&s.jsx(Ca,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:b})]})}function X0({onNicknameSynced:e}={}){var ie,D,z,ce,re,G,je,ge,Ae,Me;const{id:t}=Au(),r=Ws(),n=so(),{sendCommand:a}=yt(),o=Sr(),c=ql(),l=Nl(),d=l.ides||[],m=l.initialLoaded??!0,u=d.find(O=>O.id===t&&O.type==="adhdev-daemon"),f=d.some(O=>O.type==="adhdev-daemon"),b=t?(ie=l.connectionRetryStatuses)==null?void 0:ie[t]:void 0,v=!!(b!=null&&b.blocked),[h,p]=i.useState("workspace"),[g,y]=i.useState(null),x=i.useCallback((O,Ne)=>{y({daemonId:O,workspace:Ne})},[]),[C,S]=i.useState("ide"),w=i.useRef(null),[M,L]=i.useState(null),j=i.useRef("__home__"),[k,B]=i.useState("__home__"),[_,T]=i.useState(!1),F=i.useRef(null);i.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,u,t]),i.useEffect(()=>{if(!t||!u||h!=="overview")return;const O=u.machine;(typeof(O==null?void 0:O.cpus)!="number"||typeof(O==null?void 0:O.totalMem)!="number"||typeof(O==null?void 0:O.arch)!="string"||typeof(O==null?void 0:O.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[h,c,u,t]),Dx(t&&h==="overview"?[t]:[],{enabled:h==="overview",intervalMs:Tf});const H=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},R=zy({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:F});i.useEffect(()=>nt.onToast(Ne=>{l.setToasts(Fe=>{if(Fe.some(qe=>qe.message===Ne.message&&Ne.timestamp-qe.timestamp<3e3))return Fe;const Ge={id:Ne.id,message:Ne.message,type:Ne.type,timestamp:Ne.timestamp,targetKey:Ne.targetKey,actions:Ne.actions};return[...Fe.slice(-4),Ge]});const Re=Ne.duration||5e3;setTimeout(()=>l.setToasts(Fe=>Fe.filter(He=>He.id!==Ne.id)),Re)}),[l]);const I=(u==null?void 0:u.availableProviders)||[],N={};for(const O of I)N[O.type]=O.icon;const K=O=>N[O]||"",P=u?{id:u.id,hostname:Zc(u,{fallbackId:u.id}),platform:((D=u.machine)==null?void 0:D.platform)||"unknown",arch:((z=u.machine)==null?void 0:z.arch)||"",cpus:((ce=u.machine)==null?void 0:ce.cpus)||0,totalMem:((re=u.machine)==null?void 0:re.totalMem)||0,freeMem:(G=u.machine)==null?void 0:G.freeMem,availableMem:(je=u.machine)==null?void 0:je.availableMem,loadavg:(ge=u.machine)==null?void 0:ge.loadavg,uptime:(Ae=u.machine)==null?void 0:Ae.uptime,release:((Me=u.machine)==null?void 0:Me.release)||"",cdpConnected:!!u.cdpConnected,machineNickname:u.machineNickname||null,p2p:u.p2p?{screenshotActive:!1,...u.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:u.detectedIdes||[],workspaces:u.workspaces||[],defaultWorkspaceId:u.defaultWorkspaceId??u.activeWorkspaceId??null,defaultWorkspacePath:u.defaultWorkspacePath??u.activeWorkspacePath??null}:null,E=d.filter(O=>O.daemonId===t&&O.type!=="adhdev-daemon").filter(O=>!yr(O)&&!As(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,version:O.version||"",instanceId:O.instanceId||"",status:O.status,workspace:O.workspace||null,terminals:O.terminals||0,aiAgents:yp(O.aiAgents||(O.agents||[]).map(Ne=>({id:Ne.name,name:Ne.name,status:Ne.status,version:Ne.version}))),activeChat:O.activeChat||null,chats:O.chats||[],childSessions:O.childSessions||[],cdpConnected:O.cdpConnected||!1,daemonId:t,lastMessageAt:O.lastMessageAt})),U=d.filter(O=>O.daemonId===t&&yr(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,cliName:O.cliName||O.type,status:O.status,workspace:O.workspace||"",activeChat:O.activeChat||null,providerSessionId:O.providerSessionId,mode:O.mode,runtimeKey:O.runtimeKey,runtimeDisplayName:O.runtimeDisplayName,runtimeWorkspaceLabel:O.runtimeWorkspaceLabel,runtimeWriteOwner:O.runtimeWriteOwner||null,runtimeAttachedClients:O.runtimeAttachedClients||[],daemonId:t,lastMessageAt:O.lastMessageAt})),ee=d.filter(O=>O.daemonId===t&&As(O)).map(O=>({id:O.id,sessionId:O.sessionId,type:O.type,acpName:O.cliName||O.type,status:O.status,workspace:O.workspace||"",activeChat:O.activeChat||null,providerSessionId:O.providerSessionId,daemonId:t,lastMessageAt:O.lastMessageAt})),ye=u?Ct(u,{fallbackId:t}):"",le="workspace",Q=n.state,xe=Q==null?void 0:Q.initialMachineTab,we=Q==null?void 0:Q.initialWorkspaceCategory,be=Q==null?void 0:Q.initialWorkspaceId,X=Q==null?void 0:Q.initialWorkspacePath,ue=xe==="ides"||xe==="clis"||xe==="acps"?"workspace":xe||le,fe=xe==="ides"?"ide":xe==="clis"?"cli":xe==="acps"?"acp":we,ve=[...E.map(O=>{var Ne;return{id:`ide:${O.type}:${O.workspace||""}`,label:((Ne=O.activeChat)==null?void 0:Ne.title)||O.type,kind:"ide",providerType:O.type,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}}),...U.map(O=>{var Ne;return{id:`cli:${O.type}:${O.workspace||""}`,label:((Ne=O.activeChat)==null?void 0:Ne.title)||O.cliName,kind:"cli",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}}),...ee.map(O=>{var Ne;return{id:`acp:${O.type}:${O.workspace||""}`,label:((Ne=O.activeChat)==null?void 0:Ne.title)||O.acpName,kind:"acp",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:bs(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}})].sort((O,Ne)=>(Ne.lastLaunchedAt||0)-(O.lastLaunchedAt||0)),pe=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(O=>({id:O.id,label:O.title||O.providerName||O.providerType,kind:O.kind,providerType:O.providerType,providerSessionId:O.providerSessionId,subtitle:bs(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace,summaryMetadata:O.summaryMetadata,lastLaunchedAt:O.lastLaunchedAt})):ve,Se=i.useMemo(()=>{var Ne;const O=((Ne=l.connectionStates)==null?void 0:Ne[t||""])||void 0;return d.filter(Re=>Re.daemonId===t&&Re.type!=="adhdev-daemon").flatMap(Re=>Ao(Re,{connectionStates:t&&O?{[t]:O}:void 0,defaultConnectionState:O})).filter(Re=>!(Re.transport==="pty"&&Re.mode==="terminal")).sort((Re,Fe)=>qa(Fe)-qa(Re))},[d,l.connectionStates,t]),Z=i.useCallback(O=>{const Ne=pd(O);Ne&&r(Zt(Ne))},[r]),de=i.useCallback(()=>{w.current&&(T(!0),w.current().finally(()=>{w.current=null,T(!1),L(null)}))},[]),oe=i.useCallback(O=>{if(!P)return;const{options:Ne,selectedKey:Re}=fs({machine:P,currentWorkspacePath:O.workspace}),Fe=async()=>{S(O.kind),p("workspace")};w.current=async()=>{const He=Ne.find(et=>et.key===j.current),Ge=(He==null?void 0:He.workspacePath)??null,qe=(He==null?void 0:He.workspaceId)??null;if(O.kind==="ide"&&O.providerType){await R.handleLaunchIde(O.providerType,Ge?{workspace:Ge}:void 0);return}if((O.kind==="cli"||O.kind==="acp")&&O.providerType){await R.runLaunchCliCore({cliType:O.providerType,dir:qe?void 0:Ge||"",workspaceId:qe||void 0,model:O.kind==="acp"&&tl(O.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:O.providerSessionId});return}await Fe()},j.current=Re,B(Re),L({title:O.kind==="ide"?ls("restart-ide",O.label):O.providerSessionId?Io(O.label):ls("start-fresh",O.label),description:O.kind==="ide"?ds("restart-ide"):O.providerSessionId?To():ds("start-fresh"),confirmLabel:O.kind==="ide"?Os("restart-ide"):O.providerSessionId?gn(!0):Os("start-fresh"),busyLabel:O.kind==="ide"?Ks("restart-ide"):O.providerSessionId?No(!0):Ks("start-fresh"),workspaceOptions:Ne,details:[{label:"Mode",value:O.kind.toUpperCase()},...O.providerType?[{label:"Provider",value:O.providerType}]:[]]})},[R,P]);if(i.useEffect(()=>{p(ue)},[le,ue,t]),i.useEffect(()=>{fe&&S(fe)},[fe,t]),!P)return m?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:H,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const me=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(It,{size:14})," Workspace"]}),count:E.length+U.length+ee.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(cm,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(nm,{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:H,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:[R.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:R.nicknameInput,onChange:O=>R.setNicknameInput(O.target.value),onKeyDown:O=>{O.key==="Enter"&&R.handleSaveNickname(),O.key==="Escape"&&R.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:R.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:()=>R.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:()=>{R.setEditingNickname(!0),R.setNicknameInput(P.machineNickname||"")},title:"Click to set nickname",children:ye}),v?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),l.retryConnection&&t&&s.jsx("button",{onClick:()=>l.retryConnection(t),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[P.platform," · ",P.arch]}),s.jsxs("span",{children:[P.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),P.p2p.available&&s.jsxs("span",{children:["P2P ",P.p2p.state==="connected"?"connected":P.p2p.state]}),P.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:P.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:me.map(O=>s.jsxs("button",{onClick:()=>p(O.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===O.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[O.label,O.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===O.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:O.count})]},O.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[h==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(z0,{machineEntry:u,providers:I,recentLaunches:pe,currentConversations:Se,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",dd(u))}catch{}},onOpenRecent:oe,onOpenConversation:Z}),s.jsx(Y0,{machine:P,machineId:t,providers:I,ideSessions:E,cliSessions:U,acpSessions:ee,actions:R,getIcon:K,initialCategory:C,initialWorkspaceId:be,initialWorkspacePath:X,sendDaemonCommand:a,onOpenGitDialog:x})]}),h==="providers"&&s.jsx(t0,{machineId:t,providers:I,sendDaemonCommand:a}),h==="overview"&&s.jsx(Vy,{machineId:t,machine:P,ideSessions:E,cliSessions:U,acpSessions:ee,actions:R,sendDaemonCommand:a}),h==="session-host"&&s.jsx(H0,{machineId:t,cliSessions:U,sendDaemonCommand:a}),h==="logs"&&s.jsx(E0,{machineId:t,sendDaemonCommand:a})]})})}),R.launchPick&&P&&s.jsx(U0,{machine:P,launchPick:R.launchPick,actions:R}),M&&s.jsx(Bo,{title:M.title,description:M.description,details:M.details,workspaceOptions:M.workspaceOptions,selectedWorkspaceKey:k,onWorkspaceChange:O=>{j.current=O,B(O)},confirmLabel:M.confirmLabel,busyLabel:M.busyLabel,busy:_,onConfirm:de,onCancel:()=>{w.current=null,L(null)}}),g&&s.jsx(Hd,{daemonId:g.daemonId,workspace:g.workspace,onClose:()=>y(null)}),s.jsx(Dl,{toasts:l.toasts||[],onDismiss:O=>l.setToasts(Ne=>Ne.filter(Re=>Re.id!==O)),onClickToast:O=>{O.targetKey&&r(Zt(O.targetKey))}}),s.jsx("style",{children:`
92
- @keyframes toast-in {
93
- from { opacity: 0; transform: translateX(40px); }
94
- to { opacity: 1; transform: translateX(0); }
95
- }
96
- `})]})}const Yr=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],J0={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function an(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function Q0(e){const t=an(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"launch not ready unless an explicit provider is selected"}}function Z0(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function ev(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",r=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${r}`}function tv(e,t){return[...Array.isArray(t==null?void 0:t.cliSessions)?t.cliSessions:[],...Array.isArray(t==null?void 0:t.acpSessions)?t.acpSessions:[],...Array.isArray(t==null?void 0:t.sessions)?t.sessions:[]].filter(n=>{var a;return((a=n==null?void 0:n.settings)==null?void 0:a.meshNodeId)===e.id||(n==null?void 0:n.workspace)===e.workspace}).map(n=>{var a;return{id:n.sessionId||n.id||n.instanceId||"unknown",provider:n.providerType||n.cliType||n.acpType||n.type||"unknown",status:n.status||((a=n.activeChat)==null?void 0:a.status)||"unknown"}})}function Ia(e){return{...J0,...(e==null?void 0:e.policy)||{}}}function sv({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const o=a.id.toLowerCase(),c=a.name.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||c.includes("hermes")}),n=md(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(vt,{title:"Hermes MCP Config",description:"Hermes does not auto-import repo-local .mcp.json. Add this YAML under mcp_servers in Hermes config, then start a fresh Hermes session.",children:s.jsx($d,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function rv(){var ie;const{sendCommand:e}=yt(),{ides:t}=es(),r=t.find(D=>D.daemonMode||D.type==="adhdev-daemon"),n=(r==null?void 0:r.id)||"",a=[];let o=[];if(r){const D=r.availableProviders||[];o=Yh(D);for(const z of D)z.category==="cli"&&a.push({id:z.type||z.id,name:z.displayName||z.name||z.type,meshCoordinator:z.meshCoordinator})}const[c,l]=i.useState([]),[d,m]=i.useState(null),[u,f]=i.useState(!0),[b,v]=i.useState(null),[h,p]=i.useState(!1),[g,y]=i.useState(null),[x,C]=i.useState({}),[S,w]=i.useState([]),[M,L]=i.useState(null),[j,k]=i.useState(null),[B,_]=i.useState(!1),[T,F]=i.useState(null),[H,R]=i.useState(null),[I,N]=i.useState(!1),[K,P]=i.useState(""),[E,U]=i.useState(""),[ee,ye]=i.useState(!1),[le,Q]=i.useState(""),[xe,we]=i.useState([]),be=c.find(D=>D.id===d)||null;i.useEffect(()=>{C(Object.fromEntries(((be==null?void 0:be.nodes)||[]).map(D=>[D.id,an(D)])))},[be]),i.useEffect(()=>{const D=Xh(o);ee&&xe.length===0&&D.length>0&&we(D)},[ee,o,xe.length]),i.useEffect(()=>{const D=new Set(((be==null?void 0:be.nodes)||[]).map(z=>z.id));M&&!D.has(M)&&L(null)},[be,M]);const X=i.useCallback(async()=>{if(n){f(!0);try{const D=await e(n,"list_meshes");D!=null&&D.success?(l(D.meshes||[]),v(null)):v((D==null?void 0:D.error)||"Failed to load meshes")}catch(D){v((D==null?void 0:D.message)||"Failed to load meshes")}finally{f(!1)}}},[n,e]),ue=i.useCallback(async D=>{if(!n||!D){w([]);return}try{const z=await e(n,"get_mesh_queue",{meshId:D});z!=null&&z.success?w(Array.isArray(z.queue)?z.queue:[]):w([])}catch{w([])}},[n,e]);i.useEffect(()=>{X()},[X]),i.useEffect(()=>{ue(d)},[ue,d]);async function fe(){if(!(!n||!d))try{_(!0),F(null);const D=await e(n,"mesh_status",{meshId:d});if(D!=null&&D.success){const z=D.status||D.result||D;if(z&&typeof z=="object"){const ce=Bd(z);k(ce)}else F("Invalid mesh_status response format")}else F((D==null?void 0:D.error)||"mesh_status failed")}catch(D){F((D==null?void 0:D.message)||"Failed to load mesh graph")}finally{_(!1)}}i.useEffect(()=>{d&&(k(null),F(null),R(null),fe())},[d]);async function ve(){var D;if(!(!n||!K.trim()))try{const z=await e(n,"create_mesh",{name:K.trim(),repoIdentity:E.trim()||void 0});z!=null&&z.success?(N(!1),P(""),U(""),await X(),m(((D=z.mesh)==null?void 0:D.id)||null)):v((z==null?void 0:z.error)||"Create failed")}catch(z){v((z==null?void 0:z.message)||"Create failed")}}async function pe(D){if(!(!n||!confirm("Delete this mesh?")))try{await e(n,"delete_mesh",{meshId:D}),m(null),await X()}catch(z){v((z==null?void 0:z.message)||"Delete failed")}}async function Se(){if(!(!n||!d||!le.trim()))try{const D=await e(n,"add_mesh_node",{meshId:d,workspace:le.trim(),providerPriority:Ha(xe,o)});D!=null&&D.success?(ye(!1),Q(""),we([]),await X(),await ue(d)):v((D==null?void 0:D.error)||"Add node failed")}catch(D){v((D==null?void 0:D.message)||"Add node failed")}}async function Z(D){var re;if(!n||!d)return;const z=Ia(be),ce=((re=Yr.find(G=>G.value===z.sessionCleanupOnNodeRemove))==null?void 0:re.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
97
-
98
- Node removal cleanup policy: ${ce}`))try{await e(n,"remove_mesh_node",{meshId:d,nodeId:D}),M===D&&L(null),await X(),await ue(d)}catch(G){v((G==null?void 0:G.message)||"Remove node failed")}}async function de(D){if(!n||!d)return;const z={...Ia(be),...D};try{p(!0),v(null);const ce=await e(n,"update_mesh",{meshId:d,policy:z});if((ce==null?void 0:ce.success)===!1){v(ce.error||"Policy update failed");return}await X()}catch(ce){v((ce==null?void 0:ce.message)||"Policy update failed")}finally{p(!1)}}async function oe(D){if(!n||!d)return;const z=Ha(x[D.id]||an(D),o),ce={...D.policy||{}};delete ce.provider_priority,z.length?ce.providerPriority=z:delete ce.providerPriority;try{y(D.id),v(null);const re=await e(n,"update_mesh_node",{meshId:d,nodeId:D.id,policy:ce});if((re==null?void 0:re.success)===!1){v(re.error||"Node policy update failed");return}await X()}catch(re){v((re==null?void 0:re.message)||"Node policy update failed")}finally{y(null)}}if(!n)return s.jsx(mr,{icon:s.jsx(Is,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})});if(!be)return s.jsxs(mr,{icon:s.jsx(Is,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>N(!0),children:"+ Create Mesh"}),children:[b&&s.jsx(Ms,{variant:"error",className:"mb-4",children:b}),I&&s.jsx(vt,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Tt,{label:"Name",children:s.jsx(ta,{value:K,onChange:D=>P(D.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Tt,{label:"Repo Identity (optional)",children:s.jsx(ta,{value:E,onChange:D=>U(D.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:ve,disabled:!K.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>N(!1),children:"Cancel"})]})]})}),u?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):c.length===0?s.jsx(yn,{icon:s.jsx(Is,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:c.map(D=>s.jsxs("button",{className:"text-left w-full p-4 rounded-xl border border-border-subtle bg-bg-panel hover:border-accent-primary/40 transition-colors",onClick:()=>m(D.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:D.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:D.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[D.nodes.length," node(s)"]})]},D.id))})]});const me=Ia(be);return s.jsxs(mr,{icon:s.jsx(Is,{}),title:be.name,subtitle:be.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>pe(be.id),children:"Delete"})]}),children:[b&&s.jsx(Ms,{variant:"error",className:"mb-4",children:b}),s.jsxs(vt,{title:"Policy",description:"Coordinator safety defaults and node-removal session cleanup behavior for this local mesh.",children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[s.jsx(Tt,{label:"Checkpoint before task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:me.requirePreTaskCheckpoint?"yes":"no",onChange:D=>de({requirePreTaskCheckpoint:D.target.value==="yes"}),disabled:h,children:[s.jsx("option",{value:"no",children:"No"}),s.jsx("option",{value:"yes",children:"Yes"})]})}),s.jsx(Tt,{label:"Checkpoint after task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:me.requirePostTaskCheckpoint?"yes":"no",onChange:D=>de({requirePostTaskCheckpoint:D.target.value==="yes"}),disabled:h,children:[s.jsx("option",{value:"yes",children:"Yes"}),s.jsx("option",{value:"no",children:"No"})]})}),s.jsx(Tt,{label:"Push approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:me.requireApprovalForPush?"required":"not_required",onChange:D=>de({requireApprovalForPush:D.target.value==="required"}),disabled:h,children:[s.jsx("option",{value:"required",children:"Require approval before push"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Tt,{label:"Destructive git approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:me.requireApprovalForDestructiveGit?"required":"not_required",onChange:D=>de({requireApprovalForDestructiveGit:D.target.value==="required"}),disabled:h,children:[s.jsx("option",{value:"required",children:"Require approval"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Tt,{label:"Dirty workspace behavior",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:me.dirtyWorkspaceBehavior||"warn",onChange:D=>de({dirtyWorkspaceBehavior:D.target.value}),disabled:h,children:[s.jsx("option",{value:"warn",children:"Warn and continue"}),s.jsx("option",{value:"block",children:"Block task"}),s.jsx("option",{value:"checkpoint_then_continue",children:"Checkpoint then continue"})]})}),s.jsx(Tt,{label:"Max parallel tasks",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:String(me.maxParallelTasks??2),onChange:D=>de({maxParallelTasks:Number(D.target.value)}),disabled:h,children:[1,2,3,4,5,6,7,8].map(D=>s.jsx("option",{value:D,children:D},D))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Tt,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup. Preserve is safest when completed work may need review.",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:me.sessionCleanupOnNodeRemove||"preserve",onChange:D=>de({sessionCleanupOnNodeRemove:D.target.value}),disabled:h,children:Yr.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((ie=Yr.find(D=>D.value===me.sessionCleanupOnNodeRemove))==null?void 0:ie.description)||Yr[0].description})]}),h&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),s.jsxs(vt,{title:"Visualization",description:"Live mesh topology: branches, worktrees, sessions, and orphan detection.",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),"healthy"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-500"}),"dirty"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"}),"error"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-gray-500"}),"offline"]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:fe,disabled:B,children:B?"Loading...":"Refresh Graph"})]}),T&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:T}),j?s.jsxs("div",{className:"flex gap-4",style:{minHeight:420},children:[s.jsx("div",{className:"flex-1 rounded-xl border border-border-subtle bg-bg-secondary overflow-hidden",style:{minHeight:420},children:s.jsx(Fd,{data:j,onNodeClick:D=>R(z=>(z==null?void 0:z.id)===D.id?null:D),selectedNodeId:(H==null?void 0:H.id)||null})}),H&&s.jsx("div",{className:"w-80 shrink-0",children:s.jsx(Od,{node:H,onClose:()=>R(null)})})]}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:B?"Loading graph...":"Refresh the graph to view mesh topology."})]}),s.jsxs(vt,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[s.jsx("div",{className:"flex justify-end mb-3",children:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>ye(!0),children:"+ Add Node"})}),ee&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),s.jsx("button",{onClick:()=>ye(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(gt,{size:16})})]}),s.jsx(Tt,{label:"Workspace Path",children:s.jsx(ta,{value:le,onChange:D=>Q(D.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),s.jsx(Tt,{label:"Provider Priority",hint:"Order used when launching without an explicit provider. Empty means fail closed unless a provider is selected explicitly.",children:s.jsx(Di,{value:xe,availableProviders:o,onChange:we})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:Se,disabled:!le.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>ye(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),be.nodes.length===0?s.jsx(yn,{icon:s.jsx(xs,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:be.nodes.map(D=>{const z=an(D),ce=Q0(D),re=Z0(D,S),G=tv(D,r),je=M===D.id;return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${je?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>L(je?null:D.id),onKeyDown:ge=>{(ge.key==="Enter"||ge.key===" ")&&(ge.preventDefault(),L(je?null:D.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"text-sm font-medium",children:D.workspace.split("/").pop()}),re.length>0&&s.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-orange-500/15 text-orange-300 border border-orange-500/25",children:[re.length," active task",re.length===1?"":"s"]})]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:D.workspace}),s.jsx("div",{className:"mt-3 max-w-2xl",onClick:ge=>ge.stopPropagation(),children:s.jsxs(Tt,{label:"Provider priority",hint:"Used when launches omit an explicit provider. Empty keeps fail-closed behavior until a provider is selected manually.",children:[s.jsx(Di,{value:x[D.id]??z,availableProviders:o,onChange:ge=>C(Ae=>({...Ae,[D.id]:ge})),disabled:g===D.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:ge=>{ge.stopPropagation(),oe(D)},disabled:g===D.id,children:g===D.id?"Saving...":"Save policy"})}),s.jsxs("div",{className:"mt-2 text-[12px]",children:[s.jsx("span",{className:"text-text-muted",children:"Effective provider priority: "}),s.jsx("span",{className:ce.configured?"text-text-primary font-mono":"text-amber-400",children:ce.label}),ce.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",ce.launchBlockedMessage,")"]})]})]})})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:ge=>{ge.stopPropagation(),Z(D.id)},children:s.jsx(gt,{size:14})})]}),je&&s.jsxs("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",s.jsx("span",{className:"font-mono",children:D.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:ce.configured?"text-green-400":"text-amber-400",children:ce.configured?"yes":"provider priority not configured"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",s.jsx("span",{className:"font-mono",children:D.repoRoot||D.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",G.length]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Branch / git:"})," not loaded in standalone list view"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Health:"})," ",re.length>0||G.length>0?"active":"idle/unknown"]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),re.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:re.map(ge=>s.jsx("li",{className:"font-mono",children:ev(ge)},ge.id))})]}),G.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active sessions"}),s.jsx("ul",{className:"m-0 pl-4",children:G.map(ge=>s.jsxs("li",{className:"font-mono",children:[ge.provider," / ",ge.status," / ",ge.id]},ge.id))})]})]})]},D.id)})})]}),s.jsx(sv,{meshId:be.id,availableCliAgents:a})]})}function zo(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function nv(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=zo();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 $t(e,t){return await fetch(nv(e),{credentials:"same-origin",...t})}function Vd(){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 av{constructor(){Xe(this,"adapters",new Map);Xe(this,"states",new Map);Xe(this,"runtimeListeners",new Map);Xe(this,"screenshotCallbacks",new Map);Xe(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,o,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:o,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 o=await $t(`${a.pathname}${a.search}`);if(!o.ok){let l=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(l=d.error)}catch{}return{success:!1,error:l}}const c=await o.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 Ft=new av;function ov(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=zo();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Xr=ov(),Nc=3e3,iv=3e4;let _t=null,cv=0;const Sn=new Map;let ns=null,hr=null;function Cc(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function nr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function lv(e){return e==="connected"?"connected":e}async function on(e,t,r){const n=Ol(e,r||{}),a=_t;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++cv}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{Sn.delete(o),l(new Error(`WS command timeout: ${t}`))},3e4);Sn.set(o,{resolve:m=>{clearTimeout(d),c(m)},reject:m=>{clearTimeout(d),l(m)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Za(e,t){const r=_t;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 dv(e,t,r){const n=_t;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Ol(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 uv{constructor(t){Xe(this,"daemonId");Xe(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(_t==null?void 0:_t.readyState)===WebSocket.OPEN}get connectionState(){return(_t==null?void 0:_t.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return on(this.daemonId,t,r)}async sendInput(t,r){return on(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,ns&&(clearInterval(ns),ns=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await on(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(o=>o.blob());Ft.emitScreenshot(this.daemonId,a)}}catch{}};r(),ns=setInterval(r,2e3)}stopScreenshots(t){ns&&(clearInterval(ns),ns=null)}}let At=null;function mv(e){return(!At||At.daemonId!==e)&&(At=new uv(e)),At}function pv({children:e}){const t=i.useRef(br()),r=br();t.current=r;const{setUserName:n}=es(),a=i.useRef(n);a.current=n;const o=i.useRef(null),c=i.useRef(null),[,l]=i.useState("disconnected"),d=i.useCallback((p,g)=>{l(p),hr==null||hr(p,g)},[]),m=i.useRef(null),u=i.useRef(),f=i.useRef(Nc),b=i.useRef(!0),v=i.useRef(!1),h=i.useRef("initial_connect");return i.useEffect(()=>{b.current=!0,v.current=!1;function p(){var x,C;if(!b.current||((x=m.current)==null?void 0:x.readyState)===WebSocket.OPEN||((C=m.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Xr}...`),nr("connect_attempt",{url:Xr,reason:h.current,delayMs:f.current});let y;try{y=new WebSocket(Xr)}catch(S){console.error("[Standalone WS] Failed to create WebSocket:",S),g();return}m.current=y,y.onopen=()=>{if(!b.current){y.close();return}d("connected"),f.current=Nc,nr("open",{url:Xr,reason:h.current}),Ut.resubscribeAll({sendData:Za}),console.log("[Standalone WS] Connected")},_t=y,y.onmessage=S=>{var w,M;try{const L=JSON.parse(S.data);if((L.type==="command_result"||L.type==="error")&&L.requestId){const j=Sn.get(L.requestId);j&&(Sn.delete(L.requestId),L.type==="error"?j.reject(new Error(((w=L.data)==null?void 0:w.message)||"Command failed")):j.resolve(L.data));return}if(L.type==="session_output"){const j=L.sessionId||L.cliId||L.cliType;j&&Ft.emitSessionOutput(j,typeof L.data=="string"?L.data:"",typeof L.seq=="number"?L.seq:void 0);return}if(L.type==="runtime_snapshot"){Ft.emitRuntimeSnapshot(L.sessionId,typeof L.text=="string"?L.text:"",typeof L.seq=="number"?L.seq:0,!!L.truncated,typeof L.cols=="number"?L.cols:void 0,typeof L.rows=="number"?L.rows:void 0);return}if(L.type==="topic_update"){const j=L.update;j&&Ut.publish(j);return}if(L.type==="status"||L.type==="initial_state"){const j=L.data;if(!j)return;const{injectEntries:k,markLoaded:B,getIdes:_}=t.current,T=j.instanceId||"standalone",F=_().find(I=>I.id===T),H=mv(T);Ft.register(T,H),Ft.setState(T,"connected"),d("connected",T),Ft.emitStatus(T,j);const R=bn(j,{daemonId:T,existingDaemon:F,existingEntries:_()});Cc("ws_status",{type:L.type,daemonId:T,sessions:(j.sessions||[]).map(I=>({id:I.id,parentId:I.parentId,providerType:I.providerType,kind:I.kind,transport:I.transport,unread:I.unread,inboxBucket:I.inboxBucket,lastSeenAt:I.lastSeenAt,lastUpdated:I.lastUpdated,title:I.title})),recentLaunches:(j.recentLaunches||[]).map(I=>({id:I.id,providerType:I.providerType,kind:I.kind,workspace:I.workspace,lastLaunchedAt:I.lastLaunchedAt}))}),Cc("entries",{daemonId:T,entries:R.filter(I=>I.type!=="adhdev-daemon").map(I=>({id:I.id,type:I.type,unread:I.unread,inboxBucket:I.inboxBucket,lastSeenAt:I.lastSeenAt,lastUpdated:I.lastUpdated,sessionId:I.sessionId}))}),R.length>0&&k(R,{authoritativeDaemonIds:[T]}),B(),c.current!==T&&((M=o.current)==null||M.call(o),c.current=T,o.current=Ut.subscribe({sendData:Za},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},I=>{if(I.topic!=="daemon.metadata")return;const N=t.current.getIdes(),K=N.find(E=>E.id===T),P=bn(I.status,{daemonId:T,existingDaemon:K,existingEntries:N,timestamp:I.timestamp});P.length>0&&t.current.injectEntries(P,{authoritativeDaemonIds:[T]}),I.userName&&a.current&&a.current(I.userName)}))}}catch(L){console.error("[Standalone WS] Parse error:",L)}},y.onclose=S=>{b.current&&(At==null||At.stopScreenshots(),At&&Ft.setState(At.daemonId,"disconnected"),d("disconnected"),m.current=null,h.current=`close:${S.code}${S.wasClean?":clean":":unclean"}`,nr("close",{code:S.code,reason:S.reason||"",wasClean:S.wasClean}),g())},y.onerror=S=>{v.current||!b.current||(h.current="error",nr("error",{message:S instanceof Event?"event":String(S),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",S))}}function g(){if(!b.current)return;clearTimeout(u.current);const y=f.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),nr("schedule_reconnect",{reason:h.current,delayMs:y}),u.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,iv),p()},y)}return p(),()=>{var y;b.current=!1,v.current=!0,(y=o.current)==null||y.call(o),o.current=null,c.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,_t=null),At&&(At.stopScreenshots(),Ft.unregister(At.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function fv({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(hr=(c,l)=>{r(c),l&&a(l)},()=>{hr=null}),[]);const o=i.useMemo(()=>{const c=t==="connected",l=lv(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(Gu,{connectionOverrides:o,children:s.jsx(pv,{children:e})})}const Gd="adhdev_standalone_font_preferences",hs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Kn=[{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"}],vr=[{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"}],hv=new Set(Kn.map(e=>e.id)),xv=new Set(vr.map(e=>e.id));function Ot(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:cn("chat",t.chat),code:cn("code",t.code),terminal:cn("terminal",t.terminal)}}function cn(e,t){const r=hs[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",o=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?hv:xv).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function ln(e,t){var a;const r=cn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Kn:vr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function bv(e){const t=Ot(e),r=ln("chat",t.chat),n=ln("code",t.code),a=ln("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function os(e,t=document.documentElement){const r=Ot(e),n=bv(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function eo(e){const t=Ot(e);try{localStorage.setItem(Gd,JSON.stringify(t))}catch{}return t}function gv(){try{const e=localStorage.getItem(Gd);if(e)return Ot(JSON.parse(e))}catch{}return hs}function yv(){return os(gv())}function ar(e,t){var n;const r=e==="chat"?Kn:vr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const vv=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Ec,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(Jt,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Ds,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(Nn,{}),label:"Settings"}];function wv({children:e}){const t=Ws(),r=so(),n=i.useMemo(()=>vv.map(o=>({...o,active:r.pathname.startsWith(o.path),onSelect:()=>t(o.path)})),[r.pathname,t]),a=i.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(Bc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Oc,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(ix,{brand:({collapsed:o})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!o&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:o})=>o?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.81"]}),footerActions:({collapsed:o,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:o?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:o?"›":"‹"}),!o&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const jv=[{icon:s.jsx(Jt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(zt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Kc,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(It,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Ds,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Bc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],kv=[{icon:s.jsx(dm,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Ec,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Cn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(rm,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx($c,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(am,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Sv=[{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 Nv(){return s.jsxs(mr,{icon:s.jsx(Oc,{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.81"]}),children:[s.jsx(vt,{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(vt,{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:jv.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(vt,{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:Kl.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Wl.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Fl.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(vt,{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:kv.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(vt,{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:Sv.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(yn,{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(vm,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Ta(e,t,r){return{...e,[t]:r}}function Ma({surface:e,title:t,description:r,value:n,options:a,onChange:o}){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;o(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=>o({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:ln(e,n)})]})]})]})}function Cv({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:c,onResetToSaved:l,onResetToDefaults:d}){const m=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Ma,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Kn,onChange:u=>o(Ta(e,"chat",u))}),s.jsx(Ma,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:vr,onChange:u=>o(Ta(e,"code",u))}),s.jsx(Ma,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:vr,onChange:u=>o(Ta(e,"terminal",u))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",ar("chat",e.chat.preset)," · Code: ",ar("code",e.code.preset)," · Terminal: ",ar("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",ar("chat",hs.chat.preset)," / ",ar("code",hs.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:c,disabled:r||!m,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:l,disabled:r||!m,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick:d,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function Iv(){const{ides:e}=es(),t=e.find(X=>X.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=yt(),{userName:a}=es(),[o,c]=i.useState(a||""),[l,d]=i.useState(null),[m,u]=i.useState(null),[f,b]=i.useState(hs),[v,h]=i.useState(!1),[p,g]=i.useState(""),[y,x]=i.useState(""),[C,S]=i.useState("127.0.0.1"),[w,M]=i.useState(""),[L,j]=i.useState(""),[k,B]=i.useState(""),[_,T]=i.useState(""),[F,H]=i.useState(""),[R,I]=i.useState(!1),N=async()=>{const ue=await(await $t("/auth/session")).json();d(ue)},K=async()=>{const ue=await(await $t("/api/v1/standalone/preferences")).json();u(ue),S(ue.standaloneBindHost);const fe=Ot(ue.standaloneFontPreferences);b(fe),os(fe),eo(fe)};i.useEffect(()=>{a!==void 0&&c(a)},[a]),i.useEffect(()=>{Promise.all([N(),K()]).catch(X=>{T(X instanceof Error?X.message:String(X))})},[]),i.useEffect(()=>{os(f)},[f]);const P=X=>{const ue=X.target.value.trim();t!=null&&t.id&&ue!==a&&n(t.id,"set_user_name",{userName:ue}).catch(console.error)},[E,U]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),ee=X=>{U(X);try{localStorage.setItem("adhdev_sound",X?"1":"0")}catch{}},ye=async()=>{g(""),x(""),h(!0);try{const X=Ot(f),ue=await $t("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:X})}),fe=await ue.json();if(!ue.ok)throw new Error((fe==null?void 0:fe.error)||"Failed to save standalone font preferences");const ve=Ot(fe.standaloneFontPreferences);u(fe),b(ve),os(ve),eo(ve),x("Standalone chat fonts saved for this self-hosted dashboard.")}catch(X){g(X instanceof Error?X.message:String(X))}finally{h(!1)}},le=()=>{const X=Ot(m==null?void 0:m.standaloneFontPreferences);g(""),x(""),b(X),os(X)},Q=()=>{g(""),x(""),b(hs),os(hs)},xe=async()=>{T(""),H(""),I(!0);try{const X=await $t("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),ue=await X.json();if(!X.ok)throw new Error((ue==null?void 0:ue.error)||"Failed to save standalone network preference");u(ue),S(ue.standaloneBindHost),H(ue.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(X){T(X instanceof Error?X.message:String(X))}finally{I(!1)}},we=async()=>{if(T(""),H(""),L.trim().length<4){T("Password must be at least 4 characters.");return}if(L!==k){T("New password and confirmation do not match.");return}I(!0);try{const X=await $t("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,newPassword:L})}),ue=await X.json();if(!X.ok)throw new Error((ue==null?void 0:ue.error)||"Failed to save password");d(ue),await K(),M(""),j(""),B(""),H(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Vd()}catch(X){T(X instanceof Error?X.message:String(X))}finally{I(!1)}},be=async()=>{T(""),H(""),I(!0);try{const X=await $t("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,clear:!0})}),ue=await X.json();if(!X.ok)throw new Error((ue==null?void 0:ue.error)||"Failed to clear password");d(ue),await K(),M(""),j(""),B(""),H("Standalone password disabled.")}catch(X){T(X instanceof Error?X.message:String(X))}finally{I(!1)}};return s.jsxs(mr,{icon:s.jsx(Nn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Ms,{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(Ms,{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(vt,{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.81"]}),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(vt,{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:()=>S("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="0.0.0.0",onChange:()=>S("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:()=>{xe()},disabled:R,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 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(vt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),_&&s.jsx(Ms,{variant:"error",children:_}),F&&s.jsx(Ms,{variant:"success",children:F}),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:w,onChange:X=>M(X.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:L,onChange:X=>j(X.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:k,onChange:X=>B(X.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{we()},disabled:R,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…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{be()},disabled:R,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(vt,{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(X=>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 ${X.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:X.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:X.type})]},X.type))})}),s.jsx(vt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(xx,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(vt,{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(vx,{})]}),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(Tx,{})]}),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(Cv,{value:f,savedValue:Ot(m==null?void 0:m.standaloneFontPreferences),saving:v,error:p,notice:y,onChange:b,onSave:()=>{ye()},onResetToSaved:le,onResetToDefaults:Q})]}),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(Lx,{})]})]})}),s.jsx(vt,{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(px,{}),s.jsx(as,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ym,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:ee})]})}),s.jsx(vt,{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(sm,{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:o,onChange:X=>c(X.target.value),onBlur:P,onKeyDown:X=>{X.key==="Enter"&&X.currentTarget.blur()}})]})})})]})}ax();Cx();yv();const Tv=Pc({baseUrl:"",getToken:zo});function Mv({children:e}){const[t,r]=i.useState(null),[n,a]=i.useState(!0),[o,c]=i.useState(""),[l,d]=i.useState(""),[m,u]=i.useState(!1),f=async()=>{a(!0),d("");try{const h=await(await $t("/auth/session")).json();r(h)}catch(v){d(v instanceof Error?v.message:String(v))}finally{a(!1)}};i.useEffect(()=>{f()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let v=!1;return(async()=>{try{const h=await $t("/api/v1/standalone/preferences");if(!h.ok)return;const p=await h.json();if(v)return;const g=Ot(p.standaloneFontPreferences);os(g),eo(g)}catch{}})(),()=>{v=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const b=async v=>{v.preventDefault(),u(!0),d("");try{const h=await $t("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),p=await h.json();if(!h.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),Vd()}catch(h){d(h instanceof Error?h.message:String(h))}finally{u(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:b,children:[s.jsx("input",{type:"password",value:o,onChange:v=>c(v.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:m||!o,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 Ic(){const{ides:e,initialLoaded:t}=es();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(Ra,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Ra,{to:"/dashboard",replace:!0})}function Av(){const e=i.useMemo(()=>({sendCommand:on,sendData:Za,sendPtyInput:dv}),[]);return s.jsx(Lu,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Xu,{client:Tv,children:s.jsx(Mv,{children:s.jsx(fv,{children:s.jsx(Qu,{value:e,children:s.jsx(wv,{children:s.jsxs(Ru,{children:[s.jsx(qt,{path:"/dashboard",element:s.jsx(Uy,{})}),s.jsx(qt,{path:"/machine",element:s.jsx(Ic,{})}),s.jsx(qt,{path:"/machines/:id",element:s.jsx(X0,{})}),s.jsx(qt,{path:"/machines",element:s.jsx(Ic,{})}),s.jsx(qt,{path:"/about",element:s.jsx(Nv,{})}),s.jsx(qt,{path:"/settings",element:s.jsx(Iv,{})}),s.jsx(qt,{path:"/mesh",element:s.jsx(rv,{})}),s.jsx(qt,{path:"*",element:s.jsx(Ra,{to:"/dashboard",replace:!0})})]})})})})})})})}hh({connectionManager:Ft});_u(document.getElementById("root")).render(s.jsx(Av,{}));