@adhdev/daemon-standalone 0.9.76-rc.6 → 0.9.76-rc.8

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,7 +1,7 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-BeBmUW3m.js","assets/vendor-CLec0455.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
- var jd=Object.defineProperty;var kd=(e,t,r)=>t in e?jd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Qe=(e,t,r)=>kd(e,typeof t!="symbol"?t+"":t,r);import{r as o,j as s,M as Da,a as Sd,b as Nd,c as Cd,R as Ct,d as ar,t as Td,e as Md,u as $s,D as Ad,f as ua,g as ma,h as Ea,i as Id,k as Rd,B as Ld,l as _d,m as Gt,N as fa,n as Pd}from"./vendor-CLec0455.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();function Dd(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(a),r.length>t&&r.splice(0,r.length-t),a},list(n={}){const a=Math.max(1,Math.floor(n.limit||100));return r.filter(i=>!n.interactionId||i.interactionId===n.interactionId).filter(i=>!n.topic||i.topic===n.topic).filter(i=>!n.kind||i.kind===n.kind).slice(-a).map(i=>({...i,payload:i.payload?{...i.payload}:{}}))},clear(){r.splice(0,r.length)}}}const Ms=Dd();function _o(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 Ed(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function $d(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function zi(e,t){if(!e)return t??null;if(!t)return e??null;const r=$d(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:t.messages,a={...t,...e,activeModal:e.activeModal??null,inputContent:e.inputContent??t.inputContent};return r?{...a,messages:n}:a}function Xs(e,t){const r=Ed(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:zi(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 Vi(e,t,r){if(!(t!=null&&t.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const n=t.map(a=>{const i=e.find(c=>c.id===a.id);return i?Xs(a,i):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(t.map(i=>i.id));for(const i of e)a.has(i.id)||n.push(i)}return n}function Po(e){return!!e&&typeof e=="object"&&"text"in e}function $a(e,t){const r=(t==null?void 0:t.joiner)??" ",n=(t==null?void 0:t.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(i=>typeof i=="string"?i:Po(i)?String(i.text||""):"").join(r):Po(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function As(e){return $a(e,{normalizeWhitespace:!0})}const Gi=o.createContext({ides:[],updateRouteChats:()=>{},initialLoaded:!1,toasts:[],setToasts:()=>{},wsStatus:"connected",isConnected:!0,connectionStates:{},connectionTransports:{},showReconnected:!1,userName:void 0,setUserName:()=>{},isP2PActive:!1,p2pStates:{},userRole:void 0,connectionRetryStatuses:void 0}),qi=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Do(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 Yi(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,i=t.serverVersion??e.serverVersion??r.serverVersion,c=t.versionMismatch===!0||e.versionMismatch===!0,l=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),i&&(n.serverVersion=i),d&&(n.versionUpdateReason=d),a&&i&&a===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||c&&a&&i&&a!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function Bd(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 Sn(e){if(!e||typeof e!="object")return"";const t=e,r=Bd(As(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 Kd(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=Sn(n);for(let i=0;i<a.length;i+=1)r^=a.charCodeAt(i),r=Math.imul(r,16777619)>>>0}return{count:e.length,hash:r.toString(16).padStart(8,"0"),first:Sn(e[0]),last:Sn(e[e.length-1])}}function pa(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function ha(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(pa(e)&&pa(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)ha(e[l],t[l],r);return}const n=e,a=t,i=new Set([...Object.keys(n),...Object.keys(a)]);for(const c of i)c!=="messages"&&ha(n[c],a[c],r)}function Qs(e,t){return Array.isArray(e)?e.map(r=>Qs(r,t)):!e||typeof e!="object"?e:pa(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Kd(a,t):Qs(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Qs(n,t)]))}function Wd(e,t){try{const r=new WeakSet;return ha(e,t,r),JSON.stringify(Qs(e,r))===JSON.stringify(Qs(t,r))}catch{return!1}}function xa(e,t,r){return Wd(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Xi(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Od(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Eo(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,i=Vi(e.childSessions,t.childSessions,{preserveMissing:n}),c=zi(t.activeChat,e.activeChat);return Yi(e,t,{...e,...t,chats:a,childSessions:i,activeChat:c,_lastUpdate:r})}function Fd(e,t,r){var a,i;const n={};t.status&&t.status!==e.status&&(n.status=t.status),t.cdpConnected!==void 0&&(n.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(n.childSessions=Vi(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((i=e.chats)!=null&&i.length)&&(n.chats=t.chats);for(const c of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])Od(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Hd(e,t,r,n){const a=Fd(e,t,n),i=Object.keys(a).length>0?Yi(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return xa(e,i,r)}function Ud(e){const t=new Set(e.map(i=>i.id)),r=new Set,n=new Set,a=new Set;for(const i of e){const c=Xi(i);c&&r.add(c),c&&i.type!=="adhdev-daemon"&&n.add(c),c&&i.type==="adhdev-daemon"&&i._sessionListAuthoritative&&a.add(c)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function zd(e,t,r,n,a,i){return!a.has(t)||!i.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function Vd(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function Gd(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(x=>({...x,_lastUpdate:n}));const i=new Map;for(const x of t)i.set(x.id,x);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:m}=Ud(e);for(const x of e){const C=i.get(x.id);if(!C){i.set(x.id,{...x,_lastUpdate:n});continue}const g=Do(x),p=Do(C),j=Xi(x),b=!a.has(j);if(g>p){const S=Eo(C,x,n,b);i.set(x.id,xa(C,S,n));continue}if(g<p){i.set(x.id,Hd(C,x,n,b));continue}const h=x.timestamp||n,y=C._lastUpdate||C.timestamp||0;if(h>=y){const S=Eo(C,x,n,b);i.set(x.id,xa(C,S,n));continue}(u=x.chats)!=null&&u.length&&!((f=C.chats)!=null&&f.length)&&i.set(x.id,{...C,chats:x.chats})}for(const[x,C]of i){const g=C.daemonId||x.split(":")[0];if(!l.has(g))continue;if(a.has(g)&&m.has(g)&&!c.has(x)){i.delete(x);continue}const p=n-(C._lastUpdate||C.timestamp||0);zd(C,g,p,c,a,d)&&i.delete(x)}for(const[x,C]of i){const g=C.daemonId||x.split(":")[0];if(Vd(C,g,l,d,i))continue;n-(C._lastUpdate||C.timestamp||0)>3e5&&C.status!=="online"&&i.delete(x)}return Array.from(i.values())}function qd(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 Yd({children:e,connectionOverrides:t}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[d,m]=o.useState(void 0),u=o.useRef(r);o.useEffect(()=>{u.current=r},[r]);const f=o.useCallback((b,h)=>{n(y=>{let S=!1;const k=y.map(A=>A.id!==b||A.chats===h?A:(S=!0,{...A,chats:h}));return S?k:y})},[]),x=o.useCallback((b,h)=>{n(y=>{const S=y.length===0?b:Gd(b,y,h),k=!qd(y,S);return k&&Ms.record({kind:"dashboard.entries_applied",payload:{incoming:_o(b),next:_o(S)}}),k?S:y})},[]),C=o.useCallback(()=>i(!0),[]),g=o.useMemo(()=>({injectEntries:x,markLoaded:C,getIdes:()=>u.current}),[x,C]),p=t,j=o.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(qi.Provider,{value:g,children:s.jsx(Gi.Provider,{value:j,children:e})})}function Qt(){return o.useContext(Gi)}function or(){return o.useContext(qi)}function Ji(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function i(l){const d=r==null?void 0:r(),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),x=new AbortController,C=setTimeout(()=>x.abort(),15e3);try{const g=await fetch(f,{...d,headers:m,signal:x.signal});if(g.status===401)throw n==null||n(),new Error("Unauthorized");if(!g.ok){const p=await g.json().catch(()=>({error:g.statusText}));throw new Error(p.error||`API Error: ${g.status}`)}return g.json()}finally{clearTimeout(C)}}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=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Xd=Ji({baseUrl:"http://localhost:3847"}),Jd=o.createContext(Xd);function Qd({client:e,children:t}){return s.jsx(Jd.Provider,{value:e,children:t})}const Zd={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Qi=o.createContext(Zd);function eu({value:e,children:t}){return s.jsx(Qi.Provider,{value:e,children:t})}function bt(){return o.useContext(Qi)}function tu(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 su(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function ru(e){return e?tu([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),su(e.content)]):""}const Oe={size:18};function Zi({size:e=Oe.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 Ba({size:e=Oe.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 Yt({size:e=Oe.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 ec({size:e=Oe.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 nu({size:e=Oe.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 au({size:e=Oe.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 tc({size:e=Oe.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 ou({size:e=Oe.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 dn({size:e=Oe.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 sc({size:e=Oe.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 iu({size:e=Oe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Ut({size:e=Oe.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 Mt({size:e=Oe.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 Ka({size:e=Oe.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 cu({size:e=Oe.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 ms({size:e=Oe.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 dr({size:e=Oe.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 ir({size:e=Oe.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 Is({size:e=Oe.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 wr({size:e=Oe.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 rc({size:e=Oe.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 Wa({size:e=Oe.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 nc({size:e=Oe.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 lu({size:e=Oe.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 Oa({size:e=Oe.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 du({size:e=Oe.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 Fa({size:e=Oe.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 ac({size:e=Oe.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 yt({size:e=Oe.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 uu({size:e=Oe.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 mu({size:e=Oe.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 fu({size:e=Oe.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 pu({size:e=Oe.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 un({size:e=Oe.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 hu({size:e=Oe.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 xu({size:e=Oe.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 bu({size:e=Oe.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 gu({size:e=Oe.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 yu({size:e=Oe.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 vu({size:e=Oe.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 wu({size:e=Oe.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 ju({size:e=Oe.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 ku({size:e=Oe.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 Su({size:e=Oe.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 Nu({size:e=Oe.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 Cu({size:e=Oe.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 oc=[Sd,{singleTilde:!1}],ic=[oc,Nd,Cd],Tu=[oc],Ha=200,Mu=80,$o=650,Os=new Map;function Xr(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function Au(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}:${ru(n)}`}function Iu(e,t,r,n){return e||!t?!1:Xr(r,n)}function Ru({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=Mu,bottomThresholdPx:a=Ha}){const i=Math.max(0,Number(e)||0),c=Math.max(0,Number(t)||0),l=Math.max(0,Number(r)||0);return Math.max(0,c-l)<=0?{showTop:!1,showBottom:!1}:{showTop:i>n,showBottom:Math.max(0,c-i-l)>a}}function Lu(e){return Ru({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Js(e,t=Ha){return!!e&&e.fromBottom>=t}function _u(e,t){return Xr(e,t)?!Js(e):!0}function Pu({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function Du({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function Nn(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function cc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Eu(e,t,r){return Number(e.receivedAt||r[Jr(e,t)]||0)||0}function lc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function $u(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function jr(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 Cn(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 Bo(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):lc(e)?s.jsx(Da,{remarkPlugins:ic,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function kr({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:Bo(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=Cn(r);return a?s.jsx("img",{src:a,alt:jr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=Cn(r);return a?s.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=Cn(r);return a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:jr(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||jr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=jr(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}),Bo(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 Jr(e,t){const r=e,n=$a(e.content,{joiner:`
3
- `});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${t}`].filter(Boolean).join("|")}const Bu=o.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Da,{remarkPlugins:Tu,children:t.text}),s.jsx("span",{className:"action-time",children:cc(t.timestamp)})]})},(e,t)=>e.log===t.log),Ku=o.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var A,M,w;const d=(t.role||"").toLowerCase(),m=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),f=$u(t.content)?t.content:null,x=!!(f!=null&&f.some(v=>v.type!=="text")),C=$a(t.content,{joiner:`
4
- `});if(u==="thought"){const v=typeof((A=t.meta)==null?void 0:A.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(fu,{size:13}),s.jsx("span",{children:v})]}),s.jsx("div",{className:"chat-msg-body",children:C})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),x&&f?s.jsx("div",{className:"tool-text w-full",children:s.jsx(kr,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:C})]});if(u==="terminal"){const v=(M=t.meta)!=null&&M.isRunning?"⏳":"✅",B=typeof((w=t.meta)==null?void 0:w.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:v}),s.jsx("span",{children:B})]}),x&&f?s.jsx("div",{className:"chat-msg-body",children:s.jsx(kr,{parts:f,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:C})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:x&&f?s.jsx(kr,{parts:f,renderAsPreformatted:!1}):C.slice(0,100)});const g=t.meta,j=(typeof(g==null?void 0:g.renderMode)=="string"?g.renderMode.trim():"")==="preformatted",b=C,h=!1,y=b,S=j,k=!S&&lc(y);return s.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${m?"self-end":"self-start"}`,children:(b||x||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${b||x?"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:cc(r)})]}),(b||x)&&s.jsx("div",{className:"chat-markdown",children:x&&f?s.jsx(kr,{parts:f,renderAsPreformatted:S}):S?s.jsx("pre",{className:"chat-preformatted",children:y}):k?s.jsx(Da,{remarkPlugins:ic,children:y}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:y})}),h]})})},(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),Wu=o.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:d={},lastMessageHash:m,emptyState:u,onLoadMore:f,isLoadingMore:x,hasMoreHistory:C,hiddenLiveCount:g=0,loadError:p,scrollToBottomRequestNonce:j,isVisible:b=!0},h){const y=o.useRef(null),S=o.useRef(null),k=o.useRef(null),A=o.useRef(0),M=o.useRef(""),w=o.useRef(""),v=o.useRef(!1),B=o.useRef(null),_=o.useRef(!1),T=o.useRef(null),D=o.useRef(!1),[K,L]=o.useState(new Set),[N,I]=o.useState({showTop:!1,showBottom:!1}),W=o.useRef(!1),P=o.useRef(!1),$=o.useRef(b),H=o.useRef(b),J=o.useRef(null);H.current=b;const he=()=>{const q=y.current;return q?q.scrollHeight-q.scrollTop-q.clientHeight<Ha:!0},ie=o.useCallback(()=>{const q=y.current,V=q?Lu(q):{showTop:!1,showBottom:!1};I(le=>le.showTop===V.showTop&&le.showBottom===V.showBottom?le:V)},[]),te=o.useCallback((q="auto")=>{var le;const V=y.current;V&&(V.scrollTo({top:V.scrollHeight,behavior:q}),(le=V.ownerDocument.defaultView)==null||le.requestAnimationFrame(()=>ie()))},[ie]),be=o.useCallback((q="auto")=>{var le;const V=y.current;V&&(V.scrollTo({top:0,behavior:q}),(le=V.ownerDocument.defaultView)==null||le.requestAnimationFrame(()=>ie()))},[ie]),we=o.useCallback(()=>{var Z;const q=y.current,V=(Z=window.getSelection)==null?void 0:Z.call(window);if(!q||!V||V.rangeCount===0||V.isCollapsed){D.current=!1;return}const le=V.anchorNode,ke=V.focusNode;D.current=!!(le&&ke&&q.contains(le)&&q.contains(ke))},[]),ge=Au(t,m),X=o.useCallback(()=>{const q=y.current;if(!q||!l||!H.current)return;const V={top:q.scrollTop,fromBottom:Math.max(0,q.scrollHeight-q.scrollTop-q.clientHeight),messageFingerprint:ge};J.current={contextKey:l,snapshot:V},Os.set(l,V)},[l,ge]),ce=o.useCallback((q="auto")=>{B.current!=null&&cancelAnimationFrame(B.current),B.current=requestAnimationFrame(()=>{B.current=null,te(q)})},[te]),ye=o.useCallback(()=>{W.current=!1,_.current=!0,P.current=!0,T.current!=null&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{_.current=!1,T.current=null},$o)},[]);o.useEffect(()=>{const q=!v.current,V=w.current!==l;if(w.current=l,q||V){v.current=!0;const ke=l?Os.get(l):null,Z=!!ke&&Xr(ke,ge);W.current=Z?Js(ke):!1,_.current=_u(ke,ge),D.current||(Z?requestAnimationFrame(()=>{const De=y.current;De&&(Nn(De,ke),W.current=Js(ke),ie(),P.current=!0)}):ce("auto")),A.current=t.length,M.current=ge;return}t.length>A.current;const le=ge!==M.current;Pu({hasSelection:D.current,userScrolledUp:W.current,hasChatContentChanged:le})&&ce("auto"),A.current=t.length,M.current=ge},[ge,l,t.length,ce,ie]),o.useEffect(()=>{j&&(ye(),D.current||ce("auto"))},[ye,ce,j]),o.useEffect(()=>{const q=$.current;q&&!b&&X(),H.current=b,$.current=b;const V=l?Os.get(l):null;if(Iu(q,b,V,ge)){if(!V)return;W.current=Js(V),_.current=!1,D.current||requestAnimationFrame(()=>{const le=y.current;le&&(Nn(le,V),ie())});return}},[b,l,ge,ye,X,ce,ie]),o.useEffect(()=>()=>{const q=J.current;q&&Os.set(q.contextKey,q.snapshot),B.current!=null&&cancelAnimationFrame(B.current),T.current!=null&&window.clearTimeout(T.current)},[]),o.useEffect(()=>{const q=S.current,V=y.current;if(!q||!V)return;const le=()=>{T.current!=null&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{_.current=!1,T.current=null},$o)},ke=new ResizeObserver(()=>{ie();const Z=_.current;Du({hasSelection:D.current,userScrolledUp:W.current,contextAutoScrollActive:Z})&&(ce("auto"),Z&&le())});return ke.observe(q),V!==q&&ke.observe(V),()=>{ke.disconnect(),T.current!=null&&(window.clearTimeout(T.current),T.current=null)}},[ce,l,ie]),o.useImperativeHandle(h,()=>({scrollToBottom:(q="smooth")=>{te(q)}}),[te]),o.useEffect(()=>{const q=y.current;if(!q)return;let V;const le=()=>{X(),clearTimeout(V),V=setTimeout(()=>{W.current=!he(),ie()},50)};return q.addEventListener("scroll",le,{passive:!0}),()=>{q.removeEventListener("scroll",le),clearTimeout(V)}},[X,ie]),o.useEffect(()=>(document.addEventListener("selectionchange",we),()=>document.removeEventListener("selectionchange",we)),[we]);const ne=o.useRef(0),de=o.useRef(!1);o.useEffect(()=>{const q=y.current;if(!q||!de.current||ne.current===0)return;const V=q.scrollHeight-ne.current;V>0&&(q.scrollTop=V),ie(),X(),ne.current=0,de.current=!1},[t.length,X,ie]),o.useEffect(()=>{if(P.current||!l)return;const q=Os.get(l),V=y.current;if(!(!q||!V)){if(!Xr(q,ge)){te("auto"),P.current=!0;return}Nn(V,q),W.current=Js(q),ie(),P.current=!0}},[l,ge,t.length,te,ie]);const je=()=>{const q=y.current;q&&(ne.current=q.scrollHeight),de.current=!0,f==null||f()},me=()=>{W.current=!0,be("smooth"),X()},pe=()=>{ye(),te("smooth"),X()},ee=o.useMemo(()=>{const q=t.map((Z,De)=>({type:"message",data:Z,index:De,ts:Eu(Z,De,d)}));if(!r||r.length===0)return q;const V=[...r].sort((Z,De)=>Z.timestamp-De.timestamp).map((Z,De)=>({type:"action",data:Z,index:De,ts:Z.timestamp})),le=[];let ke=0;for(const Z of q){for(;ke<V.length&&Z.ts>0&&V[ke].ts<Z.ts;)le.push(V[ke++]);le.push(Z)}for(;ke<V.length;)le.push(V[ke++]);return le},[t,r,d]),ue=g>0||!!C,oe=g>0?`↑ Show ${Math.min(g,80)} earlier messages${g>80?` (${g} hidden)`:""}`:p?`↻ ${p}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:y,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:S,className:"chat-container-content",children:[x&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),ue&&!x&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:je,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${p&&g===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:oe})}),ee.length===0&&!ue&&(u||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ee.map(q=>{if(q.type==="action"){const Fe=q.data;return s.jsx(Bu,{log:Fe},`action-${q.index}`)}const V=q.data,le=q.index,ke=Jr(V,le),Z=V.receivedAt||d[ke],De=`${l}-${ke}`,$e=K.has(De);return s.jsx(Ku,{message:V,receivedAt:Z,agentName:n,userName:a,isCliMode:i,isTextExpanded:$e,onToggleTextExpanded:()=>L(Fe=>{const Ue=new Set(Fe);return $e?Ue.delete(De):Ue.add(De),Ue})},`msg-${ke}`)}),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:k})]})}),(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:pe,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Ou=o.memo(Wu,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.lastMessageHash===t.lastMessageHash&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible),Fu="modulepreload",Hu=function(e){return"/"+e},Ko={},Uu=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=Hu(d),d in Ko)return;Ko[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":Fu,m||(f.as="script"),f.crossOrigin="",f.href=d,l&&f.setAttribute("nonce",l),document.head.appendChild(f),m)return new Promise((x,C)=>{f.addEventListener("load",x),f.addEventListener("error",()=>C(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};let Wo=!1;const dc=o.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:i="measured"},c)=>{const l=o.useRef(null),[d,m]=o.useState(null),u=o.useRef([]),f=o.useRef(!1),x=o.useRef(!1),C=o.useRef(!1),g=o.useRef(!1),p=()=>{const j=l.current;if(j){f.current&&(j.clear(),f.current=!1);for(const b of u.current)j.write(b.data,b.onProcessed);u.current=[],x.current&&(j.fit(),x.current=!1),C.current&&(j.bumpResize(),C.current=!1),g.current&&(j.scrollToTop(),g.current=!1)}};return o.useImperativeHandle(c,()=>({write:(j,b)=>{l.current?l.current.write(j,b):u.current.push({data:j,onProcessed:b})},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:(j,b)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(j,b)},fit:()=>{l.current?l.current.fit():x.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():C.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():g.current=!0},getSelection:()=>{var j,b;return((b=(j=l.current)==null?void 0:j.getSelection)==null?void 0:b.call(j))||""},getVisibleText:()=>{var j,b;return((b=(j=l.current)==null?void 0:j.getVisibleText)==null?void 0:b.call(j))||""}}),[]),o.useEffect(()=>{d&&p()},[d]),o.useEffect(()=>{let j=!1;return Uu(()=>import("./terminal-BeBmUW3m.js"),__vite__mapDeps([0,1,2])).then(b=>{Wo||(Wo=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),j||m(()=>b.GhosttyTerminalView)}).catch(b=>{console.error("[CliTerminal] failed to load terminal renderer",b)}),()=>{j=!0}},[]),d?s.jsx(d,{ref:l,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:i,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});dc.displayName="CliTerminal";function Sr({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 Oo({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:i=!1}){const c=t>0?Math.min(Math.round(e/t*100),100):0,l=c>85?"#ef4444":c>60?"var(--status-warning)":n;return i?s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),s.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[c,"%"]})]}),s.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${c}%`,background:l}})})]}):s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-1.5",children:[s.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),s.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[c,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${c}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function zu({cursorPos:e,viewportRef:t,imgRef:r}){var h;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(h=t.current)==null?void 0:h.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,d=c/l,m=a.width/a.height;let u,f,x,C;d>m?(u=a.width,f=a.width/d,x=0,C=(a.height-f)/2):(f=a.height,u=a.height*d,x=(a.width-u)/2,C=0);const g=a.left-i.left+x+u*e.nx,p=a.top-i.top+C+f*e.ny,j=Math.max(8,Math.min(i.width-8,g)),b=Math.max(8,Math.min(i.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:j-8,top:b-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function Vu({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:f,mobileFillZoom:x,onZoomOut:C,onZoomReset:g,onZoomIn:p,transportType:j,screenshotUsage:b,lastActionStatus:h}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:y=>y.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(y=>!y),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:y=>y.stopPropagation(),onChange:y=>l(y.target.value),onKeyDown:y=>{d(y)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{i(y=>!y),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),"%"]}),j==="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"}),j==="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"}),b&&b.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:b.budgetExhausted?"#ef4444":"#c4b5fd",background:b.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:b.budgetExhausted?"TURN blocked":`TURN ${b.dailyUsedMinutes}/${b.dailyBudgetMinutes}m`}),h&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:h})]})]}),a&&s.jsxs("div",{onTouchStart:y=>y.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?x:1)+.01?f?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:y=>{y.stopPropagation(),C()},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:y=>{y.stopPropagation(),g()},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:y=>{y.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 Gu({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 qu(){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 Fo(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 ur(e,t){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!qu())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,Fo(l)]))}),r.current=t;return}const i=Object.keys({...a,...t}).filter(c=>!Object.is(a[c],t[c]));i.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(c=>[c,Fo(t[c])]))}),r.current=t})}function Yu({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:d,setPanX:m,setPanY:u,setZoom:f,lastWheelTimeRef:x,onAction:C,setLastActionStatus:g,spawnRippleFromNormalized:p,clampPan:j,isMobile:b,mobileFillZoom:h}){const[y,S]=o.useState(null),k=o.useRef(null),A=o.useRef(null),M=o.useRef(null),w=o.useRef(!1),v=o.useRef(null),B=o.useRef(0),_=o.useRef(null),T=o.useRef(1),D=o.useRef({x:0,y:0}),K=o.useRef(!1),L=o.useRef(n),N=o.useRef(C),I=30,W=550,P=18,$=60,H=400,J=12,he=()=>{if(k.current)return;const be={nx:.5,ny:.5};k.current=be,S(be)};return o.useEffect(()=>{L.current=n,n==="mouse"&&he()},[n]),o.useEffect(()=>{N.current=C},[C]),o.useEffect(()=>{const be=e.current;if(!be)return;const we=de=>{if(!r.current)return null;const je=r.current.getBoundingClientRect();return!je.width||!je.height?null:{nx:Math.max(0,Math.min(1,(de.clientX-je.left)/je.width)),ny:Math.max(0,Math.min(1,(de.clientY-je.top)/je.height))}},ge=(de,je)=>{if(!r.current)return{dnx:0,dny:0};const me=r.current,pe=me.getBoundingClientRect(),ee=me.naturalWidth||pe.width,ue=me.naturalHeight||pe.height,oe=ee/ue,q=pe.width/pe.height;let V,le;return oe>q?(V=pe.width,le=pe.width/oe):(le=pe.height,V=pe.height*oe),{dnx:de/V,dny:je/le}},X=(de,je,me)=>{if(me<=1.05)return;const pe=-(de-.5)*100,ee=-(je-.5)*100,ue=j(pe,ee,me);(Math.abs(ue.x-l.current)>.1||Math.abs(ue.y-d.current)>.1)&&(m(ue.x),u(ue.y),l.current=ue.x,d.current=ue.y)},ce=de=>{const je=t.current;if(je&&de.target instanceof Node&&je.contains(de.target))de.preventDefault();else return;if(de.touches.length===1){const me=de.touches[0];A.current={x:me.clientX,y:me.clientY,time:Date.now()},M.current={x:me.clientX,y:me.clientY},K.current||(w.current=!1),v.current=setTimeout(()=>{if(!w.current&&!K.current)if(w.current=!0,L.current==="mouse"){const pe=k.current||{nx:.5,ny:.5};g("Right Click"),p(pe.nx,pe.ny,"right"),N.current("input_click",{...pe,button:"right"}).catch(()=>{})}else{const pe=we(me);pe&&(g("Right Click"),p(pe.nx,pe.ny,"right"),N.current("input_click",{...pe,button:"right"}).catch(()=>{}))}},500);return}if(de.touches.length===2){v.current&&clearTimeout(v.current),w.current=!0,K.current=!0;const me=de.touches[1].clientX-de.touches[0].clientX,pe=de.touches[1].clientY-de.touches[0].clientY;_.current=Math.sqrt(me*me+pe*pe),T.current=c.current,D.current={x:(de.touches[0].clientX+de.touches[1].clientX)/2,y:(de.touches[0].clientY+de.touches[1].clientY)/2}}},ye=de=>{const je=t.current;if(je&&de.target instanceof Node&&je.contains(de.target)&&de.preventDefault(),de.touches.length===1&&M.current){const me=de.touches[0],pe=me.clientX-M.current.x,ee=me.clientY-M.current.y;if(!w.current&&A.current){const ue=me.clientX-A.current.x,oe=me.clientY-A.current.y;Math.sqrt(ue*ue+oe*oe)>8&&(w.current=!0,v.current&&clearTimeout(v.current))}if(w.current)if(L.current==="mouse"){const ue=ge(pe,ee),oe=k.current||{nx:.5,ny:.5},q=Math.max(0,Math.min(1,oe.nx+ue.dnx)),V=Math.max(0,Math.min(1,oe.ny+ue.dny));k.current={nx:q,ny:V},S({nx:q,ny:V}),g(`Cursor: ${Math.round(q*100)}%, ${Math.round(V*100)}%`),X(q,V,c.current);const le=Date.now();le-x.current>=30&&(x.current=le,N.current("input_mouseMoved",{nx:q,ny:V}).catch(()=>{}))}else if(c.current>1){const ue=t.current;if(ue){const oe=ue.clientWidth,q=ue.clientHeight,V=l.current+pe/oe*100,le=d.current+ee/q*100,ke=j(V,le,c.current);m(ke.x),u(ke.y),l.current=ke.x,d.current=ke.y}}else{const ue=we(me);if(ue){const oe=Date.now();oe-x.current>=40&&(x.current=oe,g("Scroll"),N.current("input_wheel",{nx:ue.nx,ny:ue.ny,deltaX:Math.round(-pe*2.5),deltaY:Math.round(-ee*2.5)}).catch(()=>{}))}}M.current={x:me.clientX,y:me.clientY};return}if(de.touches.length===2&&_.current!==null){const me=de.touches[1].clientX-de.touches[0].clientX,pe=de.touches[1].clientY-de.touches[0].clientY,ue=Math.sqrt(me*me+pe*pe)/_.current,oe=(de.touches[0].clientX+de.touches[1].clientX)/2,q=(de.touches[0].clientY+de.touches[1].clientY)/2,V=oe-D.current.x,le=q-D.current.y,ke=Math.abs(ue-1)>.03;if(L.current==="mouse"){if(ke){const Z=Math.max(i,Math.min(5,T.current*ue));f(Z),c.current=Z}else if(Math.abs(V)>2||Math.abs(le)>2){const Z=k.current||{nx:.5,ny:.5},De=Date.now();De-x.current>=30&&(x.current=De,g("Scroll"),N.current("input_wheel",{nx:Z.nx,ny:Z.ny,deltaX:Math.round(-V*3),deltaY:Math.round(-le*3)}).catch(()=>{}))}}else{const Z=Math.max(i,Math.min(5,T.current*ue));f(Z),c.current=Z;const De=t.current;if(De&&Z>1){const $e=De.clientWidth,Fe=De.clientHeight,Ue=l.current+V/$e*100,O=d.current+le/Fe*100,Ce=j(Ue,O,Z);m(Ce.x),u(Ce.y),l.current=Ce.x,d.current=Ce.y}}D.current={x:oe,y:q}}},ne=de=>{var je;if(v.current&&clearTimeout(v.current),_.current=null,de.touches.length===1&&K.current){const me=de.touches[0];A.current={x:me.clientX,y:me.clientY,time:Date.now()},M.current={x:me.clientX,y:me.clientY},w.current=!0;return}if(de.touches.length===0){if(K.current){K.current=!1,w.current=!1;return}if(de.changedTouches.length===1){const me=de.changedTouches[0],pe=Date.now(),ee=pe-(((je=A.current)==null?void 0:je.time)||0),ue=A.current?me.clientX-A.current.x:0,oe=A.current?me.clientY-A.current.y:0,q=Math.sqrt(ue*ue+oe*oe);if(L.current==="mouse"){if(ee<I||ee>W||q>P){w.current=!1;return}const V=k.current||we(me);V&&(g(`Click: ${Math.round(V.nx*100)}%, ${Math.round(V.ny*100)}%`),p(V.nx,V.ny,"left"),N.current("input_click",{...V}).catch(()=>{}))}else{if(w.current){w.current=!1;return}if(ee<$||ee>H||q>J){w.current=!1;return}const V=we(me);if(!V)return;pe-B.current<300?(g("Double tap"),p(V.nx,V.ny,"double"),N.current("input_click",{...V,clickCount:2}).catch(()=>{}),B.current=0):(g(`Tap: ${Math.round(V.nx*100)}%, ${Math.round(V.ny*100)}%`),p(V.nx,V.ny,"left"),N.current("input_click",{...V}).catch(()=>{}),B.current=pe)}}w.current=!1}};return be.addEventListener("touchstart",ce,{passive:!1}),be.addEventListener("touchmove",ye,{passive:!1}),be.addEventListener("touchend",ne,{passive:!1}),()=>{be.removeEventListener("touchstart",ce),be.removeEventListener("touchmove",ye),be.removeEventListener("touchend",ne),v.current&&clearTimeout(v.current)}},[e,t,r,i,c,l,d,m,u,f,x,g,p,j]),{cursorPos:y,cursorPosRef:k,handleToggleInputMode:()=>{a(be=>{const we=be==="touch"?"mouse":"touch";return we==="mouse"&&he(),we})},handleZoomReset:()=>{const be=b?h:1;f(be),c.current=be,m(0),u(0),l.current=0,d.current=0}}}function uc({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),d=o.useRef(null),[m,u]=o.useState(null),[f,x]=o.useState(""),[,C]=o.useState(!1),[g,p]=o.useState([]),j=o.useRef(0),[b,h]=o.useState(!1),[y,S]=o.useState(!1),k=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[A,M]=o.useState(k?"mouse":"touch"),[w,v]=o.useState(1),B=o.useRef(!1),[_,T]=o.useState(1),[D,K]=o.useState(0),[L,N]=o.useState(0);ur("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:A,zoom:_,panX:D,panY:L,isMenuOpen:b,isImeOpen:y});const I=o.useRef(0),W=o.useRef(_),P=o.useRef(D),$=o.useRef(L);o.useEffect(()=>{W.current=_},[_]),o.useEffect(()=>{P.current=D},[D]),o.useEffect(()=>{$.current=L},[L]),o.useEffect(()=>{var ee;(ee=c.current)==null||ee.focus()},[]);const H=r==="connected",J=n,he=H?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ie=H?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!k||B.current||!J)return;const ee=d.current,ue=l.current;if(!ee||!ue)return;const oe=()=>{const q=ue.clientWidth,V=ue.clientHeight,le=ee.naturalWidth,ke=ee.naturalHeight;if(!le||!ke||!q||!V)return;const Z=Math.min(q/le,V/ke),$e=Math.max(q/le,V/ke)/Z;$e>1.01&&(v($e),T($e),W.current=$e),B.current=!0};ee.complete&&ee.naturalWidth?oe():ee.addEventListener("load",oe,{once:!0})},[J,k]);const te=.5;o.useEffect(()=>{_<=te&&(K(0),N(0))},[_,te]);const be=(ee,ue,oe)=>{if(oe<=te)return{x:0,y:0};const q=(oe-1)/(2*oe)*100,V=(oe-1)/(2*oe)*100;return{x:Math.max(-q,Math.min(q,ee)),y:Math.max(-V,Math.min(V,ue))}},we=(ee,ue)=>{if(!d.current)return null;const oe=d.current.getBoundingClientRect();return!oe.width||!oe.height?null:{nx:Math.max(0,Math.min(1,(ee-oe.left)/oe.width)),ny:Math.max(0,Math.min(1,(ue-oe.top)/oe.height))}},ge=(ee,ue,oe)=>{const q=l.current;if(!q)return;const V=q.getBoundingClientRect(),le=++j.current;p(ke=>[...ke,{id:le,x:ee-V.left,y:ue-V.top,type:oe}]),setTimeout(()=>p(ke=>ke.filter(Z=>Z.id!==le)),600)},X=(ee,ue,oe)=>{const q=d.current,V=l.current;if(!q||!V)return;const le=q.getBoundingClientRect(),ke=V.getBoundingClientRect(),Z=q.naturalWidth||le.width,De=q.naturalHeight||le.height,$e=Z/De,Fe=le.width/le.height;let Ue,O,Ce,Te;$e>Fe?(Ue=le.width,O=le.width/$e,Ce=0,Te=(le.height-O)/2):(O=le.height,Ue=le.height*$e,Ce=(le.width-Ue)/2,Te=0);const _e=le.left-ke.left+Ce+Ue*ee,Be=le.top-ke.top+Te+O*ue,He=++j.current;p(Xe=>[...Xe,{id:He,x:_e,y:Be,type:oe}]),setTimeout(()=>p(Xe=>Xe.filter(st=>st.id!==He)),600)},ce=async ee=>{var oe;const ue=we(ee.clientX,ee.clientY);if(ue){u(`Click: ${Math.round(ue.nx*100)}%, ${Math.round(ue.ny*100)}%`),ge(ee.clientX,ee.clientY,"left"),(oe=c.current)==null||oe.focus();try{const q=await e("input_click",{nx:ue.nx,ny:ue.ny});q!=null&&q.success||t(`❌ Click failed: ${q==null?void 0:q.error}`)}catch(q){t(`❌ Click error: ${q.message||q}`)}}},ye=async(ee,ue,oe,q=0)=>{try{await e("input_key",{type:oe?"char":"keyDown",key:ee,code:ue,text:oe?ee:void 0,unmodifiedText:oe?ee:void 0,modifiers:q})}catch(V){t(`❌ Key error: ${V.message||V}`)}},ne=async ee=>{if(ee.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ee.key)&&ee.preventDefault();let oe=0;ee.altKey&&(oe|=1),ee.ctrlKey&&(oe|=2),ee.metaKey&&(oe|=4),ee.shiftKey&&(oe|=8),u(`Key: ${ee.key}`),await ye(ee.key,ee.code,ee.key.length===1,oe)},de=async ee=>{if(ee.key==="Enter"){if(ee.nativeEvent.isComposing)return;if(f){const ue=f;x(""),u(`IME Sent: ${ue}`);try{const oe=await e("input_type",{text:ue});oe!=null&&oe.success||t(`❌ IME error: ${oe==null?void 0:oe.error}`)}catch(oe){t(`❌ IME error: ${oe.message}`)}}else u("Key: Enter"),await ye("Enter","Enter",!1)}};o.useEffect(()=>{const ee=c.current;if(!ee)return;const ue=oe=>{var q;if((q=d.current)!=null&&q.contains(oe.target)){oe.preventDefault();const V=Date.now();if(V-I.current<40)return;I.current=V;const le=we(oe.clientX,oe.clientY);if(!le)return;u(`Scroll: ${Math.round(oe.deltaY)}`),e("input_wheel",{nx:le.nx,ny:le.ny,deltaX:Math.round(oe.deltaX),deltaY:Math.round(oe.deltaY)}).catch(()=>{})}};return ee.addEventListener("wheel",ue,{passive:!1}),()=>ee.removeEventListener("wheel",ue)},[e]);const{cursorPos:je,handleToggleInputMode:me,handleZoomReset:pe}=Yu({containerRef:c,viewportRef:l,imgRef:d,inputMode:A,setInputMode:M,minZoom:te,zoomRef:W,panXRef:P,panYRef:$,setPanX:K,setPanY:N,setZoom:T,lastWheelTimeRef:I,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:X,clampPan:be,isMobile:k,mobileFillZoom:w});return s.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ne,onContextMenu:ee=>ee.preventDefault(),onFocus:()=>C(!0),onBlur:()=>C(!1),tabIndex:0,children:[s.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[J?s.jsx("img",{ref:d,src:J,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${_}) translate(${D}%, ${L}%)`,transformOrigin:"center center",cursor:A==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ce,onContextMenu:ee=>ee.preventDefault(),onDragStart:ee=>ee.preventDefault()}):s.jsx(Gu,{waitingLabel:he,waitingHint:ie,transportType:i}),A==="mouse"&&J&&s.jsx(zu,{cursorPos:je,viewportRef:l,imgRef:d}),g.map(ee=>{const oe={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ee.type];return s.jsxs("div",{style:{position:"absolute",left:ee.x,top:ee.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${oe}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),s.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${oe}, 0.9)`,boxShadow:`0 0 12px rgba(${oe}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ee.id)})]}),s.jsx(Vu,{inputMode:A,onToggleInputMode:me,isImeOpen:y,setIsImeOpen:S,isMenuOpen:b,setIsMenuOpen:h,imeText:f,setImeText:x,handleImeSubmit:de,isConnActive:H,zoom:_,isMobile:k,mobileFillZoom:w,onZoomOut:()=>T(ee=>Math.max(.5,ee-.25)),onZoomReset:pe,onZoomIn:()=>T(ee=>Math.min(5,ee+.25)),transportType:i,screenshotUsage:a,lastActionStatus:m}),s.jsx("style",{children:`
2
+ var kd=Object.defineProperty;var Sd=(e,t,r)=>t in e?kd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Qe=(e,t,r)=>Sd(e,typeof t!="symbol"?t+"":t,r);import{r as o,j as s,M as Ea,a as Nd,b as Cd,c as Td,R as Ct,d as ar,t as Md,e as Ad,u as $s,D as Id,f as ma,g as fa,h as $a,i as Rd,k as Ld,B as _d,l as Pd,m as Gt,N as pa,n as Dd}from"./vendor-CLec0455.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();function Ed(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(a),r.length>t&&r.splice(0,r.length-t),a},list(n={}){const a=Math.max(1,Math.floor(n.limit||100));return r.filter(i=>!n.interactionId||i.interactionId===n.interactionId).filter(i=>!n.topic||i.topic===n.topic).filter(i=>!n.kind||i.kind===n.kind).slice(-a).map(i=>({...i,payload:i.payload?{...i.payload}:{}}))},clear(){r.splice(0,r.length)}}}const Ms=Ed();function Po(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 $d(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Bd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Gi(e,t){if(!e)return t??null;if(!t)return e??null;const r=Bd(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:t.messages,a={...t,...e,activeModal:e.activeModal??null,inputContent:e.inputContent??t.inputContent};return r?{...a,messages:n}:a}function Xs(e,t){const r=$d(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:Gi(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 qi(e,t,r){if(!(t!=null&&t.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const n=t.map(a=>{const i=e.find(c=>c.id===a.id);return i?Xs(a,i):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(t.map(i=>i.id));for(const i of e)a.has(i.id)||n.push(i)}return n}function Do(e){return!!e&&typeof e=="object"&&"text"in e}function Ba(e,t){const r=(t==null?void 0:t.joiner)??" ",n=(t==null?void 0:t.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(i=>typeof i=="string"?i:Do(i)?String(i.text||""):"").join(r):Do(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function As(e){return Ba(e,{normalizeWhitespace:!0})}const Yi=o.createContext({ides:[],updateRouteChats:()=>{},initialLoaded:!1,toasts:[],setToasts:()=>{},wsStatus:"connected",isConnected:!0,connectionStates:{},connectionTransports:{},showReconnected:!1,userName:void 0,setUserName:()=>{},isP2PActive:!1,p2pStates:{},userRole:void 0,connectionRetryStatuses:void 0}),Xi=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Eo(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 Ji(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,i=t.serverVersion??e.serverVersion??r.serverVersion,c=t.versionMismatch===!0||e.versionMismatch===!0,l=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),i&&(n.serverVersion=i),d&&(n.versionUpdateReason=d),a&&i&&a===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||c&&a&&i&&a!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function Kd(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 Nn(e){if(!e||typeof e!="object")return"";const t=e,r=Kd(As(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 Wd(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=Nn(n);for(let i=0;i<a.length;i+=1)r^=a.charCodeAt(i),r=Math.imul(r,16777619)>>>0}return{count:e.length,hash:r.toString(16).padStart(8,"0"),first:Nn(e[0]),last:Nn(e[e.length-1])}}function ha(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function xa(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(ha(e)&&ha(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)xa(e[l],t[l],r);return}const n=e,a=t,i=new Set([...Object.keys(n),...Object.keys(a)]);for(const c of i)c!=="messages"&&xa(n[c],a[c],r)}function Qs(e,t){return Array.isArray(e)?e.map(r=>Qs(r,t)):!e||typeof e!="object"?e:ha(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Wd(a,t):Qs(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Qs(n,t)]))}function Od(e,t){try{const r=new WeakSet;return xa(e,t,r),JSON.stringify(Qs(e,r))===JSON.stringify(Qs(t,r))}catch{return!1}}function ba(e,t,r){return Od(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Qi(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Fd(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function $o(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,i=qi(e.childSessions,t.childSessions,{preserveMissing:n}),c=Gi(t.activeChat,e.activeChat);return Ji(e,t,{...e,...t,chats:a,childSessions:i,activeChat:c,_lastUpdate:r})}function Hd(e,t,r){var a,i;const n={};t.status&&t.status!==e.status&&(n.status=t.status),t.cdpConnected!==void 0&&(n.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(n.childSessions=qi(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((i=e.chats)!=null&&i.length)&&(n.chats=t.chats);for(const c of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])Fd(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Ud(e,t,r,n){const a=Hd(e,t,n),i=Object.keys(a).length>0?Ji(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return ba(e,i,r)}function zd(e){const t=new Set(e.map(i=>i.id)),r=new Set,n=new Set,a=new Set;for(const i of e){const c=Qi(i);c&&r.add(c),c&&i.type!=="adhdev-daemon"&&n.add(c),c&&i.type==="adhdev-daemon"&&i._sessionListAuthoritative&&a.add(c)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function Vd(e,t,r,n,a,i){return!a.has(t)||!i.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function Gd(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function qd(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(x=>({...x,_lastUpdate:n}));const i=new Map;for(const x of t)i.set(x.id,x);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:m}=zd(e);for(const x of e){const C=i.get(x.id);if(!C){i.set(x.id,{...x,_lastUpdate:n});continue}const y=Eo(x),p=Eo(C),g=Qi(x),b=!a.has(g);if(y>p){const S=$o(C,x,n,b);i.set(x.id,ba(C,S,n));continue}if(y<p){i.set(x.id,Ud(C,x,n,b));continue}const h=x.timestamp||n,k=C._lastUpdate||C.timestamp||0;if(h>=k){const S=$o(C,x,n,b);i.set(x.id,ba(C,S,n));continue}(u=x.chats)!=null&&u.length&&!((f=C.chats)!=null&&f.length)&&i.set(x.id,{...C,chats:x.chats})}for(const[x,C]of i){const y=C.daemonId||x.split(":")[0];if(!l.has(y))continue;if(a.has(y)&&m.has(y)&&!c.has(x)){i.delete(x);continue}const p=n-(C._lastUpdate||C.timestamp||0);Vd(C,y,p,c,a,d)&&i.delete(x)}for(const[x,C]of i){const y=C.daemonId||x.split(":")[0];if(Gd(C,y,l,d,i))continue;n-(C._lastUpdate||C.timestamp||0)>3e5&&C.status!=="online"&&i.delete(x)}return Array.from(i.values())}function Yd(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 Xd({children:e,connectionOverrides:t}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[d,m]=o.useState(void 0),u=o.useRef(r);o.useEffect(()=>{u.current=r},[r]);const f=o.useCallback((b,h)=>{n(k=>{let S=!1;const j=k.map(A=>A.id!==b||A.chats===h?A:(S=!0,{...A,chats:h}));return S?j:k})},[]),x=o.useCallback((b,h)=>{n(k=>{const S=k.length===0?b:qd(b,k,h),j=!Yd(k,S);return j&&Ms.record({kind:"dashboard.entries_applied",payload:{incoming:Po(b),next:Po(S)}}),j?S:k})},[]),C=o.useCallback(()=>i(!0),[]),y=o.useMemo(()=>({injectEntries:x,markLoaded:C,getIdes:()=>u.current}),[x,C]),p=t,g=o.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(Xi.Provider,{value:y,children:s.jsx(Yi.Provider,{value:g,children:e})})}function Qt(){return o.useContext(Yi)}function or(){return o.useContext(Xi)}function Zi(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function i(l){const d=r==null?void 0:r(),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),x=new AbortController,C=setTimeout(()=>x.abort(),15e3);try{const y=await fetch(f,{...d,headers:m,signal:x.signal});if(y.status===401)throw n==null||n(),new Error("Unauthorized");if(!y.ok){const p=await y.json().catch(()=>({error:y.statusText}));throw new Error(p.error||`API Error: ${y.status}`)}return y.json()}finally{clearTimeout(C)}}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=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Jd=Zi({baseUrl:"http://localhost:3847"}),Qd=o.createContext(Jd);function Zd({client:e,children:t}){return s.jsx(Qd.Provider,{value:e,children:t})}const eu={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},ec=o.createContext(eu);function tu({value:e,children:t}){return s.jsx(ec.Provider,{value:e,children:t})}function gt(){return o.useContext(ec)}function su(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 ru(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function nu(e){return e?su([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),ru(e.content)]):""}const Oe={size:18};function tc({size:e=Oe.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 Ka({size:e=Oe.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 Yt({size:e=Oe.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 sc({size:e=Oe.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 au({size:e=Oe.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 ou({size:e=Oe.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 rc({size:e=Oe.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 iu({size:e=Oe.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 un({size:e=Oe.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 nc({size:e=Oe.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 cu({size:e=Oe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Ut({size:e=Oe.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 Mt({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Wa({size:e=Oe.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 lu({size:e=Oe.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 ms({size:e=Oe.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 dr({size:e=Oe.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 ir({size:e=Oe.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 Is({size:e=Oe.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 wr({size:e=Oe.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 ac({size:e=Oe.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 Oa({size:e=Oe.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 oc({size:e=Oe.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 du({size:e=Oe.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 Fa({size:e=Oe.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 uu({size:e=Oe.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 Ha({size:e=Oe.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 ic({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function vt({size:e=Oe.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 mu({size:e=Oe.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 fu({size:e=Oe.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 pu({size:e=Oe.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 hu({size:e=Oe.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 mn({size:e=Oe.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 xu({size:e=Oe.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 bu({size:e=Oe.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 gu({size:e=Oe.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 yu({size:e=Oe.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 vu({size:e=Oe.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 wu({size:e=Oe.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 ju({size:e=Oe.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 ku({size:e=Oe.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 Su({size:e=Oe.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 Nu({size:e=Oe.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 Cu({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function Tu({size:e=Oe.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 cc=[Nd,{singleTilde:!1}],lc=[cc,Cd,Td],Mu=[cc],Ua=200,Au=80,Bo=650,Os=new Map;function Xr(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function Iu(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}:${nu(n)}`}function Ru(e,t,r,n){return e||!t?!1:Xr(r,n)}function Lu({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=Au,bottomThresholdPx:a=Ua}){const i=Math.max(0,Number(e)||0),c=Math.max(0,Number(t)||0),l=Math.max(0,Number(r)||0);return Math.max(0,c-l)<=0?{showTop:!1,showBottom:!1}:{showTop:i>n,showBottom:Math.max(0,c-i-l)>a}}function _u(e){return Lu({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Js(e,t=Ua){return!!e&&e.fromBottom>=t}function Pu(e,t){return Xr(e,t)?!Js(e):!0}function Du({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function Eu({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function Cn(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function dc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function $u(e,t,r){return Number(e.receivedAt||r[Jr(e,t)]||0)||0}function uc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Bu(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function jr(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 Tn(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 Ko(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):uc(e)?s.jsx(Ea,{remarkPlugins:lc,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function kr({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:Ko(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=Tn(r);return a?s.jsx("img",{src:a,alt:jr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=Tn(r);return a?s.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=Tn(r);return a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:jr(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||jr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=jr(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}),Ko(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 Jr(e,t){const r=e,n=Ba(e.content,{joiner:`
3
+ `});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${t}`].filter(Boolean).join("|")}const Ku=o.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Ea,{remarkPlugins:Mu,children:t.text}),s.jsx("span",{className:"action-time",children:dc(t.timestamp)})]})},(e,t)=>e.log===t.log),Wu=o.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var A,M,w;const d=(t.role||"").toLowerCase(),m=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),f=Bu(t.content)?t.content:null,x=!!(f!=null&&f.some(v=>v.type!=="text")),C=Ba(t.content,{joiner:`
4
+ `});if(u==="thought"){const v=typeof((A=t.meta)==null?void 0:A.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(pu,{size:13}),s.jsx("span",{children:v})]}),s.jsx("div",{className:"chat-msg-body",children:C})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),x&&f?s.jsx("div",{className:"tool-text w-full",children:s.jsx(kr,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:C})]});if(u==="terminal"){const v=(M=t.meta)!=null&&M.isRunning?"⏳":"✅",B=typeof((w=t.meta)==null?void 0:w.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:v}),s.jsx("span",{children:B})]}),x&&f?s.jsx("div",{className:"chat-msg-body",children:s.jsx(kr,{parts:f,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:C})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:x&&f?s.jsx(kr,{parts:f,renderAsPreformatted:!1}):C.slice(0,100)});const y=t.meta,g=(typeof(y==null?void 0:y.renderMode)=="string"?y.renderMode.trim():"")==="preformatted",b=C,h=!1,k=b,S=g,j=!S&&uc(k);return s.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${m?"self-end":"self-start"}`,children:(b||x||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${b||x?"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:dc(r)})]}),(b||x)&&s.jsx("div",{className:"chat-markdown",children:x&&f?s.jsx(kr,{parts:f,renderAsPreformatted:S}):S?s.jsx("pre",{className:"chat-preformatted",children:k}):j?s.jsx(Ea,{remarkPlugins:lc,children:k}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:k})}),h]})})},(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),Ou=o.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:d={},lastMessageHash:m,emptyState:u,onLoadMore:f,isLoadingMore:x,hasMoreHistory:C,hiddenLiveCount:y=0,loadError:p,scrollToBottomRequestNonce:g,isVisible:b=!0},h){const k=o.useRef(null),S=o.useRef(null),j=o.useRef(null),A=o.useRef(0),M=o.useRef(""),w=o.useRef(""),v=o.useRef(!1),B=o.useRef(null),_=o.useRef(!1),T=o.useRef(null),D=o.useRef(!1),[K,L]=o.useState(new Set),[N,I]=o.useState({showTop:!1,showBottom:!1}),F=o.useRef(!1),P=o.useRef(!1),$=o.useRef(b),H=o.useRef(b),J=o.useRef(null);H.current=b;const he=()=>{const q=k.current;return q?q.scrollHeight-q.scrollTop-q.clientHeight<Ua:!0},ie=o.useCallback(()=>{const q=k.current,V=q?_u(q):{showTop:!1,showBottom:!1};I(le=>le.showTop===V.showTop&&le.showBottom===V.showBottom?le:V)},[]),te=o.useCallback((q="auto")=>{var le;const V=k.current;V&&(V.scrollTo({top:V.scrollHeight,behavior:q}),(le=V.ownerDocument.defaultView)==null||le.requestAnimationFrame(()=>ie()))},[ie]),be=o.useCallback((q="auto")=>{var le;const V=k.current;V&&(V.scrollTo({top:0,behavior:q}),(le=V.ownerDocument.defaultView)==null||le.requestAnimationFrame(()=>ie()))},[ie]),we=o.useCallback(()=>{var Z;const q=k.current,V=(Z=window.getSelection)==null?void 0:Z.call(window);if(!q||!V||V.rangeCount===0||V.isCollapsed){D.current=!1;return}const le=V.anchorNode,ke=V.focusNode;D.current=!!(le&&ke&&q.contains(le)&&q.contains(ke))},[]),ge=Iu(t,m),X=o.useCallback(()=>{const q=k.current;if(!q||!l||!H.current)return;const V={top:q.scrollTop,fromBottom:Math.max(0,q.scrollHeight-q.scrollTop-q.clientHeight),messageFingerprint:ge};J.current={contextKey:l,snapshot:V},Os.set(l,V)},[l,ge]),ce=o.useCallback((q="auto")=>{B.current!=null&&cancelAnimationFrame(B.current),B.current=requestAnimationFrame(()=>{B.current=null,te(q)})},[te]),ye=o.useCallback(()=>{F.current=!1,_.current=!0,P.current=!0,T.current!=null&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{_.current=!1,T.current=null},Bo)},[]);o.useEffect(()=>{const q=!v.current,V=w.current!==l;if(w.current=l,q||V){v.current=!0;const ke=l?Os.get(l):null,Z=!!ke&&Xr(ke,ge);F.current=Z?Js(ke):!1,_.current=Pu(ke,ge),D.current||(Z?requestAnimationFrame(()=>{const De=k.current;De&&(Cn(De,ke),F.current=Js(ke),ie(),P.current=!0)}):ce("auto")),A.current=t.length,M.current=ge;return}t.length>A.current;const le=ge!==M.current;Du({hasSelection:D.current,userScrolledUp:F.current,hasChatContentChanged:le})&&ce("auto"),A.current=t.length,M.current=ge},[ge,l,t.length,ce,ie]),o.useEffect(()=>{g&&(ye(),D.current||ce("auto"))},[ye,ce,g]),o.useEffect(()=>{const q=$.current;q&&!b&&X(),H.current=b,$.current=b;const V=l?Os.get(l):null;if(Ru(q,b,V,ge)){if(!V)return;F.current=Js(V),_.current=!1,D.current||requestAnimationFrame(()=>{const le=k.current;le&&(Cn(le,V),ie())});return}},[b,l,ge,ye,X,ce,ie]),o.useEffect(()=>()=>{const q=J.current;q&&Os.set(q.contextKey,q.snapshot),B.current!=null&&cancelAnimationFrame(B.current),T.current!=null&&window.clearTimeout(T.current)},[]),o.useEffect(()=>{const q=S.current,V=k.current;if(!q||!V)return;const le=()=>{T.current!=null&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{_.current=!1,T.current=null},Bo)},ke=new ResizeObserver(()=>{ie();const Z=_.current;Eu({hasSelection:D.current,userScrolledUp:F.current,contextAutoScrollActive:Z})&&(ce("auto"),Z&&le())});return ke.observe(q),V!==q&&ke.observe(V),()=>{ke.disconnect(),T.current!=null&&(window.clearTimeout(T.current),T.current=null)}},[ce,l,ie]),o.useImperativeHandle(h,()=>({scrollToBottom:(q="smooth")=>{te(q)}}),[te]),o.useEffect(()=>{const q=k.current;if(!q)return;let V;const le=()=>{X(),clearTimeout(V),V=setTimeout(()=>{F.current=!he(),ie()},50)};return q.addEventListener("scroll",le,{passive:!0}),()=>{q.removeEventListener("scroll",le),clearTimeout(V)}},[X,ie]),o.useEffect(()=>(document.addEventListener("selectionchange",we),()=>document.removeEventListener("selectionchange",we)),[we]);const ne=o.useRef(0),de=o.useRef(!1);o.useEffect(()=>{const q=k.current;if(!q||!de.current||ne.current===0)return;const V=q.scrollHeight-ne.current;V>0&&(q.scrollTop=V),ie(),X(),ne.current=0,de.current=!1},[t.length,X,ie]),o.useEffect(()=>{if(P.current||!l)return;const q=Os.get(l),V=k.current;if(!(!q||!V)){if(!Xr(q,ge)){te("auto"),P.current=!0;return}Cn(V,q),F.current=Js(q),ie(),P.current=!0}},[l,ge,t.length,te,ie]);const je=()=>{const q=k.current;q&&(ne.current=q.scrollHeight),de.current=!0,f==null||f()},me=()=>{F.current=!0,be("smooth"),X()},pe=()=>{ye(),te("smooth"),X()},ee=o.useMemo(()=>{const q=t.map((Z,De)=>({type:"message",data:Z,index:De,ts:$u(Z,De,d)}));if(!r||r.length===0)return q;const V=[...r].sort((Z,De)=>Z.timestamp-De.timestamp).map((Z,De)=>({type:"action",data:Z,index:De,ts:Z.timestamp})),le=[];let ke=0;for(const Z of q){for(;ke<V.length&&Z.ts>0&&V[ke].ts<Z.ts;)le.push(V[ke++]);le.push(Z)}for(;ke<V.length;)le.push(V[ke++]);return le},[t,r,d]),ue=y>0||!!C,oe=y>0?`↑ Show ${Math.min(y,80)} earlier messages${y>80?` (${y} hidden)`:""}`:p?`↻ ${p}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:k,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:S,className:"chat-container-content",children:[x&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),ue&&!x&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:je,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${p&&y===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:oe})}),ee.length===0&&!ue&&(u||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ee.map(q=>{if(q.type==="action"){const Fe=q.data;return s.jsx(Ku,{log:Fe},`action-${q.index}`)}const V=q.data,le=q.index,ke=Jr(V,le),Z=V.receivedAt||d[ke],De=`${l}-${ke}`,$e=K.has(De);return s.jsx(Wu,{message:V,receivedAt:Z,agentName:n,userName:a,isCliMode:i,isTextExpanded:$e,onToggleTextExpanded:()=>L(Fe=>{const Ue=new Set(Fe);return $e?Ue.delete(De):Ue.add(De),Ue})},`msg-${ke}`)}),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:j})]})}),(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:pe,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Fu=o.memo(Ou,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.lastMessageHash===t.lastMessageHash&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible),Hu="modulepreload",Uu=function(e){return"/"+e},Wo={},zu=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=Uu(d),d in Wo)return;Wo[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":Hu,m||(f.as="script"),f.crossOrigin="",f.href=d,l&&f.setAttribute("nonce",l),document.head.appendChild(f),m)return new Promise((x,C)=>{f.addEventListener("load",x),f.addEventListener("error",()=>C(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};let Oo=!1;const mc=o.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:i="measured"},c)=>{const l=o.useRef(null),[d,m]=o.useState(null),u=o.useRef([]),f=o.useRef(!1),x=o.useRef(!1),C=o.useRef(!1),y=o.useRef(!1),p=()=>{const g=l.current;if(g){f.current&&(g.clear(),f.current=!1);for(const b of u.current)g.write(b.data,b.onProcessed);u.current=[],x.current&&(g.fit(),x.current=!1),C.current&&(g.bumpResize(),C.current=!1),y.current&&(g.scrollToTop(),y.current=!1)}};return o.useImperativeHandle(c,()=>({write:(g,b)=>{l.current?l.current.write(g,b):u.current.push({data:g,onProcessed:b})},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,b)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(g,b)},fit:()=>{l.current?l.current.fit():x.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():C.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():y.current=!0},getSelection:()=>{var g,b;return((b=(g=l.current)==null?void 0:g.getSelection)==null?void 0:b.call(g))||""},getVisibleText:()=>{var g,b;return((b=(g=l.current)==null?void 0:g.getVisibleText)==null?void 0:b.call(g))||""}}),[]),o.useEffect(()=>{d&&p()},[d]),o.useEffect(()=>{let g=!1;return zu(()=>import("./terminal-BeBmUW3m.js"),__vite__mapDeps([0,1,2])).then(b=>{Oo||(Oo=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),g||m(()=>b.GhosttyTerminalView)}).catch(b=>{console.error("[CliTerminal] failed to load terminal renderer",b)}),()=>{g=!0}},[]),d?s.jsx(d,{ref:l,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:i,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});mc.displayName="CliTerminal";function Sr({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 Fo({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:i=!1}){const c=t>0?Math.min(Math.round(e/t*100),100):0,l=c>85?"#ef4444":c>60?"var(--status-warning)":n;return i?s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),s.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[c,"%"]})]}),s.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${c}%`,background:l}})})]}):s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-1.5",children:[s.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),s.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[c,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${c}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function Vu({cursorPos:e,viewportRef:t,imgRef:r}){var h;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(h=t.current)==null?void 0:h.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,d=c/l,m=a.width/a.height;let u,f,x,C;d>m?(u=a.width,f=a.width/d,x=0,C=(a.height-f)/2):(f=a.height,u=a.height*d,x=(a.width-u)/2,C=0);const y=a.left-i.left+x+u*e.nx,p=a.top-i.top+C+f*e.ny,g=Math.max(8,Math.min(i.width-8,y)),b=Math.max(8,Math.min(i.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:g-8,top:b-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 Gu({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:f,mobileFillZoom:x,onZoomOut:C,onZoomReset:y,onZoomIn:p,transportType:g,screenshotUsage:b,lastActionStatus:h}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:k=>k.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(k=>!k),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:k=>k.stopPropagation(),onChange:k=>l(k.target.value),onKeyDown:k=>{d(k)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{i(k=>!k),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"}),b&&b.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:b.budgetExhausted?"#ef4444":"#c4b5fd",background:b.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:b.budgetExhausted?"TURN blocked":`TURN ${b.dailyUsedMinutes}/${b.dailyBudgetMinutes}m`}),h&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:h})]})]}),a&&s.jsxs("div",{onTouchStart:k=>k.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?x:1)+.01?f?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:k=>{k.stopPropagation(),C()},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:k=>{k.stopPropagation(),y()},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:k=>{k.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 qu({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 Yu(){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 Ho(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 ur(e,t){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!Yu())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,Ho(l)]))}),r.current=t;return}const i=Object.keys({...a,...t}).filter(c=>!Object.is(a[c],t[c]));i.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(c=>[c,Ho(t[c])]))}),r.current=t})}function Xu({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:d,setPanX:m,setPanY:u,setZoom:f,lastWheelTimeRef:x,onAction:C,setLastActionStatus:y,spawnRippleFromNormalized:p,clampPan:g,isMobile:b,mobileFillZoom:h}){const[k,S]=o.useState(null),j=o.useRef(null),A=o.useRef(null),M=o.useRef(null),w=o.useRef(!1),v=o.useRef(null),B=o.useRef(0),_=o.useRef(null),T=o.useRef(1),D=o.useRef({x:0,y:0}),K=o.useRef(!1),L=o.useRef(n),N=o.useRef(C),I=30,F=550,P=18,$=60,H=400,J=12,he=()=>{if(j.current)return;const be={nx:.5,ny:.5};j.current=be,S(be)};return o.useEffect(()=>{L.current=n,n==="mouse"&&he()},[n]),o.useEffect(()=>{N.current=C},[C]),o.useEffect(()=>{const be=e.current;if(!be)return;const we=de=>{if(!r.current)return null;const je=r.current.getBoundingClientRect();return!je.width||!je.height?null:{nx:Math.max(0,Math.min(1,(de.clientX-je.left)/je.width)),ny:Math.max(0,Math.min(1,(de.clientY-je.top)/je.height))}},ge=(de,je)=>{if(!r.current)return{dnx:0,dny:0};const me=r.current,pe=me.getBoundingClientRect(),ee=me.naturalWidth||pe.width,ue=me.naturalHeight||pe.height,oe=ee/ue,q=pe.width/pe.height;let V,le;return oe>q?(V=pe.width,le=pe.width/oe):(le=pe.height,V=pe.height*oe),{dnx:de/V,dny:je/le}},X=(de,je,me)=>{if(me<=1.05)return;const pe=-(de-.5)*100,ee=-(je-.5)*100,ue=g(pe,ee,me);(Math.abs(ue.x-l.current)>.1||Math.abs(ue.y-d.current)>.1)&&(m(ue.x),u(ue.y),l.current=ue.x,d.current=ue.y)},ce=de=>{const je=t.current;if(je&&de.target instanceof Node&&je.contains(de.target))de.preventDefault();else return;if(de.touches.length===1){const me=de.touches[0];A.current={x:me.clientX,y:me.clientY,time:Date.now()},M.current={x:me.clientX,y:me.clientY},K.current||(w.current=!1),v.current=setTimeout(()=>{if(!w.current&&!K.current)if(w.current=!0,L.current==="mouse"){const pe=j.current||{nx:.5,ny:.5};y("Right Click"),p(pe.nx,pe.ny,"right"),N.current("input_click",{...pe,button:"right"}).catch(()=>{})}else{const pe=we(me);pe&&(y("Right Click"),p(pe.nx,pe.ny,"right"),N.current("input_click",{...pe,button:"right"}).catch(()=>{}))}},500);return}if(de.touches.length===2){v.current&&clearTimeout(v.current),w.current=!0,K.current=!0;const me=de.touches[1].clientX-de.touches[0].clientX,pe=de.touches[1].clientY-de.touches[0].clientY;_.current=Math.sqrt(me*me+pe*pe),T.current=c.current,D.current={x:(de.touches[0].clientX+de.touches[1].clientX)/2,y:(de.touches[0].clientY+de.touches[1].clientY)/2}}},ye=de=>{const je=t.current;if(je&&de.target instanceof Node&&je.contains(de.target)&&de.preventDefault(),de.touches.length===1&&M.current){const me=de.touches[0],pe=me.clientX-M.current.x,ee=me.clientY-M.current.y;if(!w.current&&A.current){const ue=me.clientX-A.current.x,oe=me.clientY-A.current.y;Math.sqrt(ue*ue+oe*oe)>8&&(w.current=!0,v.current&&clearTimeout(v.current))}if(w.current)if(L.current==="mouse"){const ue=ge(pe,ee),oe=j.current||{nx:.5,ny:.5},q=Math.max(0,Math.min(1,oe.nx+ue.dnx)),V=Math.max(0,Math.min(1,oe.ny+ue.dny));j.current={nx:q,ny:V},S({nx:q,ny:V}),y(`Cursor: ${Math.round(q*100)}%, ${Math.round(V*100)}%`),X(q,V,c.current);const le=Date.now();le-x.current>=30&&(x.current=le,N.current("input_mouseMoved",{nx:q,ny:V}).catch(()=>{}))}else if(c.current>1){const ue=t.current;if(ue){const oe=ue.clientWidth,q=ue.clientHeight,V=l.current+pe/oe*100,le=d.current+ee/q*100,ke=g(V,le,c.current);m(ke.x),u(ke.y),l.current=ke.x,d.current=ke.y}}else{const ue=we(me);if(ue){const oe=Date.now();oe-x.current>=40&&(x.current=oe,y("Scroll"),N.current("input_wheel",{nx:ue.nx,ny:ue.ny,deltaX:Math.round(-pe*2.5),deltaY:Math.round(-ee*2.5)}).catch(()=>{}))}}M.current={x:me.clientX,y:me.clientY};return}if(de.touches.length===2&&_.current!==null){const me=de.touches[1].clientX-de.touches[0].clientX,pe=de.touches[1].clientY-de.touches[0].clientY,ue=Math.sqrt(me*me+pe*pe)/_.current,oe=(de.touches[0].clientX+de.touches[1].clientX)/2,q=(de.touches[0].clientY+de.touches[1].clientY)/2,V=oe-D.current.x,le=q-D.current.y,ke=Math.abs(ue-1)>.03;if(L.current==="mouse"){if(ke){const Z=Math.max(i,Math.min(5,T.current*ue));f(Z),c.current=Z}else if(Math.abs(V)>2||Math.abs(le)>2){const Z=j.current||{nx:.5,ny:.5},De=Date.now();De-x.current>=30&&(x.current=De,y("Scroll"),N.current("input_wheel",{nx:Z.nx,ny:Z.ny,deltaX:Math.round(-V*3),deltaY:Math.round(-le*3)}).catch(()=>{}))}}else{const Z=Math.max(i,Math.min(5,T.current*ue));f(Z),c.current=Z;const De=t.current;if(De&&Z>1){const $e=De.clientWidth,Fe=De.clientHeight,Ue=l.current+V/$e*100,W=d.current+le/Fe*100,Ce=g(Ue,W,Z);m(Ce.x),u(Ce.y),l.current=Ce.x,d.current=Ce.y}}D.current={x:oe,y:q}}},ne=de=>{var je;if(v.current&&clearTimeout(v.current),_.current=null,de.touches.length===1&&K.current){const me=de.touches[0];A.current={x:me.clientX,y:me.clientY,time:Date.now()},M.current={x:me.clientX,y:me.clientY},w.current=!0;return}if(de.touches.length===0){if(K.current){K.current=!1,w.current=!1;return}if(de.changedTouches.length===1){const me=de.changedTouches[0],pe=Date.now(),ee=pe-(((je=A.current)==null?void 0:je.time)||0),ue=A.current?me.clientX-A.current.x:0,oe=A.current?me.clientY-A.current.y:0,q=Math.sqrt(ue*ue+oe*oe);if(L.current==="mouse"){if(ee<I||ee>F||q>P){w.current=!1;return}const V=j.current||we(me);V&&(y(`Click: ${Math.round(V.nx*100)}%, ${Math.round(V.ny*100)}%`),p(V.nx,V.ny,"left"),N.current("input_click",{...V}).catch(()=>{}))}else{if(w.current){w.current=!1;return}if(ee<$||ee>H||q>J){w.current=!1;return}const V=we(me);if(!V)return;pe-B.current<300?(y("Double tap"),p(V.nx,V.ny,"double"),N.current("input_click",{...V,clickCount:2}).catch(()=>{}),B.current=0):(y(`Tap: ${Math.round(V.nx*100)}%, ${Math.round(V.ny*100)}%`),p(V.nx,V.ny,"left"),N.current("input_click",{...V}).catch(()=>{}),B.current=pe)}}w.current=!1}};return be.addEventListener("touchstart",ce,{passive:!1}),be.addEventListener("touchmove",ye,{passive:!1}),be.addEventListener("touchend",ne,{passive:!1}),()=>{be.removeEventListener("touchstart",ce),be.removeEventListener("touchmove",ye),be.removeEventListener("touchend",ne),v.current&&clearTimeout(v.current)}},[e,t,r,i,c,l,d,m,u,f,x,y,p,g]),{cursorPos:k,cursorPosRef:j,handleToggleInputMode:()=>{a(be=>{const we=be==="touch"?"mouse":"touch";return we==="mouse"&&he(),we})},handleZoomReset:()=>{const be=b?h:1;f(be),c.current=be,m(0),u(0),l.current=0,d.current=0}}}function fc({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),d=o.useRef(null),[m,u]=o.useState(null),[f,x]=o.useState(""),[,C]=o.useState(!1),[y,p]=o.useState([]),g=o.useRef(0),[b,h]=o.useState(!1),[k,S]=o.useState(!1),j=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[A,M]=o.useState(j?"mouse":"touch"),[w,v]=o.useState(1),B=o.useRef(!1),[_,T]=o.useState(1),[D,K]=o.useState(0),[L,N]=o.useState(0);ur("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:A,zoom:_,panX:D,panY:L,isMenuOpen:b,isImeOpen:k});const I=o.useRef(0),F=o.useRef(_),P=o.useRef(D),$=o.useRef(L);o.useEffect(()=>{F.current=_},[_]),o.useEffect(()=>{P.current=D},[D]),o.useEffect(()=>{$.current=L},[L]),o.useEffect(()=>{var ee;(ee=c.current)==null||ee.focus()},[]);const H=r==="connected",J=n,he=H?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ie=H?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!j||B.current||!J)return;const ee=d.current,ue=l.current;if(!ee||!ue)return;const oe=()=>{const q=ue.clientWidth,V=ue.clientHeight,le=ee.naturalWidth,ke=ee.naturalHeight;if(!le||!ke||!q||!V)return;const Z=Math.min(q/le,V/ke),$e=Math.max(q/le,V/ke)/Z;$e>1.01&&(v($e),T($e),F.current=$e),B.current=!0};ee.complete&&ee.naturalWidth?oe():ee.addEventListener("load",oe,{once:!0})},[J,j]);const te=.5;o.useEffect(()=>{_<=te&&(K(0),N(0))},[_,te]);const be=(ee,ue,oe)=>{if(oe<=te)return{x:0,y:0};const q=(oe-1)/(2*oe)*100,V=(oe-1)/(2*oe)*100;return{x:Math.max(-q,Math.min(q,ee)),y:Math.max(-V,Math.min(V,ue))}},we=(ee,ue)=>{if(!d.current)return null;const oe=d.current.getBoundingClientRect();return!oe.width||!oe.height?null:{nx:Math.max(0,Math.min(1,(ee-oe.left)/oe.width)),ny:Math.max(0,Math.min(1,(ue-oe.top)/oe.height))}},ge=(ee,ue,oe)=>{const q=l.current;if(!q)return;const V=q.getBoundingClientRect(),le=++g.current;p(ke=>[...ke,{id:le,x:ee-V.left,y:ue-V.top,type:oe}]),setTimeout(()=>p(ke=>ke.filter(Z=>Z.id!==le)),600)},X=(ee,ue,oe)=>{const q=d.current,V=l.current;if(!q||!V)return;const le=q.getBoundingClientRect(),ke=V.getBoundingClientRect(),Z=q.naturalWidth||le.width,De=q.naturalHeight||le.height,$e=Z/De,Fe=le.width/le.height;let Ue,W,Ce,Te;$e>Fe?(Ue=le.width,W=le.width/$e,Ce=0,Te=(le.height-W)/2):(W=le.height,Ue=le.height*$e,Ce=(le.width-Ue)/2,Te=0);const _e=le.left-ke.left+Ce+Ue*ee,Be=le.top-ke.top+Te+W*ue,He=++g.current;p(Xe=>[...Xe,{id:He,x:_e,y:Be,type:oe}]),setTimeout(()=>p(Xe=>Xe.filter(st=>st.id!==He)),600)},ce=async ee=>{var oe;const ue=we(ee.clientX,ee.clientY);if(ue){u(`Click: ${Math.round(ue.nx*100)}%, ${Math.round(ue.ny*100)}%`),ge(ee.clientX,ee.clientY,"left"),(oe=c.current)==null||oe.focus();try{const q=await e("input_click",{nx:ue.nx,ny:ue.ny});q!=null&&q.success||t(`❌ Click failed: ${q==null?void 0:q.error}`)}catch(q){t(`❌ Click error: ${q.message||q}`)}}},ye=async(ee,ue,oe,q=0)=>{try{await e("input_key",{type:oe?"char":"keyDown",key:ee,code:ue,text:oe?ee:void 0,unmodifiedText:oe?ee:void 0,modifiers:q})}catch(V){t(`❌ Key error: ${V.message||V}`)}},ne=async ee=>{if(ee.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ee.key)&&ee.preventDefault();let oe=0;ee.altKey&&(oe|=1),ee.ctrlKey&&(oe|=2),ee.metaKey&&(oe|=4),ee.shiftKey&&(oe|=8),u(`Key: ${ee.key}`),await ye(ee.key,ee.code,ee.key.length===1,oe)},de=async ee=>{if(ee.key==="Enter"){if(ee.nativeEvent.isComposing)return;if(f){const ue=f;x(""),u(`IME Sent: ${ue}`);try{const oe=await e("input_type",{text:ue});oe!=null&&oe.success||t(`❌ IME error: ${oe==null?void 0:oe.error}`)}catch(oe){t(`❌ IME error: ${oe.message}`)}}else u("Key: Enter"),await ye("Enter","Enter",!1)}};o.useEffect(()=>{const ee=c.current;if(!ee)return;const ue=oe=>{var q;if((q=d.current)!=null&&q.contains(oe.target)){oe.preventDefault();const V=Date.now();if(V-I.current<40)return;I.current=V;const le=we(oe.clientX,oe.clientY);if(!le)return;u(`Scroll: ${Math.round(oe.deltaY)}`),e("input_wheel",{nx:le.nx,ny:le.ny,deltaX:Math.round(oe.deltaX),deltaY:Math.round(oe.deltaY)}).catch(()=>{})}};return ee.addEventListener("wheel",ue,{passive:!1}),()=>ee.removeEventListener("wheel",ue)},[e]);const{cursorPos:je,handleToggleInputMode:me,handleZoomReset:pe}=Xu({containerRef:c,viewportRef:l,imgRef:d,inputMode:A,setInputMode:M,minZoom:te,zoomRef:F,panXRef:P,panYRef:$,setPanX:K,setPanY:N,setZoom:T,lastWheelTimeRef:I,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:X,clampPan:be,isMobile:j,mobileFillZoom:w});return s.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ne,onContextMenu:ee=>ee.preventDefault(),onFocus:()=>C(!0),onBlur:()=>C(!1),tabIndex:0,children:[s.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[J?s.jsx("img",{ref:d,src:J,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${_}) translate(${D}%, ${L}%)`,transformOrigin:"center center",cursor:A==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ce,onContextMenu:ee=>ee.preventDefault(),onDragStart:ee=>ee.preventDefault()}):s.jsx(qu,{waitingLabel:he,waitingHint:ie,transportType:i}),A==="mouse"&&J&&s.jsx(Vu,{cursorPos:je,viewportRef:l,imgRef:d}),y.map(ee=>{const oe={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ee.type];return s.jsxs("div",{style:{position:"absolute",left:ee.x,top:ee.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${oe}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),s.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${oe}, 0.9)`,boxShadow:`0 0 12px rgba(${oe}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ee.id)})]}),s.jsx(Gu,{inputMode:A,onToggleInputMode:me,isImeOpen:k,setIsImeOpen:S,isMenuOpen:b,setIsMenuOpen:h,imeText:f,setImeText:x,handleImeSubmit:de,isConnActive:H,zoom:_,isMobile:j,mobileFillZoom:w,onZoomOut:()=>T(ee=>Math.max(.5,ee-.25)),onZoomReset:pe,onZoomIn:()=>T(ee=>Math.min(5,ee+.25)),transportType:i,screenshotUsage:a,lastActionStatus:m}),s.jsx("style",{children:`
5
5
  @keyframes slideUp {
6
6
  from { opacity: 0; transform: translateY(6px); }
7
7
  to { opacity: 1; transform: translateY(0); }
@@ -24,9 +24,9 @@ var jd=Object.defineProperty;var kd=(e,t,r)=>t in e?jd(e,t,{enumerable:!0,config
24
24
  50% { transform: translateY(-7px); }
25
25
  100% { transform: translateY(0px); }
26
26
  }
27
- `})]})}function mn(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,i=Date.now()-e,c=Math.floor(i/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const d=Math.floor(l/60);if(d<24)return`${d}h${r}`;const m=Math.floor(d/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const mc=e=>mn(e);function Xu(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 Bs(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 Ju(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...Xu(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 Qr(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 fn(e,t,r){const n=Qr(e,t),a=Bs(e),i=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,x=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:x,requiresAction:m,isWorking:u,isReconnecting:i,isConnecting:c,isGenerating:l,isWaiting:d,inboxBucket:m?"needs_attention":u?"working":x?"task_complete":"idle"}}function Qu(e,t,r){return fn(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function fc({activeConv:e,onModalButton:t}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Bs(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),t(l))},c=l=>l.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&s.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(ir,{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),x=r===l,C=r!==null;return s.jsx("button",{onClick:()=>i(l),disabled:C,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"} ${C&&!x?"opacity-40":"opacity-100"} ${C?"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:x?"⏳ ...":c(l)},d)})})]})]})}const Ua="adhdev_controls_bar_visible",ba="adhdev:controlsbarvisibilitychange";function Tn(e){if(!e)return!1;try{return e.getItem(Ua)==="1"}catch{return!1}}function Zu(e,t){if(t)try{t.setItem(Ua,e?"1":"0")}catch{}}function em(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ba,{detail:{visible:e}}))}function za(){const[e,t]=o.useState(()=>typeof window>"u"?!1:Tn(window.localStorage)),r=o.useRef(e),n=o.useCallback((c,l=!0)=>{r.current=c,t(c),typeof window<"u"&&Zu(c,window.localStorage),l&&em(c)},[]);o.useEffect(()=>{const c=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:Tn(window.localStorage);r.current=u,t(u)},l=d=>{if(d.key!==Ua)return;const m=Tn(window.localStorage);r.current=m,t(m)};return window.addEventListener(ba,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ba,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{n(c)},[n]),i=o.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:i}}var tm=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function sm(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function jt(e,t){if(sm(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":tm.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 pc(e){return jt(e)==="generating"}function it(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function rm(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const r=Math.floor(t/60),n=t%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),i=r%24;return`${a}d ${i}h`}function Mn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function pn(e,t){const r=typeof t=="string"?t.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),i=a.split(/[\\/]/).filter(Boolean);return i[i.length-1]||a}function nm(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 am(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function om(e){return nm(e.trim().replace(/\.local$/i,""))}function im(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function hc(e,t={}){var a,i;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(i=e.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!am(c));if(r&&r!=="Unknown")return om(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Tt(e,t={}){return im(e)||hc(e,t)}function xc(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 bc(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function fs(e,t){return xc(e).join(" · ")}function cr(e){return e.transport==="pty"}function Ns(e){return e.transport==="acp"}function cm(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:it(e)}function Ho(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=it(r||"").trim().toLowerCase();return n===a||n===i||n===c}function lm(e){return jt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function dm(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=t.get(a),c=jt(n.status);if(!i){t.set(a,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),d=r.indexOf(c||"idle");d>=0&&(l<0||d<l)&&t.set(a,{...n,status:c})}return Array.from(t.values())}function um(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function mm(e){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&&um(t.receivedAt)||0}function fm(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ga(e){return Math.max(fm(e),mm(e.activeChat))}function pm(e,t,r,n,a,i){const c=t-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(i)}function Va(e,t){return pm(ga(e),ga(t),Tt(e,{fallbackId:e.id}),Tt(t,{fallbackId:t.id}),e.id,t.id)}const gc="adhdev_notification_prefs",Uo={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function hm(){try{const e=localStorage.getItem(gc);if(e){const t=JSON.parse(e);return{...Uo,...t}}}catch{}return{...Uo}}function xm(e){try{localStorage.setItem(gc,JSON.stringify(e))}catch{}}let Ot=hm(),Kr=[];function bm(){Kr.forEach(e=>e())}function gm(e){Ot={...Ot,...e},xm(Ot),bm()}function ym(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Kr.push(r),()=>{Kr=Kr.filter(n=>n!==r)}},[]);const t=o.useCallback(r=>{gm(r)},[]);return[{...Ot},t]}function Zs(e){if(!Ot.globalEnabled)return!1;switch(e){case"disconnect":return Ot.disconnectAlert;case"completion":return Ot.completionAlert;case"approval":return Ot.approvalAlert;case"browser":return Ot.browserNotifications;default:return!0}}const vm={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function yc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function vc(){return"Notification"in window&&Notification.permission==="granted"}let Zt=null;function wm(e){return e!==!1}async function jm(){if(Zt!==null)return Zt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Zt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Zt=!!await e.pushManager.getSubscription(),Zt):(Zt=!1,!1)}catch{return Zt=!1,!1}}function ya(e,t,r){if(vc())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 km(e,t={}){const r={...vm,...t},n=o.useRef(new Map),a=o.useRef(0),[i,c]=o.useState(null);o.useEffect(()=>{let d=!1;return jm().then(m=>{d||c(m)}),()=>{d=!0}},[]);const l=o.useCallback((d,m,u)=>{const f=Date.now();f-a.current<r.throttleMs||(a.current=f,ya(d,m,u))},[r.throttleMs]);o.useEffect(()=>{var d;if(!(!r.enabled||!vc())&&Zs("browser")&&!wm(i)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,jt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const u=n.current.get(m.id),f=jt(m.status,{activeModal:m.activeModal}),x=m.name||m.id;if(r.onApproval&&Zs("approval")&&f==="waiting_approval"&&u!=="waiting_approval"){const C=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";l(`🔔 ${x} — Approval needed`,C.slice(0,120),`approval-${m.id}`)}r.onComplete&&Zs("completion")&&pc(u)&&f==="idle"&&l(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&f==="error"&&u!=="error"&&l(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,f)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,i,l])}const Sm=/^(run|approve|accept|yes|allow|always)/,Nm=/^(run|approve|accept|yes|allow|always|proceed|save)/,Cm=/^(reject|deny|delete|remove|abort|cancel|no)/;function Ga(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Tm(e){const t=Ga(e).toLowerCase();return Sm.test(t)?"primary":Cm.test(t)?"danger":"default"}function Mm(e){return Nm.test(Ga(e).toLowerCase())?"approve":"reject"}function Am(e){return e.map((t,r)=>({label:Ga(t),variant:Tm(t),action:Mm(t),button:t,buttonIndex:r}))}function Im(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Rm(e,t,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,t,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,t,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class Lm{constructor(){Qe(this,"dedupMap",new Map);Qe(this,"DEDUP_WINDOW_MS",5e3);Qe(this,"DEDUP_MAX_SIZE",50);Qe(this,"DEDUP_CLEANUP_AGE_MS",1e4);Qe(this,"toastCallbacks",[]);Qe(this,"resolveActionFn",null);Qe(this,"viewRequestRespondFn",null);Qe(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(i=>i.id===t.daemonId&&i.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const i=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var g;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),i=n||t.daemonId||"",c=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),l=`${i}:${t.event}:${c}`;if(this.isDuplicate(l))return;const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(d==null?void 0:d.type)||"";let u=it(m);const f=this.resolveOwningDaemon(t);if(f){const p=Tt(f,{fallbackId:f.id});p&&(u=!m||m==="adhdev-daemon"?p:`${p}/${u}`)}let x="",C="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";x=`✅ ${u} agent task completed${p}`,C="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(x=`⚡ ${u} approval needed`,C="warning",(g=t.modalButtons)!=null&&g.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const j=this.resolveActionFn,b=Am(t.modalButtons).map(S=>({label:S.label,variant:S.variant,onClick:()=>{j(p,"resolve_action",{action:S.action,button:S.button,buttonIndex:S.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),h=Im(u,t.modalMessage,x),y=Date.now();this.emitToast({id:y,message:h,type:C,timestamp:y,targetKey:n||p,actions:b,duration:15e3}),x=""}}else if(t.event==="monitor:long_generating"){const p=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";x=`⚠️ ${u} agent is taking a long time${p}`,C="warning",Zs("browser")&&!document.hasFocus()&&ya(`⚠️ ${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",j=t.requestId,b=t.orgId;if(x=`👁️ ${p} wants to view your session`,C="warning",j&&b&&this.viewRequestRespondFn){const h=Date.now(),y=Rm(b,j,this.viewRequestRespondFn,(S,k)=>console.error(`[EventManager] ${S} view request failed:`,k));this.emitToast({id:h,message:x,type:C,timestamp:h,actions:y,duration:3e4}),x=""}Zs("browser")&&!document.hasFocus()&&ya("👁️ View Request",`${p} wants to view your session`,`view-request-${j}`)}else t.event==="team:view_request_approved"?(x="✅ View request approved",C="success"):t.event==="team:view_request_rejected"&&(x=`❌ ${t.targetName||"Team member"} declined your view request`,C="warning");if(x){const p=Date.now();this.emitToast({id:p,message:x,type:C,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const at=new Lm,zo=new Map;function Zr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Cs(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function hn(e){return Zr(e)?Zr(e.result)?e.result:e:null}function _m(e){const t=hn(e);return!t||!Zr(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Nr(e){const t=hn(e);return!t||!Zr(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Fs(e){const t=hn(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Cr(e){const t=hn(e);return!!t&&t.success===!1}function Pm(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";at.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";at.showToast(n.notification.body,a)}}}function Dm(e,t){return e&&Cs(e.currentValue)?e.currentValue:t}function Em(e,t){return Cs(t)?Cs(e)?typeof e=="string"&&e.trim()==="":!0:!1}function $m(e,t){var i,c;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(Cs(l))return l}const n=(i=t.controlValues)==null?void 0:i[e];if(Cs(n))return n;const a=(c=t.defaultValues)==null?void 0:c[e];return Cs(a)?a:void 0}function Wr(e,t){return e.options||t[e.id]||[]}const Bm={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 Km(e,t,r){var n;return((n=Bm[t])==null?void 0:n.has(r.id))===!0}function qa(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Km(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function An(e,t){return{value:t}}function Wm(e,t,r){var a;return r?((a=Wr(e,t).find(i=>i.value===r))==null?void 0:a.label)||r:""}const Om={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Fm({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=bt(),d=`${e}:${t||n}`,m=Om[n]||"#94a3b8",[u,f]=o.useState({}),x=o.useRef({}),C=o.useRef(c);x.current=u,C.current=c;const g=o.useRef(0),p={};for(const I of i||[])I.defaultValue!==void 0&&(p[I.id]=I.defaultValue);const j={...p,...c||{},...Date.now()<g.current?u:{}};o.useEffect(()=>{c&&Date.now()>g.current&&f({})},[c]);const[b,h]=o.useState(zo.get(d)||{}),[y,S]=o.useState(null),[k,A]=o.useState(null),M=o.useCallback(async(I,W={})=>{const P={...W,...t&&{targetSessionId:t}};return await l(e,I,P)},[e,t,l]),w=o.useCallback(async(I,W={})=>{const P=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await M("invoke_provider_script",{...P,scriptName:I,...W})},[M,n,r,t]),v=o.useCallback((I,W,P)=>{const $=Dm(P,W);f(H=>({...H,[I.id]:$})),Pm(P==null?void 0:P.effects)},[]),B=o.useCallback((I,W)=>{f(P=>{const $={...P};return W===void 0?delete $[I.id]:$[I.id]=W,$}),g.current=0},[]);if(!i||i.length===0)return null;const _=qa(i,{hostIdeType:r,providerType:n});if(_.length===0)return null;const T=async I=>{if(y===I.id){S(null);return}if(Wr(I,b).length>0){S(I.id);return}if(I.dynamic&&I.listScript){A(I.id);try{const P=await w(I.listScript,{}),$=_m(P);if(!$){const he=Fs(P);he&&at.showToast(he,"warning");return}const H=$.options;h(he=>{const ie={...he,[I.id]:H};return zo.set(d,ie),ie});const J=$m(I.id,{localOverrideUntil:g.current,localValues:x.current,controlValues:C.current,defaultValues:p});if(Em(J,$.currentValue)){const he=$.currentValue;f(ie=>({...ie,[I.id]:he}))}S(I.id)}catch(P){const $=P instanceof Error?P.message:`Could not load ${I.label}`;at.showToast($,"warning")}finally{A(null)}}},D=async(I,W)=>{S(null);const P=(c==null?void 0:c[I.id])??p[I.id];f($=>({...$,[I.id]:W})),g.current=Date.now()+5e3;try{if(!I.setScript)return;const $=await w(I.setScript,An(I,W)),H=Nr($);if(H&&!H.ok||Cr($))throw new Error((H==null?void 0:H.error)||Fs($)||`Could not update ${I.label}`);v(I,W,H)}catch($){B(I,P);const H=$ instanceof Error?$.message:`Could not update ${I.label}`;at.showToast(H,"warning")}},K=async I=>{const W=Wr(I,b).map(ie=>ie.value);if(W.length===0)return;const P=String(j[I.id]||""),H=(W.indexOf(P)+1)%W.length,J=W[H];if(typeof J!="string")return;const he=(c==null?void 0:c[I.id])??p[I.id];f(ie=>({...ie,[I.id]:J})),g.current=Date.now()+5e3;try{if(!I.setScript)return;const ie=await w(I.setScript,An(I,J)),te=Nr(ie);if(te&&!te.ok||Cr(ie))throw new Error((te==null?void 0:te.error)||Fs(ie)||`Could not update ${I.label}`);v(I,J,te)}catch(ie){B(I,he);const te=ie instanceof Error?ie.message:`Could not update ${I.label}`;at.showToast(te,"warning")}},L=async I=>{const P=!j[I.id],$=(c==null?void 0:c[I.id])??p[I.id];f(H=>({...H,[I.id]:P})),g.current=Date.now()+5e3;try{if(!I.setScript)return;const H=await w(I.setScript,An(I,P)),J=Nr(H);if(J&&!J.ok||Cr(H))throw new Error((J==null?void 0:J.error)||Fs(H)||`Could not update ${I.label}`);v(I,P,J)}catch(H){B(I,$);const J=H instanceof Error?H.message:`Could not update ${I.label}`;at.showToast(J,"warning")}},N=async I=>{if(!I.invokeScript)return;if(I.confirmMessage){const P=[I.confirmTitle,I.confirmMessage,I.confirmLabel].filter(H=>typeof H=="string"&&H.trim().length>0);if(!window.confirm(P.join(`
27
+ `})]})}function fn(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,i=Date.now()-e,c=Math.floor(i/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const d=Math.floor(l/60);if(d<24)return`${d}h${r}`;const m=Math.floor(d/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const pc=e=>fn(e);function Ju(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 Bs(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 Qu(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...Ju(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 Qr(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 pn(e,t,r){const n=Qr(e,t),a=Bs(e),i=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,x=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:x,requiresAction:m,isWorking:u,isReconnecting:i,isConnecting:c,isGenerating:l,isWaiting:d,inboxBucket:m?"needs_attention":u?"working":x?"task_complete":"idle"}}function Zu(e,t,r){return pn(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function hc({activeConv:e,onModalButton:t}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Bs(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),t(l))},c=l=>l.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&s.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(ir,{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),x=r===l,C=r!==null;return s.jsx("button",{onClick:()=>i(l),disabled:C,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"} ${C&&!x?"opacity-40":"opacity-100"} ${C?"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:x?"⏳ ...":c(l)},d)})})]})]})}const za="adhdev_controls_bar_visible",ga="adhdev:controlsbarvisibilitychange";function Mn(e){if(!e)return!1;try{return e.getItem(za)==="1"}catch{return!1}}function em(e,t){if(t)try{t.setItem(za,e?"1":"0")}catch{}}function tm(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ga,{detail:{visible:e}}))}function Va(){const[e,t]=o.useState(()=>typeof window>"u"?!1:Mn(window.localStorage)),r=o.useRef(e),n=o.useCallback((c,l=!0)=>{r.current=c,t(c),typeof window<"u"&&em(c,window.localStorage),l&&tm(c)},[]);o.useEffect(()=>{const c=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:Mn(window.localStorage);r.current=u,t(u)},l=d=>{if(d.key!==za)return;const m=Mn(window.localStorage);r.current=m,t(m)};return window.addEventListener(ga,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ga,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{n(c)},[n]),i=o.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:i}}var sm=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function rm(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function bt(e,t){if(rm(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":sm.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 Zr(e){return bt(e)==="generating"}function Uo(e,t){return bt(e,t)==="waiting_approval"}function it(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function nm(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const r=Math.floor(t/60),n=t%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),i=r%24;return`${a}d ${i}h`}function An(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function hn(e,t){const r=typeof t=="string"?t.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),i=a.split(/[\\/]/).filter(Boolean);return i[i.length-1]||a}function am(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 om(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function im(e){return am(e.trim().replace(/\.local$/i,""))}function cm(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function xc(e,t={}){var a,i;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(i=e.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!om(c));if(r&&r!=="Unknown")return im(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Tt(e,t={}){return cm(e)||xc(e,t)}function bc(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 gc(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function fs(e,t){return bc(e).join(" · ")}function cr(e){return e.transport==="pty"}function Ns(e){return e.transport==="acp"}function lm(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:it(e)}function zo(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=it(r||"").trim().toLowerCase();return n===a||n===i||n===c}function dm(e,t=[],r=[]){var d,m,u,f;const n=bt(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(x=>Uo(x.status,{activeModal:x.activeModal})||Zr(x.status));if(a)return bt(a.status,{activeModal:a.activeModal});const i=r.find(x=>Uo(x.status,{activeModal:x.activeModal})||Zr(x.status));if(i)return bt(i.status,{activeModal:i.activeModal});if(n&&n!=="idle")return n;const c=bt((d=t[0])==null?void 0:d.status,{activeModal:(m=t[0])==null?void 0:m.activeModal});if(c!=="idle")return c;const l=bt((u=r[0])==null?void 0:u.status,{activeModal:(f=r[0])==null?void 0:f.activeModal});return l!=="idle"?l:"idle"}function um(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function mm(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=t.get(a),c=bt(n.status);if(!i){t.set(a,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),d=r.indexOf(c||"idle");d>=0&&(l<0||d<l)&&t.set(a,{...n,status:c})}return Array.from(t.values())}function fm(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 pm(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&&fm(t.receivedAt)||0}function hm(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ya(e){return Math.max(hm(e),pm(e.activeChat))}function xm(e,t,r,n,a,i){const c=t-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(i)}function Ga(e,t){return xm(ya(e),ya(t),Tt(e,{fallbackId:e.id}),Tt(t,{fallbackId:t.id}),e.id,t.id)}const yc="adhdev_notification_prefs",Vo={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function bm(){try{const e=localStorage.getItem(yc);if(e){const t=JSON.parse(e);return{...Vo,...t}}}catch{}return{...Vo}}function gm(e){try{localStorage.setItem(yc,JSON.stringify(e))}catch{}}let Ot=bm(),Kr=[];function ym(){Kr.forEach(e=>e())}function vm(e){Ot={...Ot,...e},gm(Ot),ym()}function wm(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Kr.push(r),()=>{Kr=Kr.filter(n=>n!==r)}},[]);const t=o.useCallback(r=>{vm(r)},[]);return[{...Ot},t]}function Zs(e){if(!Ot.globalEnabled)return!1;switch(e){case"disconnect":return Ot.disconnectAlert;case"completion":return Ot.completionAlert;case"approval":return Ot.approvalAlert;case"browser":return Ot.browserNotifications;default:return!0}}const jm={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function vc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function wc(){return"Notification"in window&&Notification.permission==="granted"}let Zt=null;function km(e){return e!==!1}async function Sm(){if(Zt!==null)return Zt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Zt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Zt=!!await e.pushManager.getSubscription(),Zt):(Zt=!1,!1)}catch{return Zt=!1,!1}}function va(e,t,r){if(wc())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 Nm(e,t={}){const r={...jm,...t},n=o.useRef(new Map),a=o.useRef(0),[i,c]=o.useState(null);o.useEffect(()=>{let d=!1;return Sm().then(m=>{d||c(m)}),()=>{d=!0}},[]);const l=o.useCallback((d,m,u)=>{const f=Date.now();f-a.current<r.throttleMs||(a.current=f,va(d,m,u))},[r.throttleMs]);o.useEffect(()=>{var d;if(!(!r.enabled||!wc())&&Zs("browser")&&!km(i)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,bt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const u=n.current.get(m.id),f=bt(m.status,{activeModal:m.activeModal}),x=m.name||m.id;if(r.onApproval&&Zs("approval")&&f==="waiting_approval"&&u!=="waiting_approval"){const C=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";l(`🔔 ${x} — Approval needed`,C.slice(0,120),`approval-${m.id}`)}r.onComplete&&Zs("completion")&&Zr(u)&&f==="idle"&&l(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&f==="error"&&u!=="error"&&l(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,f)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,i,l])}const Cm=/^(run|approve|accept|yes|allow|always)/,Tm=/^(run|approve|accept|yes|allow|always|proceed|save)/,Mm=/^(reject|deny|delete|remove|abort|cancel|no)/;function qa(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Am(e){const t=qa(e).toLowerCase();return Cm.test(t)?"primary":Mm.test(t)?"danger":"default"}function Im(e){return Tm.test(qa(e).toLowerCase())?"approve":"reject"}function Rm(e){return e.map((t,r)=>({label:qa(t),variant:Am(t),action:Im(t),button:t,buttonIndex:r}))}function Lm(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function _m(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 Pm{constructor(){Qe(this,"dedupMap",new Map);Qe(this,"DEDUP_WINDOW_MS",5e3);Qe(this,"DEDUP_MAX_SIZE",50);Qe(this,"DEDUP_CLEANUP_AGE_MS",1e4);Qe(this,"toastCallbacks",[]);Qe(this,"resolveActionFn",null);Qe(this,"viewRequestRespondFn",null);Qe(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(i=>i.id===t.daemonId&&i.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const i=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var y;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),i=n||t.daemonId||"",c=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),l=`${i}:${t.event}:${c}`;if(this.isDuplicate(l))return;const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(d==null?void 0:d.type)||"";let u=it(m);const f=this.resolveOwningDaemon(t);if(f){const p=Tt(f,{fallbackId:f.id});p&&(u=!m||m==="adhdev-daemon"?p:`${p}/${u}`)}let x="",C="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";x=`✅ ${u} agent task completed${p}`,C="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(x=`⚡ ${u} approval needed`,C="warning",(y=t.modalButtons)!=null&&y.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const g=this.resolveActionFn,b=Rm(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}})}})),h=Lm(u,t.modalMessage,x),k=Date.now();this.emitToast({id:k,message:h,type:C,timestamp:k,targetKey:n||p,actions:b,duration:15e3}),x=""}}else if(t.event==="monitor:long_generating"){const p=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";x=`⚠️ ${u} agent is taking a long time${p}`,C="warning",Zs("browser")&&!document.hasFocus()&&va(`⚠️ ${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,b=t.orgId;if(x=`👁️ ${p} wants to view your session`,C="warning",g&&b&&this.viewRequestRespondFn){const h=Date.now(),k=_m(b,g,this.viewRequestRespondFn,(S,j)=>console.error(`[EventManager] ${S} view request failed:`,j));this.emitToast({id:h,message:x,type:C,timestamp:h,actions:k,duration:3e4}),x=""}Zs("browser")&&!document.hasFocus()&&va("👁️ View Request",`${p} wants to view your session`,`view-request-${g}`)}else t.event==="team:view_request_approved"?(x="✅ View request approved",C="success"):t.event==="team:view_request_rejected"&&(x=`❌ ${t.targetName||"Team member"} declined your view request`,C="warning");if(x){const p=Date.now();this.emitToast({id:p,message:x,type:C,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const at=new Pm,Go=new Map;function en(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Cs(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function xn(e){return en(e)?en(e.result)?e.result:e:null}function Dm(e){const t=xn(e);return!t||!en(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Nr(e){const t=xn(e);return!t||!en(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Fs(e){const t=xn(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Cr(e){const t=xn(e);return!!t&&t.success===!1}function Em(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";at.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";at.showToast(n.notification.body,a)}}}function $m(e,t){return e&&Cs(e.currentValue)?e.currentValue:t}function Bm(e,t){return Cs(t)?Cs(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Km(e,t){var i,c;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(Cs(l))return l}const n=(i=t.controlValues)==null?void 0:i[e];if(Cs(n))return n;const a=(c=t.defaultValues)==null?void 0:c[e];return Cs(a)?a:void 0}function Wr(e,t){return e.options||t[e.id]||[]}const Wm={antigravity:new Set(["new_session"]),"claude-cli":new Set(["compact","new_session"]),"claude-code-vscode":new Set(["new_session"]),codex:new Set(["new_session"])};function Om(e,t,r){var n;return((n=Wm[t])==null?void 0:n.has(r.id))===!0}function Ya(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Om(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function In(e,t){return{value:t}}function Fm(e,t,r){var a;return r?((a=Wr(e,t).find(i=>i.value===r))==null?void 0:a.label)||r:""}const Hm={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Um({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=gt(),d=`${e}:${t||n}`,m=Hm[n]||"#94a3b8",[u,f]=o.useState({}),x=o.useRef({}),C=o.useRef(c);x.current=u,C.current=c;const y=o.useRef(0),p={};for(const I of i||[])I.defaultValue!==void 0&&(p[I.id]=I.defaultValue);const g={...p,...c||{},...Date.now()<y.current?u:{}};o.useEffect(()=>{c&&Date.now()>y.current&&f({})},[c]);const[b,h]=o.useState(Go.get(d)||{}),[k,S]=o.useState(null),[j,A]=o.useState(null),M=o.useCallback(async(I,F={})=>{const P={...F,...t&&{targetSessionId:t}};return await l(e,I,P)},[e,t,l]),w=o.useCallback(async(I,F={})=>{const P=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await M("invoke_provider_script",{...P,scriptName:I,...F})},[M,n,r,t]),v=o.useCallback((I,F,P)=>{const $=$m(P,F);f(H=>({...H,[I.id]:$})),Em(P==null?void 0:P.effects)},[]),B=o.useCallback((I,F)=>{f(P=>{const $={...P};return F===void 0?delete $[I.id]:$[I.id]=F,$}),y.current=0},[]);if(!i||i.length===0)return null;const _=Ya(i,{hostIdeType:r,providerType:n});if(_.length===0)return null;const T=async I=>{if(k===I.id){S(null);return}if(Wr(I,b).length>0){S(I.id);return}if(I.dynamic&&I.listScript){A(I.id);try{const P=await w(I.listScript,{}),$=Dm(P);if(!$){const he=Fs(P);he&&at.showToast(he,"warning");return}const H=$.options;h(he=>{const ie={...he,[I.id]:H};return Go.set(d,ie),ie});const J=Km(I.id,{localOverrideUntil:y.current,localValues:x.current,controlValues:C.current,defaultValues:p});if(Bm(J,$.currentValue)){const he=$.currentValue;f(ie=>({...ie,[I.id]:he}))}S(I.id)}catch(P){const $=P instanceof Error?P.message:`Could not load ${I.label}`;at.showToast($,"warning")}finally{A(null)}}},D=async(I,F)=>{S(null);const P=(c==null?void 0:c[I.id])??p[I.id];f($=>({...$,[I.id]:F})),y.current=Date.now()+5e3;try{if(!I.setScript)return;const $=await w(I.setScript,In(I,F)),H=Nr($);if(H&&!H.ok||Cr($))throw new Error((H==null?void 0:H.error)||Fs($)||`Could not update ${I.label}`);v(I,F,H)}catch($){B(I,P);const H=$ instanceof Error?$.message:`Could not update ${I.label}`;at.showToast(H,"warning")}},K=async I=>{const F=Wr(I,b).map(ie=>ie.value);if(F.length===0)return;const P=String(g[I.id]||""),H=(F.indexOf(P)+1)%F.length,J=F[H];if(typeof J!="string")return;const he=(c==null?void 0:c[I.id])??p[I.id];f(ie=>({...ie,[I.id]:J})),y.current=Date.now()+5e3;try{if(!I.setScript)return;const ie=await w(I.setScript,In(I,J)),te=Nr(ie);if(te&&!te.ok||Cr(ie))throw new Error((te==null?void 0:te.error)||Fs(ie)||`Could not update ${I.label}`);v(I,J,te)}catch(ie){B(I,he);const te=ie instanceof Error?ie.message:`Could not update ${I.label}`;at.showToast(te,"warning")}},L=async I=>{const P=!g[I.id],$=(c==null?void 0:c[I.id])??p[I.id];f(H=>({...H,[I.id]:P})),y.current=Date.now()+5e3;try{if(!I.setScript)return;const H=await w(I.setScript,In(I,P)),J=Nr(H);if(J&&!J.ok||Cr(H))throw new Error((J==null?void 0:J.error)||Fs(H)||`Could not update ${I.label}`);v(I,P,J)}catch(H){B(I,$);const J=H instanceof Error?H.message:`Could not update ${I.label}`;at.showToast(J,"warning")}},N=async I=>{if(!I.invokeScript)return;if(I.confirmMessage){const P=[I.confirmTitle,I.confirmMessage,I.confirmLabel].filter(H=>typeof H=="string"&&H.trim().length>0);if(!window.confirm(P.join(`
28
28
 
29
- `)))return}const W=(c==null?void 0:c[I.id])??p[I.id];try{const P=await w(I.invokeScript),$=Nr(P);if($&&!$.ok||Cr(P))throw new Error(($==null?void 0:$.error)||Fs(P)||`Could not run ${I.label}`);$&&v(I,W??!0,$)}catch(P){B(I,W);const $=P instanceof Error?P.message:`Could not run ${I.label}`;at.showToast($,"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(I=>{const W=String(j[I.id]||""),P=Wm(I,b,W),$=y===I.id,H=k===I.id,J=Wr(I,b),he="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(I.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:$?`${m}55`:"var(--border-default)",background:$?`${m}10`:"var(--surface-tertiary)",color:W?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void T(I),title:I.label,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:H?"Loading…":P||I.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),$&&J.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:I.label}),J.map(ie=>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:ie.value===W?`${m}14`:"transparent",color:ie.value===W?"var(--text-primary)":"var(--text-secondary)",borderLeft:ie.value===W?`2px solid ${m}`:"2px solid transparent"},title:ie.description||ie.label,onMouseEnter:te=>{te.currentTarget.style.background=`${m}10`},onMouseLeave:te=>{te.currentTarget.style.background=ie.value===W?`${m}14`:"transparent"},onClick:()=>void D(I,ie.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ie.label}),ie.value===W&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},ie.value))]})]})]},I.id);case"cycle":return s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:W?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void K(I),title:`Click to cycle: ${J.map(ie=>ie.label).join(" → ")}`,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:P||I.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},I.id);case"toggle":return s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:W?`${m}44`:"var(--border-default)",background:W?`${m}14`:"var(--surface-tertiary)",color:W?m:"var(--text-muted)"},onClick:()=>void L(I),"aria-pressed":!!W,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),I.label]},I.id);case"action":return s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void N(I),children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:I.resultDisplay==="inline"&&W?`${I.label}: ${W}`:I.label})]},I.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:W?"var(--text-primary)":"var(--text-muted)"},children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:W?`${I.label}: ${W}`:I.label})]},I.id);default:return null}})]})})}function Hm({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:d}){const{isVisible:m}=za(),u=qa(l,{hostIdeType:a,providerType:i});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(Fm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:u,controlValues:d})})}function Um({hasDraft:e,isBusy:t=!1}){return!e||t}const wc=o.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:d=!1,animateVisibility:m=!0,onControlsToggle:u}){const f=o.useRef(null),[x,C]=o.useState(""),g=o.useRef(!1),{isVisible:p,toggleVisibility:j}=za();o.useEffect(()=>{C("")},[t]),o.useEffect(()=>{var h;l&&((h=f.current)==null||h.focus({preventScroll:!0}))},[t,l]);const b=async()=>{const h=x.trim();if(!(!h||a)&&!g.current){g.current=!0;try{await c(h)!==!1&&C("")}finally{g.current=!1}}};return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":""].filter(Boolean).join(" "),style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[s.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[d&&s.jsx("button",{type:"button",onClick:()=>{j(),u==null||u()},"aria-label":p?"Hide controls":"Show controls","aria-pressed":p,title:p?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("input",{ref:f,type:"text",placeholder:i||`Send message to ${r}...`,value:x,onChange:h=>C(h.target.value),onPaste:h=>{const y=h.clipboardData.getData("text");y&&C(S=>S+y),h.preventDefault()},onKeyDown:h=>{if(h.key==="Enter"){if(h.nativeEvent.isComposing){h.preventDefault();return}h.preventDefault(),b()}},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:()=>{b()},disabled:Um({hasDraft:!!x.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${x.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:x.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:x.trim()?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),tt=e=>e.transport==="pty",Ks=(e,t)=>tt(e)?e.mode||"terminal":"chat",jc=(e,t)=>tt(e)&&Ks(e)==="terminal",Ze=e=>e.transport==="acp",zm=180;function Xt(e){return e.streamSource!=="agent-stream"}function bs(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function kc(e){return e.machineName||""}function mr(e){return bs(e)}function Kt(e){return e.agentType||""}function en(e){return e.hostIdeType||""}function Ya(e){return e.displayPrimary||e.agentName||"Agent"}function Sc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Vm(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Nc(e){const t=Vm(e),r=As(t==null?void 0:t.content),n=As(e.lastMessagePreview);return r||n||""}function Gm(e,t=zm){const r=As(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 qm(e){return Gm(Nc(e)||e.displaySecondary||"")}function Cc(e){return[e.displaySecondary,kc(e)].filter(Boolean)}function Rs(e){return e.agentName||it(Kt(e))}function Ym(e){var t,r;if(!Xt(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return it(en(e)||Kt(e))}function Tc(e){return Xt(e)?e.sessionId:e.nativeSessionId}function Vo(e){return Xt(e)?"native":e.tabKey}function Xm(e){return e.sessionId}function Jm(e,t){if(t)return Xt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function Qm(e,t){const r=Kt(e),n=Xt(e),a=tt(e)||Ze(e),i=n?a?Rs(e)||(t==null?void 0:t.cliName)||it(en(e)||r):t!=null&&t.type?it(t.type):it(en(e)||r):Rs(e);return{isNativeConversation:n,isCli:tt(e),isAcp:Ze(e),isCliTerminal:jc(e),providerType:r,displayLabel:i,targetEntry:Jm(e,t)}}function rs(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:tt(e)||Ze(e)?{agentType:Kt(e)}:e.streamSource==="agent-stream"?{agentType:Kt(e)}:t}function Ls(e){return e?mr(e):""}function Hs(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Xa(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Zm(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 Mc(){return"select_session"}function ef(){return"open_panel"}function tf({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function sf(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Go(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function tn(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ja(e){return e instanceof Error?e.message:String(e||"")}function qo(e){const t=Ja(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Yo(e,t){const r=Ja(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function xn({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[d,m]=o.useState(null),u=o.useRef(!1),f=o.useRef(null);o.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const x=o.useCallback(async j=>{if(!t||u.current)return!1;const b=j.trim(),h=Xa(t);if(tf({hasMessage:!!b,blockedMessage:h,sendInFlight:u.current}))return h&&m(h),!1;const y=Date.now(),S={tabKey:t.tabKey,message:b,timestamp:y};if(sf(f.current,S))return m(null),!0;u.current=!0,l(!0),m(null),f.current=S;try{const k=Ls(t);if(!k)return f.current=Go(f.current,S),m("Unable to send message right now."),!1;const A=await e(k,"send_chat",{message:b,...rs(t)}),M=tn(A);if(M!=null&&M.deduplicated)return m(null),!0;if((M==null?void 0:M.sent)===!1)throw new Error((M==null?void 0:M.error)||"Send failed");if((M==null?void 0:M.success)===!1)throw new Error((M==null?void 0:M.error)||"Send failed");return m(null),!0}catch(k){const A=Ja(k);return A.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",A):console.warn("Send blocked/failed",k),f.current=Go(f.current,S),m(Zm(k)),!1}finally{u.current=!1,l(!1)}},[t,e]),C=o.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(j){console.error("Relaunch failed",j)}},[t,e]),g=o.useCallback(async j=>{if(t)try{const h=(t.modalButtons||[]).indexOf(j),y=j.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(y),k=Ls(t);if(!k)return;const A=await e(k,"resolve_action",{button:j,action:S?"approve":"reject",...h>=0&&{buttonIndex:h},...rs(t)}),M=tn(A);M.success||r(w=>[...w,{routeId:t.tabKey,text:Yo(j,M==null?void 0:M.error),timestamp:Date.now()}])}catch(b){qo(b)||console.error("[ModalButton] Error:",b),r(h=>[...h,{routeId:t.tabKey,text:qo(b)?Yo(j,b):`❌ **${j}** error`,timestamp:Date.now()}])}},[t,e,r]),p=o.useCallback(async()=>{if(!(!t||a)){i(!0);try{await e(t.routeId,ef(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(j){console.error("Focus agent failed",j)}finally{i(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:x,handleRelaunch:C,handleModalButton:g,handleFocusAgent:p}}const rf=10,nf=8e3,af=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function of(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 va(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(af.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=of(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=>va(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,va(a,n,r+1)]))}function Tr(e,t){return Array.isArray(e)?e.slice(-t):[]}function cf(e,t=Date.now()){const r=e&&t-e.firstAt<=nf,n=r?e.count+1:1;return n>=rf?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function Ac(e){var n;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:t.messages.length,visible:e.visibleMessages.length,history:((n=e.chatTailState.historyMessages)==null?void 0:n.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:Tr(t.messages,10),visibleMessagesTail:Tr(e.visibleMessages,5),historyMessagesTail:Tr(e.chatTailState.historyMessages,5),actionLogsTail:Tr(e.actionLogs.filter(a=>a.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{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 va(r)}function Ic(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 Rc(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 Lc(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(`
29
+ `)))return}const F=(c==null?void 0:c[I.id])??p[I.id];try{const P=await w(I.invokeScript),$=Nr(P);if($&&!$.ok||Cr(P))throw new Error(($==null?void 0:$.error)||Fs(P)||`Could not run ${I.label}`);$&&v(I,F??!0,$)}catch(P){B(I,F);const $=P instanceof Error?P.message:`Could not run ${I.label}`;at.showToast($,"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(I=>{const F=String(g[I.id]||""),P=Fm(I,b,F),$=k===I.id,H=j===I.id,J=Wr(I,b),he="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(I.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:$?`${m}55`:"var(--border-default)",background:$?`${m}10`:"var(--surface-tertiary)",color:F?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void T(I),title:I.label,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:H?"Loading…":P||I.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),$&&J.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:I.label}),J.map(ie=>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:ie.value===F?`${m}14`:"transparent",color:ie.value===F?"var(--text-primary)":"var(--text-secondary)",borderLeft:ie.value===F?`2px solid ${m}`:"2px solid transparent"},title:ie.description||ie.label,onMouseEnter:te=>{te.currentTarget.style.background=`${m}10`},onMouseLeave:te=>{te.currentTarget.style.background=ie.value===F?`${m}14`:"transparent"},onClick:()=>void D(I,ie.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ie.label}),ie.value===F&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},ie.value))]})]})]},I.id);case"cycle":return s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:F?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void K(I),title:`Click to cycle: ${J.map(ie=>ie.label).join(" → ")}`,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:P||I.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},I.id);case"toggle":return s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:F?`${m}44`:"var(--border-default)",background:F?`${m}14`:"var(--surface-tertiary)",color:F?m:"var(--text-muted)"},onClick:()=>void L(I),"aria-pressed":!!F,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),I.label]},I.id);case"action":return s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void N(I),children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:I.resultDisplay==="inline"&&F?`${I.label}: ${F}`:I.label})]},I.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:F?"var(--text-primary)":"var(--text-muted)"},children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:F?`${I.label}: ${F}`:I.label})]},I.id);default:return null}})]})})}function zm({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:d}){const{isVisible:m}=Va(),u=Ya(l,{hostIdeType:a,providerType:i});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(Um,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:u,controlValues:d})})}function Vm({hasDraft:e,isBusy:t=!1}){return!e||t}const jc=o.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:d=!1,animateVisibility:m=!0,onControlsToggle:u}){const f=o.useRef(null),[x,C]=o.useState(""),y=o.useRef(!1),{isVisible:p,toggleVisibility:g}=Va();o.useEffect(()=>{C("")},[t]),o.useEffect(()=>{var h;l&&((h=f.current)==null||h.focus({preventScroll:!0}))},[t,l]);const b=async()=>{const h=x.trim();if(!(!h||a)&&!y.current){y.current=!0;try{await c(h)!==!1&&C("")}finally{y.current=!1}}};return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":""].filter(Boolean).join(" "),style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[s.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[d&&s.jsx("button",{type:"button",onClick:()=>{g(),u==null||u()},"aria-label":p?"Hide controls":"Show controls","aria-pressed":p,title:p?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("input",{ref:f,type:"text",placeholder:i||`Send message to ${r}...`,value:x,onChange:h=>C(h.target.value),onPaste:h=>{const k=h.clipboardData.getData("text");k&&C(S=>S+k),h.preventDefault()},onKeyDown:h=>{if(h.key==="Enter"){if(h.nativeEvent.isComposing){h.preventDefault();return}h.preventDefault(),b()}},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:()=>{b()},disabled:Vm({hasDraft:!!x.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${x.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:x.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:x.trim()?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),tt=e=>e.transport==="pty",Ks=(e,t)=>tt(e)?e.mode||"terminal":"chat",kc=(e,t)=>tt(e)&&Ks(e)==="terminal",Ze=e=>e.transport==="acp",Gm=180;function Xt(e){return e.streamSource!=="agent-stream"}function bs(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Sc(e){return e.machineName||""}function mr(e){return bs(e)}function Kt(e){return e.agentType||""}function tn(e){return e.hostIdeType||""}function Xa(e){return e.displayPrimary||e.agentName||"Agent"}function Nc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function qm(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Cc(e){const t=qm(e),r=As(t==null?void 0:t.content),n=As(e.lastMessagePreview);return r||n||""}function Ym(e,t=Gm){const r=As(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 Xm(e){return Ym(Cc(e)||e.displaySecondary||"")}function Tc(e){return[e.displaySecondary,Sc(e)].filter(Boolean)}function Rs(e){return e.agentName||it(Kt(e))}function Jm(e){var t,r;if(!Xt(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return it(tn(e)||Kt(e))}function Mc(e){return Xt(e)?e.sessionId:e.nativeSessionId}function qo(e){return Xt(e)?"native":e.tabKey}function Qm(e){return e.sessionId}function Zm(e,t){if(t)return Xt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function ef(e,t){const r=Kt(e),n=Xt(e),a=tt(e)||Ze(e),i=n?a?Rs(e)||(t==null?void 0:t.cliName)||it(tn(e)||r):t!=null&&t.type?it(t.type):it(tn(e)||r):Rs(e);return{isNativeConversation:n,isCli:tt(e),isAcp:Ze(e),isCliTerminal:kc(e),providerType:r,displayLabel:i,targetEntry:Zm(e,t)}}function rs(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:tt(e)||Ze(e)?{agentType:Kt(e)}:e.streamSource==="agent-stream"?{agentType:Kt(e)}:t}function Ls(e){return e?mr(e):""}function Hs(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Ja(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function tf(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 Ac(){return"select_session"}function sf(){return"open_panel"}function rf({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function nf(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Yo(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function sn(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Qa(e){return e instanceof Error?e.message:String(e||"")}function Xo(e){const t=Qa(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Jo(e,t){const r=Qa(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function bn({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[d,m]=o.useState(null),u=o.useRef(!1),f=o.useRef(null);o.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const x=o.useCallback(async g=>{if(!t||u.current)return!1;const b=g.trim(),h=Ja(t);if(rf({hasMessage:!!b,blockedMessage:h,sendInFlight:u.current}))return h&&m(h),!1;const k=Date.now(),S={tabKey:t.tabKey,message:b,timestamp:k};if(nf(f.current,S))return m(null),!0;u.current=!0,l(!0),m(null),f.current=S;try{const j=Ls(t);if(!j)return f.current=Yo(f.current,S),m("Unable to send message right now."),!1;const A=await e(j,"send_chat",{message:b,...rs(t)}),M=sn(A);if(M!=null&&M.deduplicated)return m(null),!0;if((M==null?void 0:M.sent)===!1)throw new Error((M==null?void 0:M.error)||"Send failed");if((M==null?void 0:M.success)===!1)throw new Error((M==null?void 0:M.error)||"Send failed");return m(null),!0}catch(j){const A=Qa(j);return A.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",A):console.warn("Send blocked/failed",j),f.current=Yo(f.current,S),m(tf(j)),!1}finally{u.current=!1,l(!1)}},[t,e]),C=o.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]),y=o.useCallback(async g=>{if(t)try{const h=(t.modalButtons||[]).indexOf(g),k=g.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(k),j=Ls(t);if(!j)return;const A=await e(j,"resolve_action",{button:g,action:S?"approve":"reject",...h>=0&&{buttonIndex:h},...rs(t)}),M=sn(A);M.success||r(w=>[...w,{routeId:t.tabKey,text:Jo(g,M==null?void 0:M.error),timestamp:Date.now()}])}catch(b){Xo(b)||console.error("[ModalButton] Error:",b),r(h=>[...h,{routeId:t.tabKey,text:Xo(b)?Jo(g,b):`❌ **${g}** error`,timestamp:Date.now()}])}},[t,e,r]),p=o.useCallback(async()=>{if(!(!t||a)){i(!0);try{await e(t.routeId,sf(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(g){console.error("Focus agent failed",g)}finally{i(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:x,handleRelaunch:C,handleModalButton:y,handleFocusAgent:p}}const af=10,of=8e3,cf=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function lf(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 wa(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(cf.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=lf(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=>wa(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,wa(a,n,r+1)]))}function Tr(e,t){return Array.isArray(e)?e.slice(-t):[]}function df(e,t=Date.now()){const r=e&&t-e.firstAt<=of,n=r?e.count+1:1;return n>=af?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function Ic(e){var n;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:t.messages.length,visible:e.visibleMessages.length,history:((n=e.chatTailState.historyMessages)==null?void 0:n.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:Tr(t.messages,10),visibleMessagesTail:Tr(e.visibleMessages,5),historyMessagesTail:Tr(e.chatTailState.historyMessages,5),actionLogsTail:Tr(e.actionLogs.filter(a=>a.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{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 wa(r)}function Rc(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 Lc(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 _c(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(`
30
30
  `)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
31
31
 
32
32
  \`\`\`json
@@ -35,60 +35,60 @@ ${JSON.stringify(t.bundle,null,2)}
35
35
 
36
36
  \`\`\`json
37
37
  ${JSON.stringify(t,null,2)}
38
- \`\`\``}function In(e,t){return`${e}:${t}`}function lf(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Us(e,t){lf()&&console.debug(`[subscription-manager] ${e}`,t)}class df{constructor(){Qe(this,"active",new Map);Qe(this,"retryTimers",new Map)}subscribe(t,r,n,a,i){var u;const c=In(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),Us("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(i!=null&&i.retryIntervalMs)&&this.scheduleRetry(c,t,i.retryIntervalMs)}const m=()=>{var C;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 x={type:"unsubscribe",topic:n.topic,key:n.key};Us("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(C=t.sendData)==null||C.call(t,r,x)};return m.initialSendAccepted=d,m}publish(t){const r=In(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Ms.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),Ms.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=In(t,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(t){var r;Us("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=t.sendData)==null||r.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,r){var a;const n=Array.from(this.active.values()).filter(i=>i.daemonId===t);Us("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}scheduleRetry(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var l;this.retryTimers.delete(t);const i=this.active.get(t);if(!i)return;const c=((l=r.sendData)==null?void 0:l.call(r,i.daemonId,i.request))??!1;Us("subscribe_retry",{id:t,accepted:c,topic:i.request.topic,key:i.request.key}),c||this.scheduleRetry(t,r,n)},n);this.retryTimers.set(t,a)}clearRetry(t){const r=this.retryTimers.get(t);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(t))}}const Ht=new df;function uf(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 i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function mf(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 sn(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=t,l=c||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:m,childrenByParent:u}=mf(d),f=uf(i,n),x=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,C=m.filter(j=>j.kind==="workspace"&&j.transport==="cdp-page"),g=m.filter(j=>j.kind==="agent"&&j.transport==="pty"),p=m.filter(j=>j.kind==="agent"&&j.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...x&&{machine:x,platform:x.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:C.some(j=>!!j.cdpConnected)});for(const j of C){const b=f.get(j.id),h=Xs(j,b),y=(u.get(j.id)||[]).map(S=>Xs(S,f.get(S.id)));r.push({id:`${n}:ide:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(b==null?void 0:b.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:n,instanceId:j.id,workspace:h.workspace,terminals:0,childSessions:y,agents:y.map(S=>({id:S.id,name:S.providerName||S.providerType,type:S.providerType,status:S.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},timestamp:l})}for(const j of g){const b=f.get(j.id),h=Xs(j,b);r.push({id:`${n}:cli:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(b==null?void 0:b.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:j.id,cliName:h.providerName||h.providerType,mode:h.mode||(b==null?void 0:b.mode)||"terminal",workspace:h.workspace||"",activeChat:h.activeChat,...h.resume!==void 0&&{resume:h.resume},...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},timestamp:l,_isCli:!0})}for(const j of p){const b=f.get(j.id),h=Xs(j,b);r.push({id:`${n}:acp:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(b==null?void 0:b.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:j.id,cliName:h.providerName||h.providerType,mode:"chat",workspace:h.workspace||"",activeChat:h.activeChat,...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},timestamp:l,_isAcp:!0})}return r}const ff=15e3,pf=15e3,hf=6e4,xf=1200,Xo=12,bf=8e3,gf=4e3,Rn=new Map,Ln=new Map,Mr=new Set,er=new Map;function yf(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 Jo(e,t){const r=er.get(e);!r||r.size===0||(er.delete(e),r.forEach(n=>n(t)))}function vf(e,t){return new Promise(r=>{const n=er.get(e)||new Set;er.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&er.delete(e),r(c)},i=setTimeout(()=>a(!1),t);n.add(a)})}function fr(){const{sendCommand:e,sendData:t}=bt(),{injectEntries:r,getIdes:n}=or();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??hf,l=Ln.get(a)||0;if(!(i!=null&&i.force)&&Mr.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const d=Rn.get(a);if(d)return d;const m=(async()=>{if(t&&!Mr.has(a)){const p=Ht.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},j=>{const b=n(),h=b.find(S=>S.id===a),y=sn(j.status,{daemonId:a,existingDaemon:h,existingEntries:b,timestamp:j.timestamp});y.length>0&&r(y),Ln.set(a,Date.now()),Jo(a,!0)});if(p.initialSendAccepted?Mr.add(a):Mr.delete(a),!(i!=null&&i.force)&&p.initialSendAccepted&&await vf(a,xf))return}const u=await e(a,"get_status_metadata"),f=yf(u);if(!f)return;const x=n(),C=x.find(p=>p.id===a),g=sn(f,{daemonId:a,existingDaemon:C,existingEntries:x,timestamp:f.timestamp||Date.now()});g.length>0&&r(g,{authoritativeDaemonIds:[a]}),Ln.set(a,Date.now()),Jo(a,!0)})().finally(()=>{Rn.delete(a)});return Rn.set(a,m),m},[n,r,e,t])}function wf(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const jf=60,kf=50;function _c(e={}){return e.isCliLike?kf:jf}function Sf(e={}){return _c(e)}function St(e){return(typeof e=="string"?e.trim():"")||void 0}function Ft(e,t){const r=St(t);return r?`${e}:${r}`:void 0}function qt(e,t,r){const n=Ft(t,r),a=St(r);n&&e.push(n),a&&e.push(a)}function ks(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function Pc(e){return St(e.providerSessionId)||St(e.sessionId)||St(e.tabKey)||St(e.routeId)}function Qa(e){return ks([St(e.providerSessionId),St(e.sessionId)])}function Ts(e){const t=[];return qt(t,"provider",e.providerSessionId),qt(t,"session",e.sessionId),qt(t,"tab",e.tabKey),qt(t,"route",e.routeId),ks(t)}function Nf(e){const t=[];return St(e.providerSessionId)?(qt(t,"provider",e.providerSessionId),ks(t)):St(e.sessionId)?(qt(t,"session",e.sessionId),ks(t)):St(e.tabKey)?(qt(t,"tab",e.tabKey),ks(t)):St(e.routeId)?(qt(t,"route",e.routeId),ks(t)):[]}function Za(e){return Ft("provider",e.providerSessionId)||Ft("session",e.sessionId)||Ft("tab",e.tabKey)||Ft("route",e.routeId)||"unknown:"}function pr(e){return Qa(e)[0]}function Cf(e){const t=St(e.providerSessionId),r=St(e.sessionId),n=St(e.tabKey),a=St(e.routeId),i=[Ft("provider",t),Ft("session",r),Ft("tab",n),Ft("route",a)].filter(d=>typeof d=="string"),c=Ts({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=Za({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:Pc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:pr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function wa(e,t){const r=Cf(e);return Nf(t).some(n=>r.lookupKeys.includes(n))}const hr=60,Tf=1e3,eo=12e4,Mf=new Set(["generating","waiting_approval","starting","streaming","working"]),Qo=new Map;function Dc(e,t){return`${e}::${t}`}function ja(e=hr){return{liveMessages:[],cursor:Af([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Af(e,t=hr){return{tailLimit:t}}function Zo(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 If{constructor(t){Qe(this,"manager");Qe(this,"sendData");Qe(this,"daemonId");Qe(this,"sessionId");Qe(this,"historySessionId");Qe(this,"subscriptionKey");Qe(this,"snapshot");Qe(this,"transportSubscription",null);Qe(this,"listeners",new Set);Qe(this,"retainCount",0);Qe(this,"loadHistoryPromise",null);Qe(this,"pendingDisconnectTimer",null);this.manager=t.manager||Ht,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=ja(Math.max(0,t.tailLimit??hr))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);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=await t({offset:this.snapshot.historyOffset,excludeRecentCount:this.snapshot.liveMessages.length}),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},...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:Tf}))}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};Zo(this.snapshot.liveMessages)===Zo(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,cursor:n},this.emit())}}function Ec(e){const t=Dc(e.daemonId,e.sessionId),r=Qo.get(t);if(r)return r.updateOptions(e),r;const n=new If(e);return Qo.set(t,n),n}function Rf(e,t){return{...e,loadHistoryPage:t}}function Lf(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function _f(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Mf.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??eo)),i=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return i>0?n-i<=a:Array.isArray(e.messages)&&e.messages.length>0}function Pf(e=eo){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Df(e,t={}){const r=new Set,n=[];for(const a of e){if(!_f(a,t))continue;const i=mr(a),c=a.sessionId||"";if(!i||!c)continue;const l=Dc(i,c);if(r.has(l))continue;r.add(l);const d=pr(a);n.push({daemonId:i,sessionId:c,historySessionId:d||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Lf),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Ef(e,t){const{sendData:r,sendCommand:n}=bt(),a=(t==null?void 0:t.enabled)!==!1,i=mr(e),c=e.sessionId||"",l=pr(e)||c,d=`daemon:${i}:session:${c}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??hr),u=o.useMemo(()=>!a||!i||!c?null:Ec({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:d,sendData:r,tailLimit:m}),[i,a,l,r,c,d,m]),[f,x]=o.useState(()=>(u==null?void 0:u.getSnapshot())||ja(m));o.useEffect(()=>{if(!u){x(ja(m));return}u.retain(),x(u.getSnapshot());const g=u.subscribe(p=>{x(p)});return()=>{g(),u.release()}},[u,m]);const C=o.useCallback(async()=>{!u||!i||!c||await u.loadHistoryPage(async({offset:g,excludeRecentCount:p})=>{const j=e.agentType,b=await n(i,"chat_history",{agentType:j,offset:g,limit:30,targetSessionId:c,historySessionId:l,excludeRecentCount:p}),h=b&&typeof b=="object"&&"result"in b?b.result||{}:b||{};return{messages:Array.isArray(h.messages)?h.messages:[],hasMore:h.hasMore===!0}})},[e.agentType,u,i,l,n,c]);return o.useMemo(()=>Rf(f,C),[C,f])}function $f(e,t){const{sendData:r}=bt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??hr),i=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??eo)),c=Pf(i),[l,d]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(f=>f+1)},c);return()=>{clearInterval(u)}},[e.length,n,c]);const m=o.useMemo(()=>Df(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(f=>Ec({...f,sendData:r,tailLimit:a}));return u.forEach(f=>{f.retain()}),()=>{u.forEach(f=>f.release())}},[m.signature,n,r,a])}function Bf(e,t){return t?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function ei(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 Kf(e,t){if(e.length===0)return[];if(t.some(ei))return[];const r=[],n=new Set;for(let a=e.length-1;a>=0&&r.length<2;a-=1){const i=e[a];if(!i||!ei(i))continue;const c=String(i.role||"").toLowerCase();n.has(c)||(n.add(c),r.unshift(i))}return r}function Wf(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),i=a>0?r.slice(0,a):[],c=a>0?r.slice(-n):r,l=Kf(i,c),d=l.length>0?[...l,...c]:c;return t.length===0?d:[...t,...d]}function Of(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Ff(e){return Of(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function Hf(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Uf(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function zf(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function $c(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Bc(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 Vf(e){return $c(e)?!1:e.inboxBucket==="task_complete"&&Bc(e).length>0}function ti(e){return e.branch||"detached HEAD"}function Gf(e){if(e.error)return`${ti(e)} · Git error: ${e.error}`;const t=[ti(e)];return e.changedFiles>0?t.push(Hf(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 qf(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Gf(t)}`}function Yf(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function Xf(e,t={}){if(t.enabled===!1)return[];if(!zf(e))return[];const r=$c(e)?"working":Vf(e)?"complete":null;if(!r)return[];const n=r==="complete"?Bc(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Uf(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:qf(r,e.git),timestamp:Yf(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 Jf=60;function ka({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:d,scrollToBottomRequestNonce:m,isInputActive:u=!0,isVisible:f=!0}){var ce,ye,ne,de,je,me,pe;const x=o.useRef(new Map),C=o.useRef(void 0),g=fr(),{sendCommand:p}=bt(),{isVisible:j}=za();ur("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const b=Ct.useMemo(()=>Bs(e),[e.status,e.connectionState]),h=o.useMemo(()=>Qm(e,t),[e,t]),y=o.useMemo(()=>{var ee;return qa((ee=h.targetEntry)==null?void 0:ee.providerControls,{hostIdeType:e.hostIdeType,providerType:h.providerType})},[e.hostIdeType,h.providerType,(ce=h.targetEntry)==null?void 0:ce.providerControls]),S=_c({isCliLike:h.isCli||h.isAcp}),k=Sf({isCliLike:h.isCli||h.isAcp}),A=Ef(e,{enabled:f&&!!e.sessionId,tailLimit:k}),[M,w]=o.useState(S),v=e.tabKey,B=A.historyMessages,_=A.hasMoreHistory,T=A.historyError,D=Bf(e,A);o.useEffect(()=>{w(S)},[S,v]);const K=Math.max(0,D.length-M),L=Ya(e),N=mr(e),I=Ff(e),W=Xa(e),P=a||W,$=!!W,[H,J]=o.useState(!1);o.useEffect(()=>{const ee=h.targetEntry;N&&(!ee||ee.providerControls===void 0||ee.controlValues===void 0)&&g(N,{minFreshMs:3e4}).catch(()=>{})},[N,h.isAcp,(ye=h.targetEntry)==null?void 0:ye.providerControls,(ne=h.targetEntry)==null?void 0:ne.controlValues,g]);const he=o.useCallback(async()=>{if(!H){if(D.length>M){w(ee=>Math.min(D.length,ee+Jf));return}J(!0);try{await A.loadHistoryPage()}finally{J(!1)}}},[A,H,D.length,M]),{allMessages:ie,receivedAtMap:te}=o.useMemo(()=>{const ee=Wf({historyMessages:B,liveMessages:D,visibleLiveCount:M}),ue=Xf(e),oe=ue.length>0?[...ee,...ue]:ee,q={};return oe.forEach((V,le)=>{const ke=`${e.tabKey}:${Jr(V,le)}`;let Z=wf(V)||x.current.get(ke)||0;Z||(Z=Date.now(),x.current.set(ke,Z)),q[Jr(V,le)]=Z}),{allMessages:oe,receivedAtMap:q}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,K,B,D,M]),be=o.useMemo(()=>l.filter(ee=>ee.routeId===e.tabKey).sort((ee,ue)=>ee.timestamp-ue.timestamp),[l,e.tabKey]),we=o.useCallback(async()=>{var le,ke;if(!N)return;const ee=Ac({activeConv:e,visibleMessages:ie,actionLogs:l,controls:(le=h.targetEntry)==null?void 0:le.providerControls,controlValues:(ke=h.targetEntry)==null?void 0:ke.controlValues,visibleBarControlCount:y.length,chatTailState:{hasMoreHistory:_,historyError:T,historyMessages:B},ui:{controlsVisible:j,visibleLiveCount:M,hiddenLiveCount:K,isInputActive:u,isVisible:f}}),ue=await p(N,"get_chat_debug_bundle",{agentType:h.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:ee}),oe=tn(ue),q=Lc(oe),V=await Rc(q);V==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),at.showToast(Ic(oe,{locatorCopyStatus:V}),V==="failed"?"warning":"success")},[e,l,ie,j,h.providerType,(de=h.targetEntry)==null?void 0:de.controlValues,(je=h.targetEntry)==null?void 0:je.providerControls,N,_,K,B,u,f,T,p,y.length,M]),ge=o.useCallback(()=>{const ee=cf(C.current);C.current=ee.state,ee.shouldCollect&&we().catch(ue=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",ue),at.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[we]),X=o.useMemo(()=>{if(D.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((b.isGenerating||e.status==="streaming")&&J(!1),e.status==="not_monitored"&&I)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(Is,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ms,{size:14})," Open ",L," 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"&&I)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(rc,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ms,{size:14})," Open ",L," 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"&&!H)return!_&&B.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,I,i,_,B.length,c,H,D.length,L,b.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[s.jsx(Ou,{messages:ie,actionLogs:be,agentName:Rs(e)||L||"Agent",userName:d,isCliMode:h.isCli||h.isAcp,isWorking:b.isGenerating,contextKey:e.tabKey,receivedAtMap:te,lastMessageHash:e.lastMessageHash,onLoadMore:he,isLoadingMore:H,hasMoreHistory:_,hiddenLiveCount:K,loadError:T??void 0,emptyState:X,scrollToBottomRequestNonce:m,isVisible:f}),s.jsx(Hm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:h.providerType,displayLabel:h.displayLabel,controls:(me=h.targetEntry)==null?void 0:me.providerControls,controlValues:(pe=h.targetEntry)==null?void 0:pe.controlValues,isActive:u,isCliTerminal:h.isCliTerminal}),!h.isCliTerminal&&s.jsx(wc,{contextKey:e.tabKey,panelLabel:L,isSending:n,isBusy:$,statusMessage:P,onSend:r,isActive:u,showControlsToggle:y.length>0,onControlsToggle:ge})]})}let Kc=Qt;function Wc(){return Kc()}class Qf{constructor(){Qe(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 Oc=new Qf;class Zf{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 ut=new Zf;function ep(e){e.dashboardWS&&(Oc=e.dashboardWS),e.connectionManager&&(ut=e.connectionManager),e.useDaemonsHook&&(Kc=e.useDaemonsHook)}const tp=.5,sp=1.25;function lt(e){return Ya(e)}function ps(e){return Cc(e).join(" · ")}function Fc(e){const t=Nc(e);return t||(e.title?e.title:ps(e)||"No messages yet")}function Hc(e,t){const{isReconnecting:r,isConnecting:n}=Bs(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function rp(e,t){const r=["Chat",...Cc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function ns(e){return Hc(e)||ps(e)}function np(e){return`${lt(e)} · ${Fc(e)}`}function ap(e){const t=en(e),r=t?it(t):Rs(e);return`${lt(e)} — ${r||"Agent"}`}function op(e){return Rs(e)||"CLI"}function Uc(e){return Sc(e)}function zc(e){return e?`Remote · ${lt(e)||e.workspaceName||"Session"}`:"Remote"}function ip({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var se;Qt();const{sendPtyInput:d}=bt(),[m,u]=o.useState(!1),f=o.useRef(!1);f.current=m;const[x,C]=o.useState("Runtime terminal unavailable"),[g,p]=o.useState(!1),[j,b]=o.useState(null),[h,y]=o.useState(!1),[S,k]=o.useState(!1),[A,M]=o.useState(1),[w,v]=o.useState(!1),[B,_]=o.useState({width:0,height:0}),[T,D]=o.useState({width:0,height:0}),[K,L]=o.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[N,I]=o.useState(null),W=o.useRef(null),P=o.useRef(null),$=o.useRef(!1),H=o.useRef(!1),J=o.useRef(c),he=o.useRef(0),ie=o.useRef(!1),te=o.useRef(""),be=o.useRef(null),we=o.useRef(!1),ge=o.useRef(!1),X=o.useRef(null),ce=o.useRef(null),ye=o.useRef(null),ne=32*1024,de=()=>{var E,Y,Q,re;return((Y=(E=W.current)==null?void 0:E.ownerDocument)==null?void 0:Y.defaultView)||((re=(Q=P.current)==null?void 0:Q.ownerDocument)==null?void 0:re.defaultView)||window},je=E=>{const Y=de();return{ownerWindow:Y,frameId:Y.requestAnimationFrame(E)}},me=()=>{const E=X.current;if(E){try{E.ownerWindow.cancelAnimationFrame(E.frameId)}catch{}X.current=null}},pe=()=>{const E=ce.current;if(E){try{E.ownerWindow.clearTimeout(E.timeoutId)}catch{}ce.current=null}},ee=()=>{const E=ye.current;if(E){try{E.ownerWindow.clearTimeout(E.timeoutId)}catch{}ye.current=null}},ue=()=>{c&&X.current===null&&(X.current=je(()=>{st()}))},oe=e.tabKey,q=e.sessionId||"",V=e.daemonId||((se=e.routeId)==null?void 0:se.split(":")[0])||e.routeId||"",le=Xa(e),ke=m?i||le:x,Z=tp,De=sp,$e=.05,Fe=()=>{const E=T.width,Y=T.height;if(!Number.isFinite(B.width)||B.width<=0||!Number.isFinite(B.height)||B.height<=0||!Number.isFinite(E)||E<=0||!Number.isFinite(Y)||Y<=0)return 1;const Q=B.width/E,re=B.height/Y;return Number(Math.min(De,Math.max(Z,Math.min(Q,re))).toFixed(2))},Ue=Fe(),O=$.current&&A>Ue,Ce=Number.isFinite(T.width)&&T.width>0?Math.max(B.width,Math.round(T.width*A)):B.width,Te=Number.isFinite(T.height)&&T.height>0?Math.max(B.height,Math.round(T.height*A)):B.height,_e=()=>{je(()=>{const E=P.current;E&&(E.scrollLeft=0,E.scrollTop=E.scrollHeight-E.clientHeight)})},Be=()=>{var E,Y;he.current=0,ie.current=!1,te.current="",be.current=null,we.current=!1,ge.current=!1,$.current||(H.current=!1,M(1)),X.current!==null&&me(),u(!1),C("Runtime terminal unavailable"),ee(),pe(),b(null),I(null),v(!1),p(!1),y(!1),k(!1),(Y=(E=r.current)==null?void 0:E.reset)==null||Y.call(E)},He=()=>{var E,Y;he.current=0,ie.current=!1,te.current="",be.current=null,we.current=!1,ge.current=!1,X.current!==null&&me(),u(!0),C(""),ee(),pe(),b(null),I(null),v(!1),p(!1),y(!1),k(!1),(Y=(E=r.current)==null?void 0:E.reset)==null||Y.call(E)},Xe=()=>{ge.current&&(ge.current=!1,je(()=>{var E,Y;(Y=(E=r.current)==null?void 0:E.scrollToTop)==null||Y.call(E)}))},st=()=>{if(X.current=null,!c)return;const E=te.current;if(!E)return;const Y=E.slice(0,ne);te.current=E.slice(Y.length);const Q=r.current;if(!Q){te.current=Y+te.current,ue();return}Q.write(Y,()=>{if(te.current.length>0){ue();return}Xe()})},mt=E=>{E&&(te.current+=E,ue())},ht=(E,Y=0,Q,re,ve={})=>{var Le,Se,Pe,Ee;const Ie=!!ve.force;!Ie&&Y>0&&he.current>=Y||!Ie&&Y===0&&ie.current||(he.current=Y,Y>0&&y(!0),u(!0),C(""),typeof Q=="number"&&typeof re=="number"&&Q>0&&re>0&&((Se=(Le=r.current)==null?void 0:Le.resize)==null||Se.call(Le,Q,re)),te.current="",(Ee=(Pe=r.current)==null?void 0:Pe.reset)==null||Ee.call(Pe),E?mt(E):Xe())};o.useEffect(()=>{Be()},[q]),o.useEffect(()=>{var Y;if(!q)return;const E=((Y=ut.onRuntimeEvent)==null?void 0:Y.call(ut,q,Q=>{if(!(!Q||Q.sessionId!==q)){if(Q.type==="runtime_snapshot"){if(!c){be.current={text:Q.text||"",seq:Q.seq||0,cols:Q.cols,rows:Q.rows,force:!!Q.force};return}ht(Q.text||"",Q.seq||0,Q.cols,Q.rows,{force:!!Q.force});return}if(Q.type==="session_output"){ie.current=!0,typeof Q.seq=="number"&&(he.current=Math.max(he.current,Q.seq),Q.seq>0&&y(!0)),f.current||u(!0),f.current||C(""),typeof Q.data=="string"&&mt(Q.data);return}if(Q.type==="session_cleared"){if(!c){we.current=!0,te.current="",be.current=null;return}He();return}if(Q.type==="session_io_error"){const re=typeof Q.error=="string"&&Q.error?Q.error:typeof Q.reason=="string"&&Q.reason?Q.reason:"unknown error";u(!1),C(`Runtime input failed: ${re}`);return}}},V))||(()=>{});return()=>{E()}},[V,q,r,c]);const xt=async(E={})=>{var Y;if(!V||!q)return{success:!1,error:"daemonId and sessionId are required"};E.preserveStatus||C(E.loadingMessage||"Loading runtime terminal...");try{const Q=await((Y=ut.requestRuntimeSnapshot)==null?void 0:Y.call(ut,V,q,{sinceSeq:E.sinceSeq,force:E.force}));return Q&&Q.success===!1?(E.preserveStatus||(u(!1),C(`Runtime terminal unavailable: ${Q.error}`)),Q):Q||{success:!0}}catch(Q){const re=(Q==null?void 0:Q.message)||String(Q);return E.preserveStatus||(u(!1),C(`Runtime terminal unavailable: ${re}`)),{success:!1,error:re}}},Ne=async E=>{var Ie,Le;const Y=((Ie=W.current)==null?void 0:Ie.ownerDocument)||document,Q=Y.defaultView||window,re=(Le=Q.navigator)==null?void 0:Le.clipboard;if(re!=null&&re.writeText&&Q.isSecureContext)try{return await re.writeText(E),!0}catch{}let ve=null;try{return ve=Y.createElement("textarea"),ve.value=E,ve.setAttribute("readonly","true"),ve.style.position="fixed",ve.style.left="-9999px",ve.style.top="0",Y.body.appendChild(ve),ve.focus(),ve.select(),Y.execCommand("copy")}catch{return!1}finally{ve==null||ve.remove()}},ze=E=>{pe(),I(E);const Y=de();ce.current={ownerWindow:Y,timeoutId:Y.setTimeout(()=>{ce.current=null,I(Q=>Q===E?null:Q)},2200)}},Je=E=>{ee(),b(E);const Y=de();ye.current={ownerWindow:Y,timeoutId:Y.setTimeout(()=>{ye.current=null,b(Q=>Q===E?null:Q)},2200)}},Ge=async()=>{var ve,Ie,Le,Se;const E=((Ie=(ve=r.current)==null?void 0:ve.getSelection)==null?void 0:Ie.call(ve))||"",Y=((Se=(Le=r.current)==null?void 0:Le.getVisibleText)==null?void 0:Se.call(Le))||"",Q=E.trimEnd()||Y.trimEnd();if(!Q){ze("Nothing to copy");return}if(!await Ne(Q)){ze("Copy failed");return}ze(E.trimEnd()?"Copied selection":"Copied visible terminal")},rt=E=>{if(!m||!c)return;((d==null?void 0:d(V,q,E))??!1)||ze("Terminal input failed")},F=async()=>{if(g)return;p(!0),b("Loading older terminal output..."),ge.current=!0;const E=await xt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),(E==null?void 0:E.success)===!1){ge.current=!1,b(`Older terminal output unavailable: ${E.error}`);return}k(!0),Je("Older terminal output loaded"),je(()=>{var Y;(Y=r.current)==null||Y.bumpResize()})};o.useEffect(()=>{var Y,Q;if(!q)return;V&&((Y=ut.getState)==null?void 0:Y.call(ut,V))==="connected"&&xt();const E=(Q=ut.onStateChange)==null?void 0:Q.call(ut,(re,ve)=>{re!==V||ve!=="connected"||xt()});return()=>{E==null||E()}},[V,q,r]),o.useEffect(()=>{t&&Be()},[t,oe,r]),o.useEffect(()=>{var re,ve;const E=W.current,Y=(ve=(re=E==null?void 0:E.ownerDocument)==null?void 0:re.defaultView)==null?void 0:ve.ResizeObserver;if(!E||!Y)return;const Q=new Y(Ie=>{const Le=Ie[0];if(!Le)return;const{width:Se,height:Pe}=Le.contentRect;_(Ee=>{const Ae=Math.round(Se),qe=Math.round(Pe);return Ee.width===Ae&&Ee.height===qe?Ee:{width:Ae,height:qe}})});return Q.observe(E),()=>Q.disconnect()},[]),o.useEffect(()=>{if($.current)return;const E=Fe();!Number.isFinite(E)||E<=0||M(Y=>H.current?E<Y-$e?E:Y:(H.current=!0,E))},[T.height,T.width,B.height,B.width]),o.useEffect(()=>{O&&_e()},[O,Te,Ce]),o.useEffect(()=>{var Q;const E=J.current;if(J.current=c,!c)return;E||k(!1),we.current&&(we.current=!1,He());const Y=be.current;Y&&(be.current=null,ht(Y.text,Y.seq,Y.cols,Y.rows,{force:!!Y.force})),V&&q&&((Q=ut.getState)==null?void 0:Q.call(ut,V))==="connected"&&xt(),te.current&&X.current===null&&ue(),je(()=>{var re;(re=r.current)==null||re.bumpResize()})},[V,c,q]),o.useEffect(()=>()=>{X.current!==null&&me(),pe(),ee()},[]),o.useEffect(()=>{const E=re=>{var Ie;const ve=re.detail;ve!=null&&ve.sessionId&&ve.sessionId!==q||m&&((Ie=r.current)==null||Ie.bumpResize())},Y=de(),Q=Y===window?[window]:[window,Y];for(const re of Q)re.addEventListener("adhdev:fit-cli-terminal",E);return()=>{for(const re of Q)re.removeEventListener("adhdev:fit-cli-terminal",E)}},[m,q,r]);const G=m&&h&&!S&&(K.atTop||!K.canScroll)||g||!!j;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:W,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[G&&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:()=>{F()},disabled:!q||g,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:g?"Loading older...":"Load older terminal output"}),j&&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:j})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[N&&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:N}),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:()=>{Ge()},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:()=>v(E=>!E),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":w,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),w&&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:()=>v(!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:()=>{$.current=!0,M(E=>{const Y=Math.max(Ue,Number((E-.1).toFixed(2)));return Y>Ue&&_e(),Y})},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:()=>{$.current=!0,M(E=>{const Y=Math.min(De,Number((E+.1).toFixed(2)));return Y>Ue&&_e(),Y})},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:Ce>0?`${Ce}px`:"100%",height:Te>0?`${Te}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:A},children:s.jsx(dc,{ref:r,readOnly:!m||!c,sizingMode:"measured",onViewportMetrics:D,onScrollMetrics:L,onInput:E=>{!m||(d==null||d(V,q,E))}})})})}),!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:x})]}),s.jsx(wc,{contextKey:e.tabKey,panelLabel:lt(e),isSending:a,isBusy:!!le,statusMessage:ke,onSend:async E=>le?!1:n(E),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const cp=5e3,lp=12e3;function dp(e){return e==="disconnected"||e==="reconnecting"}function up({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=cp,reconnectActionDelayMs:i=lp}){const c=dp(e),[l,d]=o.useState(()=>!c||a<=0),[m,u]=o.useState(()=>!c||i<=0),f=o.useRef(!1);o.useEffect(()=>{if(!c){d(!1);return}if(f.current=!1,a<=0){f.current=!0,d(!0);return}d(!1);const k=setTimeout(()=>{f.current=!0,d(!0)},a);return()=>clearTimeout(k)},[a,c]),o.useEffect(()=>{if(!c){u(!1);return}if(i<=0){u(!0);return}u(!1);const k=setTimeout(()=>{u(!0)},i);return()=>clearTimeout(k)},[i,c]);const x=c?l:e==="offline"||e==="auth_failed",C=!!(n&&e!=="auth_failed"&&(!c||m)),g=o.useMemo(()=>!t||e!=="connected"?!1:a<=0||f.current,[a,t,e]),p=e==="auth_failed"?"red":e==="offline"?"orange":"accent",j={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))"},b={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)"},h={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},y="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:[x&&s.jsx("div",{className:y,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:j[p],border:b[p],color:h[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.")]}),C&&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"})]})}),g&&s.jsx("div",{className:y,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 mp({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=o.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=o.useState(!1);if(o.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!t||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!0)};return s.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[l," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:d,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function to({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(Oa,{size:n}):s.jsx(Ut,{size:n})})}const $t="New session",Vc="A connected machine is ready. Start a new session to begin chatting, or open a workspace to launch an IDE, CLI, or ACP session.";function fp(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 pp(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 hp(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 _s({git:e,className:t="",compact:r=!1}){const n=fp(e),a=pp(e);if(!n||!a)return null;const i=[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 ${hp(a)} ${t}`.trim(),title:i.join(" · ")||n,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:n})]})}function xp({wsStatus:e,isConnected:t,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),i=a.filter(l=>l==="connected").length,c=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&c>0&&i===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:t?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function si({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function ri({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=mn(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(),i()},children:"Delete"})]})]})}function bp({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:f,onShowAllHidden:x,onResetPanelsToMain:C,inboxOpen:g,onInboxOpenChange:p,hiddenOpen:j,onHiddenOpenChange:b,onOpenNewSession:h,onOpenDashboardGuide:y,guideNudgeVisible:S=!1,actionShortcuts:k,notifications:A,notificationUnreadCount:M,onOpenNotification:w,onMarkNotificationRead:v,onMarkNotificationUnread:B,onDeleteNotification:_,onOpenGitDialog:T}){const{ides:D,p2pStates:K={}}=Qt(),L=!!e&&tt(e)&&!Ze(e),N=!!e&&Ze(e),I=l||(e?jc(e)?"terminal":"chat":null),[W,P]=o.useState(!1),$=o.useRef(null),H=o.useRef(null),J=D.filter(ne=>ne.type==="adhdev-daemon"),he=xp({wsStatus:t,isConnected:r,daemonCount:J.length,p2pStates:K}),ie=he.subtitle,te=he.tone==="connected"?"#22c55e":he.tone==="limited"?"#eab308":"#ef4444",be=he.tone==="connected"?"0 0 4px #22c55e80":he.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",we=o.useMemo(()=>A.filter(ne=>!ne.readAt),[A]),ge=o.useMemo(()=>A.filter(ne=>!!ne.readAt),[A]),X=o.useMemo(()=>we.slice(0,9),[we]),ce=M;o.useEffect(()=>{if(!g)return;const ne=de=>{var je;(je=$.current)!=null&&je.contains(de.target)||p(!1)};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[g,p]),o.useEffect(()=>{if(!j)return;const ne=de=>{var je;(je=H.current)!=null&&je.contains(de.target)||b(!1)};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[j,b]),o.useEffect(()=>{if(!j&&!g)return;const ne=de=>{if(!de.altKey)return;const je=de.code.match(/^Digit([1-9])$/);if(!je)return;const me=Number(je[1])-1,pe=j?u[me]:void 0,ee=g?X[me]:void 0;if(!(!pe&&!ee)){if(de.preventDefault(),de.stopPropagation(),pe){f==null||f(pe),b(!1);return}ee&&(w(ee),p(!1))}};return window.addEventListener("keydown",ne,!0),()=>window.removeEventListener("keydown",ne,!0)},[u,j,g,X,b,p,w,f]);const ye=ne=>{if(!ne)return;const de=n.find(je=>je.tabKey===ne);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(Ut,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?lt(e):"Dashboard"}),s.jsx("span",{title:he.title,"aria-label":he.title,className:"header-title-status-dot",style:{background:te,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:te,boxShadow:be}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[ie&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ie]}),h&&s.jsx("button",{type:"button",onClick:h,className:"btn btn-secondary btn-sm ml-2",title:`${$t}${k!=null&&k.openNewSession?` (${k.openNewSession})`:""}`,"aria-label":$t,children:s.jsx(ac,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[y&&s.jsxs("button",{type:"button",onClick:y,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&&(L||N||!Ze(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:ps(e)||lt(e),children:lt(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(_s,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(_s,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(L||N)&&c&&s.jsxs(s.Fragment,{children:[L&&d&&I&&s.jsx(to,{mode:I,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(yt,{size:14})})]}),!Ze(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(Ka,{size:14})}),!L&&!Ze(e)&&s.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Mt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:$,children:[s.jsxs("div",{className:`dashboard-header-hidden${W?" is-drop-target":""}`,ref:H,onDragEnter:ne=>{ne.dataTransfer.types.includes("text/tab-key")&&(ne.preventDefault(),P(!0))},onDragOver:ne=>{ne.dataTransfer.types.includes("text/tab-key")&&(ne.preventDefault(),ne.dataTransfer.dropEffect="move",P(!0))},onDragLeave:ne=>{ne.currentTarget.contains(ne.relatedTarget)||P(!1)},onDrop:ne=>{const de=ne.dataTransfer.getData("text/tab-key");ne.preventDefault(),P(!1),ye(de)},children:[s.jsxs("button",{type:"button",onClick:()=>b(!j),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${k!=null&&k.toggleHiddenTabs?` (${k.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Wa,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),j&&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(si,{value:k==null?void 0:k.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[C&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:C,children:"Reset panels"}),u.length>0&&x&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{x(),b(!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(si,{value:k==null?void 0:k.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:lt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(ne=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{f==null||f(ne),b(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:lt(ne)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(ne)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(ne)+1]}):null,ps(ne)]})]},ne.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!g),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(un,{size:16}),ce>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ce})]}),g&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[we.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),we.map(ne=>s.jsx(ri,{notification:ne,shortcutIndex:X.indexOf(ne)>=0?X.indexOf(ne)+1:void 0,onOpen:()=>w(ne),onMarkRead:()=>v(ne.id),onMarkUnread:()=>B(ne.id),onDelete:()=>_(ne.id)},ne.id))]}),ge.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),ge.map(ne=>s.jsx(ri,{notification:ne,onOpen:()=>w(ne),onMarkRead:()=>v(ne.id),onMarkUnread:()=>B(ne.id),onDelete:()=>_(ne.id)},ne.id))]}),A.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function vt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function gp(e,t){return String(e||"")!==String(t||"")}function yp(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),i=!!t.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(d=>String(d||"").toLowerCase()).join(`
39
- `).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!xc(c.summaryMetadata).map(d=>d.toLowerCase()).join(`
40
- `).includes(a)))}function vp(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const i=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function Gc(e,t={}){return vp(yp(e,t),t.sortMode||"recent")}function rn(e){return e?"Resume saved history":"Start fresh"}function so(e){return e?"Resuming saved history…":"Starting fresh…"}function wp(){return"Start fresh"}function qc(e,t=!1){return e==="cli"?rn(t):e==="ide"?"Start IDE":"Start ACP session"}function Yc(e,t=!1){return e==="cli"?so(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function jp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function kp(){return"Open saved history"}function Sp(){return"Saved History"}function ro(){return"Use saved history when you want continuity in the same provider conversation."}function Np(){return"No saved history found yet."}function Cp(){return"Refresh saved history"}function Tp(){return"Refreshing saved history…"}function as(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function os(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 Ps(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ds(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function no(e){return`Resume saved history with ${e}?`}function ao(){return"Review or change the target workspace before resuming saved history."}function Mp(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 oo({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:f,onSwitchSession:x,onRefreshHistory:C,onResumeSavedSession:g}){var _;const p=t.find(T=>T.id===e.routeId),j=(p==null?void 0:p.chats)||[],b=(_=p==null?void 0:p.activeChat)==null?void 0:_.id,h=tt(e)&&!Ze(e),[y,S]=o.useState(()=>vt()),k=l||y,A=String(d||"").trim(),M=T=>{if(m){m(T);return}S(T)},w=o.useMemo(()=>a.map(T=>{const D=String(T.workspace||"").trim();return T.canResume||D||!A?T:{...T,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,a]),v=o.useMemo(()=>Gc(w,{textQuery:k.textQuery,workspaceQuery:k.workspaceQuery,modelQuery:k.modelQuery,resumableOnly:k.resumableOnly,sortMode:k.sortMode}),[w,k.modelQuery,k.resumableOnly,k.sortMode,k.textQuery,k.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:h?Sp():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:ap(e)}),h&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:ro()})]}),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(yt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!h&&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"}),h?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:k.textQuery,onChange:T=>M({...k,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:k.workspaceQuery,onChange:T=>M({...k,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:k.modelQuery,onChange:T=>M({...k,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:k.sortMode,onChange:T=>M({...k,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:k.resumableOnly,onChange:T=>M({...k,resumableOnly:T.target.checked})}),"Resume-ready only"]})]}),v.map(T=>{const D=e.providerSessionId===T.providerSessionId,K=D||!T.canResume||!!c,L=T.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{K||!g||g(T)},disabled:K,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${D?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${K?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${D?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children: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:Mp(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",L?" · selected workspace":"",fs(T.summaryMetadata)?` · ${fs(T.summaryMetadata)}`:"",T.messageCount>0?` · ${T.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:D?"ACTIVE":T.canResume?L?"RESUME IN SELECTED WORKSPACE":c===T.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},T.id)})]}):j.map(T=>s.jsxs("div",{onClick:()=>{x(e.routeId,T.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===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 ${b===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),"..."]}),b===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)),(h&&!i&&v.length===0||!h&&j.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(pu,{size:32})}),s.jsx("div",{className:"text-[13px]",children:h?a.length>0?"No saved history matches these filters.":Np():"No recent chat sessions found."})]}),h&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Tp()})})]}),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:C,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(dr,{size:13})," ",h?Cp():"Refresh History"]})})})]})]});return typeof document>"u"?B:ar.createPortal(B,document.body)}const ni={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 Xc({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=ni[n.type]||ni.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=n.actions)!=null&&i.length||r&&r(n)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(yt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:l=>{l.stopPropagation(),i.onClick(),t(n.id)},children:i.label},c))})]})]},n.id)})})}const Ap=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Ip(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Rp(e){return e.sessionId||e.instanceId||e.agentType}function _n(e,t){return e||t}function Jc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Tt(r,{fallbackId:r.id}));return t}function Qc(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 io(e,t={}){return Lp(e,Qc(e,t))}function Lp(e,t={}){var f,x,C,g,p,j,b,h;const r=[],n=t.machineName,a=t.connectionState,i=Ip(e),c=e.workspace||"",l=cm(e.type,{agentName:e.cliName}),d=tt(e)||Ze(e)?l:it(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var S,k;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||it(y.providerType),status:y.status,title:y.title,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,messages:((S=y.activeChat)==null?void 0:S.messages)||[],activeModal:((k=y.activeChat)==null?void 0:k.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,surfaceHidden:y.surfaceHidden,git:y.git,settings:y.settings}}):[],u=Ap(e);if(u){const y=e.sessionId||e.instanceId,S=(f=e.settings)==null?void 0:f.meshCoordinatorFor,k=(x=e.settings)==null?void 0:x.meshNodeFor,A=S?" (Coordinator)":k?" (Mesh Node)":"",M=l+A,w=(C=e.activeChat)==null?void 0:C.activeModal,v=w&&Array.isArray(w.buttons)&&w.buttons.length>0,B=jt((g=e.activeChat)==null?void 0:g.status,{activeModal:(p=e.activeChat)==null?void 0:p.activeModal})||jt((b=(j=e.agents)==null?void 0:j[0])==null?void 0:b.status)||"idle",_=e.activeChat||{title:"",messages:[]};let T=_.title&&String(_.title).trim()?String(_.title).trim():"";const D=(h=e.activeChat)==null?void 0:h.id,K=e.chats;if(D&&Array.isArray(K)&&K.length>0){const W=K.find(P=>P.id===D||P.id&&String(P.id)===String(D));W!=null&&W.title&&String(W.title).trim()&&(T=String(W.title).trim())}const L=(tt(e)||Ze(e),e.type),N=(tt(e)||Ze(e))&&Ho(T,M,L)?"":T,I=_.messages||[];r.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:tt(e)?e.mode||"terminal":"chat",agentName:M,agentType:L,status:B,title:N,messages:I,resume:e.resume,hostIdeType:!tt(e)&&!Ze(e)?e.type:void 0,workspaceName:i,workspacePath:c,git:e.git,displayPrimary:N||i||(tt(e)?e.mode==="chat"?M:`Terminal${A}`:M),displaySecondary:tt(e)&&i?M: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:v?w.buttons:void 0,modalMessage:v?w.message:void 0,streamSource:"native",tabKey:_n(y,e.id),machineName:n,connectionState:a,settings:e.settings})}if(u&&(tt(e)||Ze(e)))return r;for(const y of m){const S=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,k=lm(y),A=Rp(y),M=`${e.id}:${A}`,w=y.title&&String(y.title).trim()||"",v=Ho(w,y.agentName,y.agentType)?"":w,B=y.messages||[];(y.transport==="cdp-webview"||y.sessionId||y.providerSessionId||B.length>0||S||v||!["idle","panel_hidden","disconnected","not_monitored"].includes(k))&&r.push({routeId:e.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:y.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:y.sessionCapabilities,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:k,title:v,messages:B,hostIdeType:e.type,workspaceName:i,workspacePath:c,git:y.git||e.git,displayPrimary:v||i||y.agentName||d,displaySecondary:`${d} · ${y.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,lastUpdated:y.lastUpdated||e.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,modalButtons:S?y.activeModal.buttons:void 0,modalMessage:S?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:_n(y.sessionId||y.instanceId,M),machineName:n,connectionState:a,settings:y.settings})}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:i,workspacePath:c,git:e.git,displayPrimary:i||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:_n(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings}),r}function _p(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 Zc(e,t){const r=_p(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const el=[{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:"🏄"}],tl=[{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:"🧩"}],sl=[{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:"🟠"}],Pp=el,Dp=tl,Ep=sl;function zt(...e){return Td(Md(e))}function $p({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:zt("dashboard-header",i),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function tr({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx($p,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:zt("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const Sa="adhdev:themechange";function Bp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function vs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function ws(e){return e==="system"?Bp():e}function rl(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Or(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Sa,{detail:{preference:e,theme:t}}))}function Kp(){const e=vs(),t=ws(e);rl(t),Or(e,t)}function co(){const[e,t]=o.useState(vs),[r,n]=o.useState(()=>ws(vs()));o.useEffect(()=>{rl(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),Or("system",m)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=d=>{const m=d.detail||{},u=m.preference,f=m.theme;t(u==="dark"||u==="light"||u==="system"?u:vs()),n(f==="dark"||f==="light"?f:ws(vs()))},l=d=>{if(d.key!=="theme")return;const m=vs(),u=ws(m);t(m),n(u)};return window.addEventListener(Sa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(Sa,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=ws(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Or(c,l)},[]),i=o.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=ws(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Or(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const ai={dark:"Dark",light:"Light",system:"System"};function Wp({collapsed:e}){const{preference:t,cycleTheme:r}=co(),n=t==="dark"?s.jsx(xu,{size:16}):t==="light"?s.jsx(hu,{size:16}):s.jsx(bu,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ai[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:ai[t]})]})}function Pn(e,t){return e?typeof e=="function"?e(t):e:null}function Op({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=o.useState(!1),[f,x]=o.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),C=()=>u(!0),g=()=>u(!1),p=()=>{x(y=>{const S=!y;try{localStorage.setItem(d,S?"1":"0")}catch{}return S})},j=o.useMemo(()=>({collapsed:f,mobileMenuOpen:m,openMobileMenu:C,closeMobileMenu:g,toggleCollapsed:p}),[f,m]),b=y=>`nav-item${y.active?" active":""} cursor-pointer ${f?"justify-center py-2.5 px-0":""}${y.className?` ${y.className}`:""}`,h=y=>s.jsxs("div",{className:b(y),id:`nav-${y.id}`,onClick:()=>{y.onSelect(),g()},title:f?y.title??(typeof y.label=="string"?y.label:void 0):y.title,children:[s.jsx("span",{className:"nav-icon",children:y.icon}),!f&&y.label]},y.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:C,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:g,onKeyDown:y=>y.key==="Escape"&&g()}),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:Pn(t,j)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:g,children:s.jsx(yt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(h)}),n.map(y=>s.jsxs("div",{className:y.className??"border-t border-border-subtle pt-2 mt-2",children:[!f&&y.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:y.title}):null,y.items.map(h)]},y.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(h),Pn(i,j),s.jsx(Wp,{collapsed:f}),Pn(c,j)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function kt({title:e,icon:t,description:r,accentColor:n,className:a,children:i}){return s.jsxs("div",{className:zt("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function nn({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:zt("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 Fp={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"},Hp={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ss({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:zt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Fp[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Hp[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 Dn({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:zt("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 En(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:zt("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 Up={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"},zp={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Vp({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:zt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Up[e],r),children:[s.jsx("span",{className:zt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",zp[e])}),n]})}function ts({label:e,description:t,checked:r,disabled:n,onChange:a,extra:i}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,s.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Gp({onPrefChange:e}){const[t,r]=ym(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(un,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>i("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Mt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>i("browserNotifications",c)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{yc().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(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(gu,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(yu,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Is,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function an(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function qp(e,t){const r=an(e),n=an(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 nl(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function sr(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||qp(r,t)>=0)return!1;const n=an(r),a=an(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Yp(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function $n(e,t){return e instanceof Error?e.message:t}function Xp({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(nn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:t||"Install ADHDev on a machine and sign in to connect it here."}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>s.jsx(Qp,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function oi({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return ar.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:i,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function Jp(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Pp,...Dp,...Ep].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 Qp({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var K,L;const[i,c]=o.useState("idle"),[l,d]=o.useState(""),[m,u]=o.useState(null),[f,x]=o.useState("idle"),[C,g]=o.useState(""),p=e.version||null,j=((K=e.machine)==null?void 0:K.platform)||((L=e.system)==null?void 0:L.platform)||"",b=Tt(e,{fallbackId:e.id}),h=j==="win32"?"🪟":j==="darwin"?"🍎":"🐧",y=t.filter(N=>N.daemonId===e.id&&N.transport==="cdp-page"),S=t.filter(N=>N.daemonId===e.id&&N.transport==="pty"),k=t.filter(N=>N.daemonId===e.id&&N.transport==="acp"),A=e.p2p,M=async()=>{if(r){c("upgrading"),d("Starting upgrade...");try{const N=Yp(await r(e.id,"daemon_upgrade",{}));N.alreadyLatest?(c("done"),d(`Already on v${N.version||"latest"}.`)):N.upgraded||N.success?(c("done"),d(`Upgrade to v${N.version||"latest"} started. Daemon is restarting...`)):(c("error"),d(N.error||"Upgrade failed"))}catch(N){c("error"),d($n(N,"Connection lost during upgrade"))}}},w=async()=>{if(u(null),!!n){x("loading");try{await n(e.id),x("done"),g("Machine disconnected.")}catch(N){x("error"),g($n(N,"Failed to disconnect"))}}},v=async()=>{if(u(null),!!a){x("loading");try{await a(e.id),x("done"),g("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(N){x("error"),g($n(N,"Failed to revoke token"))}}},B="0.9.75",_=nl(e,B),T=sr(e,B),D=y.length+S.length+k.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:h}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:b}),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:M,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${B}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${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(Vp,{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:[A&&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 ${A.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${A.state==="connecting"||A.state==="new"?"animate-pulse":""}`,style:A.state==="connecting"||A.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",A.state==="connected"?"connected":A.state==="connecting"||A.state==="new"?"connecting...":A.state||"off"]}),A.peers!==void 0&&A.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",A.peers," peer",A.peers!==1?"s":"",")"]})]}),A&&D>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),D>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[y.map(N=>{const I=Jp(N.type),W=N.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:I.icon}),s.jsx("span",{children:I.name}),W!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${W?"bg-green-400":"animate-pulse"}`,style:W?void 0:{background:"var(--status-warning)"},title:W?"CDP connected":"CDP connecting..."})]},N.id)}),S.map(N=>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:N.cliName||"CLI"})]},N.id)),k.map(N=>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:N.cliName||"ACP"})]},N.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||C)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-red-400":i==="done"||f==="done"?"text-green-400":"text-text-muted"}`,children:C||l})]}),m==="disconnect"&&s.jsx(oi,{title:"🔌 Disconnect Machine",message:`Disconnect "${b}" from ADHDev?
38
+ \`\`\``}function Rn(e,t){return`${e}:${t}`}function uf(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Us(e,t){uf()&&console.debug(`[subscription-manager] ${e}`,t)}class mf{constructor(){Qe(this,"active",new Map);Qe(this,"retryTimers",new Map)}subscribe(t,r,n,a,i){var u;const c=Rn(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),Us("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(i!=null&&i.retryIntervalMs)&&this.scheduleRetry(c,t,i.retryIntervalMs)}const m=()=>{var C;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 x={type:"unsubscribe",topic:n.topic,key:n.key};Us("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(C=t.sendData)==null||C.call(t,r,x)};return m.initialSendAccepted=d,m}publish(t){const r=Rn(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Ms.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),Ms.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=Rn(t,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(t){var r;Us("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=t.sendData)==null||r.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,r){var a;const n=Array.from(this.active.values()).filter(i=>i.daemonId===t);Us("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}scheduleRetry(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var l;this.retryTimers.delete(t);const i=this.active.get(t);if(!i)return;const c=((l=r.sendData)==null?void 0:l.call(r,i.daemonId,i.request))??!1;Us("subscribe_retry",{id:t,accepted:c,topic:i.request.topic,key:i.request.key}),c||this.scheduleRetry(t,r,n)},n);this.retryTimers.set(t,a)}clearRetry(t){const r=this.retryTimers.get(t);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(t))}}const Ht=new mf;function ff(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 i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function pf(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 rn(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=t,l=c||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:m,childrenByParent:u}=pf(d),f=ff(i,n),x=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,C=m.filter(g=>g.kind==="workspace"&&g.transport==="cdp-page"),y=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},...x&&{machine:x,platform:x.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:C.some(g=>!!g.cdpConnected)});for(const g of C){const b=f.get(g.id),h=Xs(g,b),k=(u.get(g.id)||[]).map(S=>Xs(S,f.get(S.id)));r.push({id:`${n}:ide:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(b==null?void 0:b.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:n,instanceId:g.id,workspace:h.workspace,terminals:0,childSessions:k,agents:k.map(S=>({id:S.id,name:S.providerName||S.providerType,type:S.providerType,status:S.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},timestamp:l})}for(const g of y){const b=f.get(g.id),h=Xs(g,b);r.push({id:`${n}:cli:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(b==null?void 0:b.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:g.id,cliName:h.providerName||h.providerType,mode:h.mode||(b==null?void 0:b.mode)||"terminal",workspace:h.workspace||"",activeChat:h.activeChat,...h.resume!==void 0&&{resume:h.resume},...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},timestamp:l,_isCli:!0})}for(const g of p){const b=f.get(g.id),h=Xs(g,b);r.push({id:`${n}:acp:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(b==null?void 0:b.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:g.id,cliName:h.providerName||h.providerType,mode:"chat",workspace:h.workspace||"",activeChat:h.activeChat,...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},timestamp:l,_isAcp:!0})}return r}const hf=15e3,xf=15e3,bf=6e4,gf=1200,Qo=12,yf=8e3,vf=4e3,Ln=new Map,_n=new Map,Mr=new Set,er=new Map;function wf(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 Zo(e,t){const r=er.get(e);!r||r.size===0||(er.delete(e),r.forEach(n=>n(t)))}function jf(e,t){return new Promise(r=>{const n=er.get(e)||new Set;er.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&er.delete(e),r(c)},i=setTimeout(()=>a(!1),t);n.add(a)})}function fr(){const{sendCommand:e,sendData:t}=gt(),{injectEntries:r,getIdes:n}=or();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??bf,l=_n.get(a)||0;if(!(i!=null&&i.force)&&Mr.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const d=Ln.get(a);if(d)return d;const m=(async()=>{if(t&&!Mr.has(a)){const p=Ht.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},g=>{const b=n(),h=b.find(S=>S.id===a),k=rn(g.status,{daemonId:a,existingDaemon:h,existingEntries:b,timestamp:g.timestamp});k.length>0&&r(k),_n.set(a,Date.now()),Zo(a,!0)});if(p.initialSendAccepted?Mr.add(a):Mr.delete(a),!(i!=null&&i.force)&&p.initialSendAccepted&&await jf(a,gf))return}const u=await e(a,"get_status_metadata"),f=wf(u);if(!f)return;const x=n(),C=x.find(p=>p.id===a),y=rn(f,{daemonId:a,existingDaemon:C,existingEntries:x,timestamp:f.timestamp||Date.now()});y.length>0&&r(y,{authoritativeDaemonIds:[a]}),_n.set(a,Date.now()),Zo(a,!0)})().finally(()=>{Ln.delete(a)});return Ln.set(a,m),m},[n,r,e,t])}function kf(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const Sf=60,Nf=50;function Pc(e={}){return e.isCliLike?Nf:Sf}function Cf(e={}){return Pc(e)}function St(e){return(typeof e=="string"?e.trim():"")||void 0}function Ft(e,t){const r=St(t);return r?`${e}:${r}`:void 0}function qt(e,t,r){const n=Ft(t,r),a=St(r);n&&e.push(n),a&&e.push(a)}function ks(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function Dc(e){return St(e.providerSessionId)||St(e.sessionId)||St(e.tabKey)||St(e.routeId)}function Za(e){return ks([St(e.providerSessionId),St(e.sessionId)])}function Ts(e){const t=[];return qt(t,"provider",e.providerSessionId),qt(t,"session",e.sessionId),qt(t,"tab",e.tabKey),qt(t,"route",e.routeId),ks(t)}function Tf(e){const t=[];return St(e.providerSessionId)?(qt(t,"provider",e.providerSessionId),ks(t)):St(e.sessionId)?(qt(t,"session",e.sessionId),ks(t)):St(e.tabKey)?(qt(t,"tab",e.tabKey),ks(t)):St(e.routeId)?(qt(t,"route",e.routeId),ks(t)):[]}function eo(e){return Ft("provider",e.providerSessionId)||Ft("session",e.sessionId)||Ft("tab",e.tabKey)||Ft("route",e.routeId)||"unknown:"}function pr(e){return Za(e)[0]}function Mf(e){const t=St(e.providerSessionId),r=St(e.sessionId),n=St(e.tabKey),a=St(e.routeId),i=[Ft("provider",t),Ft("session",r),Ft("tab",n),Ft("route",a)].filter(d=>typeof d=="string"),c=Ts({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=eo({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:Dc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:pr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function ja(e,t){const r=Mf(e);return Tf(t).some(n=>r.lookupKeys.includes(n))}const hr=60,Af=1e3,to=12e4,If=new Set(["generating","waiting_approval","starting","streaming","working"]),ei=new Map;function Ec(e,t){return`${e}::${t}`}function ka(e=hr){return{liveMessages:[],cursor:Rf([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Rf(e,t=hr){return{tailLimit:t}}function ti(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 Lf{constructor(t){Qe(this,"manager");Qe(this,"sendData");Qe(this,"daemonId");Qe(this,"sessionId");Qe(this,"historySessionId");Qe(this,"subscriptionKey");Qe(this,"snapshot");Qe(this,"transportSubscription",null);Qe(this,"listeners",new Set);Qe(this,"retainCount",0);Qe(this,"loadHistoryPromise",null);Qe(this,"pendingDisconnectTimer",null);this.manager=t.manager||Ht,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=ka(Math.max(0,t.tailLimit??hr))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);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=await t({offset:this.snapshot.historyOffset,excludeRecentCount:this.snapshot.liveMessages.length}),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},...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:Af}))}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};ti(this.snapshot.liveMessages)===ti(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,cursor:n},this.emit())}}function $c(e){const t=Ec(e.daemonId,e.sessionId),r=ei.get(t);if(r)return r.updateOptions(e),r;const n=new Lf(e);return ei.set(t,n),n}function _f(e,t){return{...e,loadHistoryPage:t}}function Pf(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Df(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(If.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??to)),i=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return i>0?n-i<=a:Array.isArray(e.messages)&&e.messages.length>0}function Ef(e=to){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function $f(e,t={}){const r=new Set,n=[];for(const a of e){if(!Df(a,t))continue;const i=mr(a),c=a.sessionId||"";if(!i||!c)continue;const l=Ec(i,c);if(r.has(l))continue;r.add(l);const d=pr(a);n.push({daemonId:i,sessionId:c,historySessionId:d||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Pf),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Bf(e,t){const{sendData:r,sendCommand:n}=gt(),a=(t==null?void 0:t.enabled)!==!1,i=mr(e),c=e.sessionId||"",l=pr(e)||c,d=`daemon:${i}:session:${c}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??hr),u=o.useMemo(()=>!a||!i||!c?null:$c({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:d,sendData:r,tailLimit:m}),[i,a,l,r,c,d,m]),[f,x]=o.useState(()=>(u==null?void 0:u.getSnapshot())||ka(m));o.useEffect(()=>{if(!u){x(ka(m));return}u.retain(),x(u.getSnapshot());const y=u.subscribe(p=>{x(p)});return()=>{y(),u.release()}},[u,m]);const C=o.useCallback(async()=>{!u||!i||!c||await u.loadHistoryPage(async({offset:y,excludeRecentCount:p})=>{const g=e.agentType,b=await n(i,"chat_history",{agentType:g,offset:y,limit:30,targetSessionId:c,historySessionId:l,excludeRecentCount:p}),h=b&&typeof b=="object"&&"result"in b?b.result||{}:b||{};return{messages:Array.isArray(h.messages)?h.messages:[],hasMore:h.hasMore===!0}})},[e.agentType,u,i,l,n,c]);return o.useMemo(()=>_f(f,C),[C,f])}function Kf(e,t){const{sendData:r}=gt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??hr),i=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??to)),c=Ef(i),[l,d]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(f=>f+1)},c);return()=>{clearInterval(u)}},[e.length,n,c]);const m=o.useMemo(()=>$f(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(f=>$c({...f,sendData:r,tailLimit:a}));return u.forEach(f=>{f.retain()}),()=>{u.forEach(f=>f.release())}},[m.signature,n,r,a])}function Wf(e,t){return t?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function si(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 Of(e,t){if(e.length===0)return[];if(t.some(si))return[];const r=[],n=new Set;for(let a=e.length-1;a>=0&&r.length<2;a-=1){const i=e[a];if(!i||!si(i))continue;const c=String(i.role||"").toLowerCase();n.has(c)||(n.add(c),r.unshift(i))}return r}function Ff(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),i=a>0?r.slice(0,a):[],c=a>0?r.slice(-n):r,l=Of(i,c),d=l.length>0?[...l,...c]:c;return t.length===0?d:[...t,...d]}function Hf(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Uf(e){return Hf(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function zf(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Vf(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function Gf(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Bc(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Kc(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 qf(e){return Bc(e)?!1:e.inboxBucket==="task_complete"&&Kc(e).length>0}function ri(e){return e.branch||"detached HEAD"}function Yf(e){if(e.error)return`${ri(e)} · Git error: ${e.error}`;const t=[ri(e)];return e.changedFiles>0?t.push(zf(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 Xf(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Yf(t)}`}function Jf(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function Qf(e,t={}){if(t.enabled===!1)return[];if(!Gf(e))return[];const r=Bc(e)?"working":qf(e)?"complete":null;if(!r)return[];const n=r==="complete"?Kc(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Vf(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:Xf(r,e.git),timestamp:Jf(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 Zf=60;function Sa({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:d,scrollToBottomRequestNonce:m,isInputActive:u=!0,isVisible:f=!0}){var ce,ye,ne,de,je,me,pe;const x=o.useRef(new Map),C=o.useRef(void 0),y=fr(),{sendCommand:p}=gt(),{isVisible:g}=Va();ur("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const b=Ct.useMemo(()=>Bs(e),[e.status,e.connectionState]),h=o.useMemo(()=>ef(e,t),[e,t]),k=o.useMemo(()=>{var ee;return Ya((ee=h.targetEntry)==null?void 0:ee.providerControls,{hostIdeType:e.hostIdeType,providerType:h.providerType})},[e.hostIdeType,h.providerType,(ce=h.targetEntry)==null?void 0:ce.providerControls]),S=Pc({isCliLike:h.isCli||h.isAcp}),j=Cf({isCliLike:h.isCli||h.isAcp}),A=Bf(e,{enabled:f&&!!e.sessionId,tailLimit:j}),[M,w]=o.useState(S),v=e.tabKey,B=A.historyMessages,_=A.hasMoreHistory,T=A.historyError,D=Wf(e,A);o.useEffect(()=>{w(S)},[S,v]);const K=Math.max(0,D.length-M),L=Xa(e),N=mr(e),I=Uf(e),F=Ja(e),P=a||F,$=!!F,[H,J]=o.useState(!1);o.useEffect(()=>{const ee=h.targetEntry;N&&(!ee||ee.providerControls===void 0||ee.controlValues===void 0)&&y(N,{minFreshMs:3e4}).catch(()=>{})},[N,h.isAcp,(ye=h.targetEntry)==null?void 0:ye.providerControls,(ne=h.targetEntry)==null?void 0:ne.controlValues,y]);const he=o.useCallback(async()=>{if(!H){if(D.length>M){w(ee=>Math.min(D.length,ee+Zf));return}J(!0);try{await A.loadHistoryPage()}finally{J(!1)}}},[A,H,D.length,M]),{allMessages:ie,receivedAtMap:te}=o.useMemo(()=>{const ee=Ff({historyMessages:B,liveMessages:D,visibleLiveCount:M}),ue=Qf(e),oe=ue.length>0?[...ee,...ue]:ee,q={};return oe.forEach((V,le)=>{const ke=`${e.tabKey}:${Jr(V,le)}`;let Z=kf(V)||x.current.get(ke)||0;Z||(Z=Date.now(),x.current.set(ke,Z)),q[Jr(V,le)]=Z}),{allMessages:oe,receivedAtMap:q}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,K,B,D,M]),be=o.useMemo(()=>l.filter(ee=>ee.routeId===e.tabKey).sort((ee,ue)=>ee.timestamp-ue.timestamp),[l,e.tabKey]),we=o.useCallback(async()=>{var le,ke;if(!N)return;const ee=Ic({activeConv:e,visibleMessages:ie,actionLogs:l,controls:(le=h.targetEntry)==null?void 0:le.providerControls,controlValues:(ke=h.targetEntry)==null?void 0:ke.controlValues,visibleBarControlCount:k.length,chatTailState:{hasMoreHistory:_,historyError:T,historyMessages:B},ui:{controlsVisible:g,visibleLiveCount:M,hiddenLiveCount:K,isInputActive:u,isVisible:f}}),ue=await p(N,"get_chat_debug_bundle",{agentType:h.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:ee}),oe=sn(ue),q=_c(oe),V=await Lc(q);V==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),at.showToast(Rc(oe,{locatorCopyStatus:V}),V==="failed"?"warning":"success")},[e,l,ie,g,h.providerType,(de=h.targetEntry)==null?void 0:de.controlValues,(je=h.targetEntry)==null?void 0:je.providerControls,N,_,K,B,u,f,T,p,k.length,M]),ge=o.useCallback(()=>{const ee=df(C.current);C.current=ee.state,ee.shouldCollect&&we().catch(ue=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",ue),at.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[we]),X=o.useMemo(()=>{if(D.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((b.isGenerating||e.status==="streaming")&&J(!1),e.status==="not_monitored"&&I)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(Is,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ms,{size:14})," Open ",L," 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"&&I)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(ac,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ms,{size:14})," Open ",L," 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"&&!H)return!_&&B.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,I,i,_,B.length,c,H,D.length,L,b.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[s.jsx(Fu,{messages:ie,actionLogs:be,agentName:Rs(e)||L||"Agent",userName:d,isCliMode:h.isCli||h.isAcp,isWorking:b.isGenerating,contextKey:e.tabKey,receivedAtMap:te,lastMessageHash:e.lastMessageHash,onLoadMore:he,isLoadingMore:H,hasMoreHistory:_,hiddenLiveCount:K,loadError:T??void 0,emptyState:X,scrollToBottomRequestNonce:m,isVisible:f}),s.jsx(zm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:h.providerType,displayLabel:h.displayLabel,controls:(me=h.targetEntry)==null?void 0:me.providerControls,controlValues:(pe=h.targetEntry)==null?void 0:pe.controlValues,isActive:u,isCliTerminal:h.isCliTerminal}),!h.isCliTerminal&&s.jsx(jc,{contextKey:e.tabKey,panelLabel:L,isSending:n,isBusy:$,statusMessage:P,onSend:r,isActive:u,showControlsToggle:k.length>0,onControlsToggle:ge})]})}let Wc=Qt;function Oc(){return Wc()}class ep{constructor(){Qe(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 Fc=new ep;class tp{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 ut=new tp;function sp(e){e.dashboardWS&&(Fc=e.dashboardWS),e.connectionManager&&(ut=e.connectionManager),e.useDaemonsHook&&(Wc=e.useDaemonsHook)}const rp=.5,np=1.25;function lt(e){return Xa(e)}function ps(e){return Tc(e).join(" · ")}function Hc(e){const t=Cc(e);return t||(e.title?e.title:ps(e)||"No messages yet")}function Uc(e,t){const{isReconnecting:r,isConnecting:n}=Bs(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function ap(e,t){const r=["Chat",...Tc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function ns(e){return Uc(e)||ps(e)}function op(e){return`${lt(e)} · ${Hc(e)}`}function ip(e){const t=tn(e),r=t?it(t):Rs(e);return`${lt(e)} — ${r||"Agent"}`}function cp(e){return Rs(e)||"CLI"}function zc(e){return Nc(e)}function Vc(e){return e?`Remote · ${lt(e)||e.workspaceName||"Session"}`:"Remote"}function lp({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var se;Qt();const{sendPtyInput:d}=gt(),[m,u]=o.useState(!1),f=o.useRef(!1);f.current=m;const[x,C]=o.useState("Runtime terminal unavailable"),[y,p]=o.useState(!1),[g,b]=o.useState(null),[h,k]=o.useState(!1),[S,j]=o.useState(!1),[A,M]=o.useState(1),[w,v]=o.useState(!1),[B,_]=o.useState({width:0,height:0}),[T,D]=o.useState({width:0,height:0}),[K,L]=o.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[N,I]=o.useState(null),F=o.useRef(null),P=o.useRef(null),$=o.useRef(!1),H=o.useRef(!1),J=o.useRef(c),he=o.useRef(0),ie=o.useRef(!1),te=o.useRef(""),be=o.useRef(null),we=o.useRef(!1),ge=o.useRef(!1),X=o.useRef(null),ce=o.useRef(null),ye=o.useRef(null),ne=32*1024,de=()=>{var E,Y,Q,re;return((Y=(E=F.current)==null?void 0:E.ownerDocument)==null?void 0:Y.defaultView)||((re=(Q=P.current)==null?void 0:Q.ownerDocument)==null?void 0:re.defaultView)||window},je=E=>{const Y=de();return{ownerWindow:Y,frameId:Y.requestAnimationFrame(E)}},me=()=>{const E=X.current;if(E){try{E.ownerWindow.cancelAnimationFrame(E.frameId)}catch{}X.current=null}},pe=()=>{const E=ce.current;if(E){try{E.ownerWindow.clearTimeout(E.timeoutId)}catch{}ce.current=null}},ee=()=>{const E=ye.current;if(E){try{E.ownerWindow.clearTimeout(E.timeoutId)}catch{}ye.current=null}},ue=()=>{c&&X.current===null&&(X.current=je(()=>{st()}))},oe=e.tabKey,q=e.sessionId||"",V=e.daemonId||((se=e.routeId)==null?void 0:se.split(":")[0])||e.routeId||"",le=Ja(e),ke=m?i||le:x,Z=rp,De=np,$e=.05,Fe=()=>{const E=T.width,Y=T.height;if(!Number.isFinite(B.width)||B.width<=0||!Number.isFinite(B.height)||B.height<=0||!Number.isFinite(E)||E<=0||!Number.isFinite(Y)||Y<=0)return 1;const Q=B.width/E,re=B.height/Y;return Number(Math.min(De,Math.max(Z,Math.min(Q,re))).toFixed(2))},Ue=Fe(),W=$.current&&A>Ue,Ce=Number.isFinite(T.width)&&T.width>0?Math.max(B.width,Math.round(T.width*A)):B.width,Te=Number.isFinite(T.height)&&T.height>0?Math.max(B.height,Math.round(T.height*A)):B.height,_e=()=>{je(()=>{const E=P.current;E&&(E.scrollLeft=0,E.scrollTop=E.scrollHeight-E.clientHeight)})},Be=()=>{var E,Y;he.current=0,ie.current=!1,te.current="",be.current=null,we.current=!1,ge.current=!1,$.current||(H.current=!1,M(1)),X.current!==null&&me(),u(!1),C("Runtime terminal unavailable"),ee(),pe(),b(null),I(null),v(!1),p(!1),k(!1),j(!1),(Y=(E=r.current)==null?void 0:E.reset)==null||Y.call(E)},He=()=>{var E,Y;he.current=0,ie.current=!1,te.current="",be.current=null,we.current=!1,ge.current=!1,X.current!==null&&me(),u(!0),C(""),ee(),pe(),b(null),I(null),v(!1),p(!1),k(!1),j(!1),(Y=(E=r.current)==null?void 0:E.reset)==null||Y.call(E)},Xe=()=>{ge.current&&(ge.current=!1,je(()=>{var E,Y;(Y=(E=r.current)==null?void 0:E.scrollToTop)==null||Y.call(E)}))},st=()=>{if(X.current=null,!c)return;const E=te.current;if(!E)return;const Y=E.slice(0,ne);te.current=E.slice(Y.length);const Q=r.current;if(!Q){te.current=Y+te.current,ue();return}Q.write(Y,()=>{if(te.current.length>0){ue();return}Xe()})},mt=E=>{E&&(te.current+=E,ue())},ht=(E,Y=0,Q,re,ve={})=>{var Le,Se,Pe,Ee;const Ie=!!ve.force;!Ie&&Y>0&&he.current>=Y||!Ie&&Y===0&&ie.current||(he.current=Y,Y>0&&k(!0),u(!0),C(""),typeof Q=="number"&&typeof re=="number"&&Q>0&&re>0&&((Se=(Le=r.current)==null?void 0:Le.resize)==null||Se.call(Le,Q,re)),te.current="",(Ee=(Pe=r.current)==null?void 0:Pe.reset)==null||Ee.call(Pe),E?mt(E):Xe())};o.useEffect(()=>{Be()},[q]),o.useEffect(()=>{var Y;if(!q)return;const E=((Y=ut.onRuntimeEvent)==null?void 0:Y.call(ut,q,Q=>{if(!(!Q||Q.sessionId!==q)){if(Q.type==="runtime_snapshot"){if(!c){be.current={text:Q.text||"",seq:Q.seq||0,cols:Q.cols,rows:Q.rows,force:!!Q.force};return}ht(Q.text||"",Q.seq||0,Q.cols,Q.rows,{force:!!Q.force});return}if(Q.type==="session_output"){ie.current=!0,typeof Q.seq=="number"&&(he.current=Math.max(he.current,Q.seq),Q.seq>0&&k(!0)),f.current||u(!0),f.current||C(""),typeof Q.data=="string"&&mt(Q.data);return}if(Q.type==="session_cleared"){if(!c){we.current=!0,te.current="",be.current=null;return}He();return}if(Q.type==="session_io_error"){const re=typeof Q.error=="string"&&Q.error?Q.error:typeof Q.reason=="string"&&Q.reason?Q.reason:"unknown error";u(!1),C(`Runtime input failed: ${re}`);return}}},V))||(()=>{});return()=>{E()}},[V,q,r,c]);const xt=async(E={})=>{var Y;if(!V||!q)return{success:!1,error:"daemonId and sessionId are required"};E.preserveStatus||C(E.loadingMessage||"Loading runtime terminal...");try{const Q=await((Y=ut.requestRuntimeSnapshot)==null?void 0:Y.call(ut,V,q,{sinceSeq:E.sinceSeq,force:E.force}));return Q&&Q.success===!1?(E.preserveStatus||(u(!1),C(`Runtime terminal unavailable: ${Q.error}`)),Q):Q||{success:!0}}catch(Q){const re=(Q==null?void 0:Q.message)||String(Q);return E.preserveStatus||(u(!1),C(`Runtime terminal unavailable: ${re}`)),{success:!1,error:re}}},Ne=async E=>{var Ie,Le;const Y=((Ie=F.current)==null?void 0:Ie.ownerDocument)||document,Q=Y.defaultView||window,re=(Le=Q.navigator)==null?void 0:Le.clipboard;if(re!=null&&re.writeText&&Q.isSecureContext)try{return await re.writeText(E),!0}catch{}let ve=null;try{return ve=Y.createElement("textarea"),ve.value=E,ve.setAttribute("readonly","true"),ve.style.position="fixed",ve.style.left="-9999px",ve.style.top="0",Y.body.appendChild(ve),ve.focus(),ve.select(),Y.execCommand("copy")}catch{return!1}finally{ve==null||ve.remove()}},ze=E=>{pe(),I(E);const Y=de();ce.current={ownerWindow:Y,timeoutId:Y.setTimeout(()=>{ce.current=null,I(Q=>Q===E?null:Q)},2200)}},Je=E=>{ee(),b(E);const Y=de();ye.current={ownerWindow:Y,timeoutId:Y.setTimeout(()=>{ye.current=null,b(Q=>Q===E?null:Q)},2200)}},Ge=async()=>{var ve,Ie,Le,Se;const E=((Ie=(ve=r.current)==null?void 0:ve.getSelection)==null?void 0:Ie.call(ve))||"",Y=((Se=(Le=r.current)==null?void 0:Le.getVisibleText)==null?void 0:Se.call(Le))||"",Q=E.trimEnd()||Y.trimEnd();if(!Q){ze("Nothing to copy");return}if(!await Ne(Q)){ze("Copy failed");return}ze(E.trimEnd()?"Copied selection":"Copied visible terminal")},rt=E=>{if(!m||!c)return;((d==null?void 0:d(V,q,E))??!1)||ze("Terminal input failed")},O=async()=>{if(y)return;p(!0),b("Loading older terminal output..."),ge.current=!0;const E=await xt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),(E==null?void 0:E.success)===!1){ge.current=!1,b(`Older terminal output unavailable: ${E.error}`);return}j(!0),Je("Older terminal output loaded"),je(()=>{var Y;(Y=r.current)==null||Y.bumpResize()})};o.useEffect(()=>{var Y,Q;if(!q)return;V&&((Y=ut.getState)==null?void 0:Y.call(ut,V))==="connected"&&xt();const E=(Q=ut.onStateChange)==null?void 0:Q.call(ut,(re,ve)=>{re!==V||ve!=="connected"||xt()});return()=>{E==null||E()}},[V,q,r]),o.useEffect(()=>{t&&Be()},[t,oe,r]),o.useEffect(()=>{var re,ve;const E=F.current,Y=(ve=(re=E==null?void 0:E.ownerDocument)==null?void 0:re.defaultView)==null?void 0:ve.ResizeObserver;if(!E||!Y)return;const Q=new Y(Ie=>{const Le=Ie[0];if(!Le)return;const{width:Se,height:Pe}=Le.contentRect;_(Ee=>{const Ae=Math.round(Se),qe=Math.round(Pe);return Ee.width===Ae&&Ee.height===qe?Ee:{width:Ae,height:qe}})});return Q.observe(E),()=>Q.disconnect()},[]),o.useEffect(()=>{if($.current)return;const E=Fe();!Number.isFinite(E)||E<=0||M(Y=>H.current?E<Y-$e?E:Y:(H.current=!0,E))},[T.height,T.width,B.height,B.width]),o.useEffect(()=>{W&&_e()},[W,Te,Ce]),o.useEffect(()=>{var Q;const E=J.current;if(J.current=c,!c)return;E||j(!1),we.current&&(we.current=!1,He());const Y=be.current;Y&&(be.current=null,ht(Y.text,Y.seq,Y.cols,Y.rows,{force:!!Y.force})),V&&q&&((Q=ut.getState)==null?void 0:Q.call(ut,V))==="connected"&&xt(),te.current&&X.current===null&&ue(),je(()=>{var re;(re=r.current)==null||re.bumpResize()})},[V,c,q]),o.useEffect(()=>()=>{X.current!==null&&me(),pe(),ee()},[]),o.useEffect(()=>{const E=re=>{var Ie;const ve=re.detail;ve!=null&&ve.sessionId&&ve.sessionId!==q||m&&((Ie=r.current)==null||Ie.bumpResize())},Y=de(),Q=Y===window?[window]:[window,Y];for(const re of Q)re.addEventListener("adhdev:fit-cli-terminal",E);return()=>{for(const re of Q)re.removeEventListener("adhdev:fit-cli-terminal",E)}},[m,q,r]);const G=m&&h&&!S&&(K.atTop||!K.canScroll)||y||!!g;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:F,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[G&&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:()=>{O()},disabled:!q||y,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:y?"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:[N&&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:N}),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:()=>{Ge()},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:()=>v(E=>!E),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":w,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),w&&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:()=>v(!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:()=>{$.current=!0,M(E=>{const Y=Math.max(Ue,Number((E-.1).toFixed(2)));return Y>Ue&&_e(),Y})},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:()=>{$.current=!0,M(E=>{const Y=Math.min(De,Number((E+.1).toFixed(2)));return Y>Ue&&_e(),Y})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:P,className:W?"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:Ce>0?`${Ce}px`:"100%",height:Te>0?`${Te}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:A},children:s.jsx(mc,{ref:r,readOnly:!m||!c,sizingMode:"measured",onViewportMetrics:D,onScrollMetrics:L,onInput:E=>{!m||(d==null||d(V,q,E))}})})})}),!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:x})]}),s.jsx(jc,{contextKey:e.tabKey,panelLabel:lt(e),isSending:a,isBusy:!!le,statusMessage:ke,onSend:async E=>le?!1:n(E),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const dp=5e3,up=12e3;function mp(e){return e==="disconnected"||e==="reconnecting"}function fp({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=dp,reconnectActionDelayMs:i=up}){const c=mp(e),[l,d]=o.useState(()=>!c||a<=0),[m,u]=o.useState(()=>!c||i<=0),f=o.useRef(!1);o.useEffect(()=>{if(!c){d(!1);return}if(f.current=!1,a<=0){f.current=!0,d(!0);return}d(!1);const j=setTimeout(()=>{f.current=!0,d(!0)},a);return()=>clearTimeout(j)},[a,c]),o.useEffect(()=>{if(!c){u(!1);return}if(i<=0){u(!0);return}u(!1);const j=setTimeout(()=>{u(!0)},i);return()=>clearTimeout(j)},[i,c]);const x=c?l:e==="offline"||e==="auth_failed",C=!!(n&&e!=="auth_failed"&&(!c||m)),y=o.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))"},b={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)"},h={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},k="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:[x&&s.jsx("div",{className:k,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:b[p],color:h[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.")]}),C&&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"})]})}),y&&s.jsx("div",{className:k,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 pp({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=o.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=o.useState(!1);if(o.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!t||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!0)};return s.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[l," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:d,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function 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(Fa,{size:n}):s.jsx(Ut,{size:n})})}const $t="New session",Gc="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 hp(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 xp(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 bp(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 _s({git:e,className:t="",compact:r=!1}){const n=hp(e),a=xp(e);if(!n||!a)return null;const i=[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 ${bp(a)} ${t}`.trim(),title:i.join(" · ")||n,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:n})]})}function gp({wsStatus:e,isConnected:t,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),i=a.filter(l=>l==="connected").length,c=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&c>0&&i===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:t?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function ni({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function ai({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=fn(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(),i()},children:"Delete"})]})]})}function yp({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:f,onShowAllHidden:x,onResetPanelsToMain:C,inboxOpen:y,onInboxOpenChange:p,hiddenOpen:g,onHiddenOpenChange:b,onOpenNewSession:h,onOpenDashboardGuide:k,guideNudgeVisible:S=!1,actionShortcuts:j,notifications:A,notificationUnreadCount:M,onOpenNotification:w,onMarkNotificationRead:v,onMarkNotificationUnread:B,onDeleteNotification:_,onOpenGitDialog:T}){const{ides:D,p2pStates:K={}}=Qt(),L=!!e&&tt(e)&&!Ze(e),N=!!e&&Ze(e),I=l||(e?kc(e)?"terminal":"chat":null),[F,P]=o.useState(!1),$=o.useRef(null),H=o.useRef(null),J=D.filter(ne=>ne.type==="adhdev-daemon"),he=gp({wsStatus:t,isConnected:r,daemonCount:J.length,p2pStates:K}),ie=he.subtitle,te=he.tone==="connected"?"#22c55e":he.tone==="limited"?"#eab308":"#ef4444",be=he.tone==="connected"?"0 0 4px #22c55e80":he.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",we=o.useMemo(()=>A.filter(ne=>!ne.readAt),[A]),ge=o.useMemo(()=>A.filter(ne=>!!ne.readAt),[A]),X=o.useMemo(()=>we.slice(0,9),[we]),ce=M;o.useEffect(()=>{if(!y)return;const ne=de=>{var je;(je=$.current)!=null&&je.contains(de.target)||p(!1)};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[y,p]),o.useEffect(()=>{if(!g)return;const ne=de=>{var je;(je=H.current)!=null&&je.contains(de.target)||b(!1)};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[g,b]),o.useEffect(()=>{if(!g&&!y)return;const ne=de=>{if(!de.altKey)return;const je=de.code.match(/^Digit([1-9])$/);if(!je)return;const me=Number(je[1])-1,pe=g?u[me]:void 0,ee=y?X[me]:void 0;if(!(!pe&&!ee)){if(de.preventDefault(),de.stopPropagation(),pe){f==null||f(pe),b(!1);return}ee&&(w(ee),p(!1))}};return window.addEventListener("keydown",ne,!0),()=>window.removeEventListener("keydown",ne,!0)},[u,g,y,X,b,p,w,f]);const ye=ne=>{if(!ne)return;const de=n.find(je=>je.tabKey===ne);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(Ut,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?lt(e):"Dashboard"}),s.jsx("span",{title:he.title,"aria-label":he.title,className:"header-title-status-dot",style:{background:te,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:te,boxShadow:be}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[ie&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ie]}),h&&s.jsx("button",{type:"button",onClick:h,className:"btn btn-secondary btn-sm ml-2",title:`${$t}${j!=null&&j.openNewSession?` (${j.openNewSession})`:""}`,"aria-label":$t,children:s.jsx(ic,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[k&&s.jsxs("button",{type:"button",onClick:k,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&&(L||N||!Ze(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:ps(e)||lt(e),children:lt(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(_s,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(_s,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(L||N)&&c&&s.jsxs(s.Fragment,{children:[L&&d&&I&&s.jsx(so,{mode:I,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(vt,{size:14})})]}),!Ze(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(Wa,{size:14})}),!L&&!Ze(e)&&s.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Mt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:$,children:[s.jsxs("div",{className:`dashboard-header-hidden${F?" is-drop-target":""}`,ref:H,onDragEnter:ne=>{ne.dataTransfer.types.includes("text/tab-key")&&(ne.preventDefault(),P(!0))},onDragOver:ne=>{ne.dataTransfer.types.includes("text/tab-key")&&(ne.preventDefault(),ne.dataTransfer.dropEffect="move",P(!0))},onDragLeave:ne=>{ne.currentTarget.contains(ne.relatedTarget)||P(!1)},onDrop:ne=>{const de=ne.dataTransfer.getData("text/tab-key");ne.preventDefault(),P(!1),ye(de)},children:[s.jsxs("button",{type:"button",onClick:()=>b(!g),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${j!=null&&j.toggleHiddenTabs?` (${j.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Oa,{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(ni,{value:j==null?void 0:j.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[C&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:C,children:"Reset panels"}),u.length>0&&x&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{x(),b(!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(ni,{value:j==null?void 0:j.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:lt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(ne=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{f==null||f(ne),b(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:lt(ne)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(ne)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(ne)+1]}):null,ps(ne)]})]},ne.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!y),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(mn,{size:16}),ce>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ce})]}),y&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[we.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),we.map(ne=>s.jsx(ai,{notification:ne,shortcutIndex:X.indexOf(ne)>=0?X.indexOf(ne)+1:void 0,onOpen:()=>w(ne),onMarkRead:()=>v(ne.id),onMarkUnread:()=>B(ne.id),onDelete:()=>_(ne.id)},ne.id))]}),ge.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),ge.map(ne=>s.jsx(ai,{notification:ne,onOpen:()=>w(ne),onMarkRead:()=>v(ne.id),onMarkUnread:()=>B(ne.id),onDelete:()=>_(ne.id)},ne.id))]}),A.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function wt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function vp(e,t){return String(e||"")!==String(t||"")}function wp(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),i=!!t.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(d=>String(d||"").toLowerCase()).join(`
39
+ `).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!bc(c.summaryMetadata).map(d=>d.toLowerCase()).join(`
40
+ `).includes(a)))}function jp(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const i=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function qc(e,t={}){return jp(wp(e,t),t.sortMode||"recent")}function nn(e){return e?"Resume saved history":"Start fresh"}function ro(e){return e?"Resuming saved history…":"Starting fresh…"}function kp(){return"Start fresh"}function Yc(e,t=!1){return e==="cli"?nn(t):e==="ide"?"Start IDE":"Start ACP session"}function Xc(e,t=!1){return e==="cli"?ro(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Sp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Np(){return"Open saved history"}function Cp(){return"Saved History"}function no(){return"Use saved history when you want continuity in the same provider conversation."}function Tp(){return"No saved history found yet."}function Mp(){return"Refresh saved history"}function Ap(){return"Refreshing saved history…"}function as(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function os(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 Ps(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ds(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function ao(e){return`Resume saved history with ${e}?`}function oo(){return"Review or change the target workspace before resuming saved history."}function Ip(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 io({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:f,onSwitchSession:x,onRefreshHistory:C,onResumeSavedSession:y}){var _;const p=t.find(T=>T.id===e.routeId),g=(p==null?void 0:p.chats)||[],b=(_=p==null?void 0:p.activeChat)==null?void 0:_.id,h=tt(e)&&!Ze(e),[k,S]=o.useState(()=>wt()),j=l||k,A=String(d||"").trim(),M=T=>{if(m){m(T);return}S(T)},w=o.useMemo(()=>a.map(T=>{const D=String(T.workspace||"").trim();return T.canResume||D||!A?T:{...T,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,a]),v=o.useMemo(()=>qc(w,{textQuery:j.textQuery,workspaceQuery:j.workspaceQuery,modelQuery:j.modelQuery,resumableOnly:j.resumableOnly,sortMode:j.sortMode}),[w,j.modelQuery,j.resumableOnly,j.sortMode,j.textQuery,j.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:h?Cp():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:ip(e)}),h&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:no()})]}),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(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!h&&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"}),h?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:j.textQuery,onChange:T=>M({...j,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:j.workspaceQuery,onChange:T=>M({...j,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:j.modelQuery,onChange:T=>M({...j,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:j.sortMode,onChange:T=>M({...j,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:j.resumableOnly,onChange:T=>M({...j,resumableOnly:T.target.checked})}),"Resume-ready only"]})]}),v.map(T=>{const D=e.providerSessionId===T.providerSessionId,K=D||!T.canResume||!!c,L=T.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{K||!y||y(T)},disabled:K,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${D?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${K?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${D?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children: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:Ip(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",L?" · selected workspace":"",fs(T.summaryMetadata)?` · ${fs(T.summaryMetadata)}`:"",T.messageCount>0?` · ${T.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:D?"ACTIVE":T.canResume?L?"RESUME IN SELECTED WORKSPACE":c===T.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},T.id)})]}):g.map(T=>s.jsxs("div",{onClick:()=>{x(e.routeId,T.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===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 ${b===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),"..."]}),b===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)),(h&&!i&&v.length===0||!h&&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(hu,{size:32})}),s.jsx("div",{className:"text-[13px]",children:h?a.length>0?"No saved history matches these filters.":Tp():"No recent chat sessions found."})]}),h&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Ap()})})]}),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:C,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(dr,{size:13})," ",h?Mp():"Refresh History"]})})})]})]});return typeof document>"u"?B:ar.createPortal(B,document.body)}const oi={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 Jc({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=oi[n.type]||oi.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=n.actions)!=null&&i.length||r&&r(n)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(vt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:l=>{l.stopPropagation(),i.onClick(),t(n.id)},children:i.label},c))})]})]},n.id)})})}const Rp=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Lp(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function _p(e){return e.sessionId||e.instanceId||e.agentType}function Pn(e,t){return e||t}function Qc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Tt(r,{fallbackId:r.id}));return t}function Zc(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 co(e,t={}){return Pp(e,Zc(e,t))}function Pp(e,t={}){var f,x,C,y,p;const r=[],n=t.machineName,a=t.connectionState,i=Lp(e),c=e.workspace||"",l=lm(e.type,{agentName:e.cliName}),d=tt(e)||Ze(e)?l:it(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(g=>{var b,h;return{sessionId:g.id,instanceId:g.id,providerSessionId:g.providerSessionId,transport:g.transport,sessionCapabilities:g.capabilities,agentType:g.providerType,agentName:g.providerName||it(g.providerType),status:g.status,title:g.title,lastMessagePreview:g.lastMessagePreview,lastMessageRole:g.lastMessageRole,lastMessageAt:g.lastMessageAt,lastMessageHash:g.lastMessageHash,messages:((b=g.activeChat)==null?void 0:b.messages)||[],activeModal:((h=g.activeChat)==null?void 0:h.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}}):[],u=Rp(e);if(u){const g=e.sessionId||e.instanceId,b=(f=e.settings)==null?void 0:f.meshCoordinatorFor,h=(x=e.settings)==null?void 0:x.meshNodeFor,k=b?" (Coordinator)":h?" (Mesh Node)":"",S=l+k,j=(C=e.activeChat)==null?void 0:C.activeModal,A=j&&Array.isArray(j.buttons)&&j.buttons.length>0,M=dm(e.activeChat,[{status:e.status,activeModal:(y=e.activeChat)==null?void 0:y.activeModal}],e.agents||[]),w=e.activeChat||{title:"",messages:[]};let v=w.title&&String(w.title).trim()?String(w.title).trim():"";const B=(p=e.activeChat)==null?void 0:p.id,_=e.chats;if(B&&Array.isArray(_)&&_.length>0){const L=_.find(N=>N.id===B||N.id&&String(N.id)===String(B));L!=null&&L.title&&String(L.title).trim()&&(v=String(L.title).trim())}const T=(tt(e)||Ze(e),e.type),D=(tt(e)||Ze(e))&&zo(v,S,T)?"":v,K=w.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:tt(e)?e.mode||"terminal":"chat",agentName:S,agentType:T,status:M,title:D,messages:K,resume:e.resume,hostIdeType:!tt(e)&&!Ze(e)?e.type:void 0,workspaceName:i,workspacePath:c,git:e.git,displayPrimary:D||i||(tt(e)?e.mode==="chat"?S:`Terminal${k}`:S),displaySecondary:tt(e)&&i?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:A?j.buttons:void 0,modalMessage:A?j.message:void 0,streamSource:"native",tabKey:Pn(g,e.id),machineName:n,connectionState:a,settings:e.settings})}if(u&&(tt(e)||Ze(e)))return r;for(const g of m){const b=g.activeModal&&Array.isArray(g.activeModal.buttons)&&g.activeModal.buttons.length>0,h=um(g),k=_p(g),S=`${e.id}:${k}`,j=g.title&&String(g.title).trim()||"",A=zo(j,g.agentName,g.agentType)?"":j,M=g.messages||[];(g.transport==="cdp-webview"||g.sessionId||g.providerSessionId||M.length>0||b||A||!["idle","panel_hidden","disconnected","not_monitored"].includes(h))&&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:h,title:A,messages:M,hostIdeType:e.type,workspaceName:i,workspacePath:c,git:g.git||e.git,displayPrimary:A||i||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:b?g.activeModal.buttons:void 0,modalMessage:b?g.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Pn(g.sessionId||g.instanceId,S),machineName:n,connectionState:a,settings:g.settings})}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:i,workspacePath:c,git:e.git,displayPrimary:i||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Pn(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings}),r}function Dp(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 el(e,t){const r=Dp(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const tl=[{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:"🏄"}],sl=[{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:"🧩"}],rl=[{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:"🟠"}],Ep=tl,$p=sl,Bp=rl;function zt(...e){return Md(Ad(e))}function Kp({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:zt("dashboard-header",i),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function tr({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Kp,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:zt("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const Na="adhdev:themechange";function Wp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function vs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function ws(e){return e==="system"?Wp():e}function nl(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Or(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Na,{detail:{preference:e,theme:t}}))}function Op(){const e=vs(),t=ws(e);nl(t),Or(e,t)}function lo(){const[e,t]=o.useState(vs),[r,n]=o.useState(()=>ws(vs()));o.useEffect(()=>{nl(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),Or("system",m)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=d=>{const m=d.detail||{},u=m.preference,f=m.theme;t(u==="dark"||u==="light"||u==="system"?u:vs()),n(f==="dark"||f==="light"?f:ws(vs()))},l=d=>{if(d.key!=="theme")return;const m=vs(),u=ws(m);t(m),n(u)};return window.addEventListener(Na,c),window.addEventListener("storage",l),()=>{window.removeEventListener(Na,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=ws(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Or(c,l)},[]),i=o.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=ws(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Or(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const ii={dark:"Dark",light:"Light",system:"System"};function Fp({collapsed:e}){const{preference:t,cycleTheme:r}=lo(),n=t==="dark"?s.jsx(bu,{size:16}):t==="light"?s.jsx(xu,{size:16}):s.jsx(gu,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ii[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:ii[t]})]})}function Dn(e,t){return e?typeof e=="function"?e(t):e:null}function Hp({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=o.useState(!1),[f,x]=o.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),C=()=>u(!0),y=()=>u(!1),p=()=>{x(k=>{const S=!k;try{localStorage.setItem(d,S?"1":"0")}catch{}return S})},g=o.useMemo(()=>({collapsed:f,mobileMenuOpen:m,openMobileMenu:C,closeMobileMenu:y,toggleCollapsed:p}),[f,m]),b=k=>`nav-item${k.active?" active":""} cursor-pointer ${f?"justify-center py-2.5 px-0":""}${k.className?` ${k.className}`:""}`,h=k=>s.jsxs("div",{className:b(k),id:`nav-${k.id}`,onClick:()=>{k.onSelect(),y()},title:f?k.title??(typeof k.label=="string"?k.label:void 0):k.title,children:[s.jsx("span",{className:"nav-icon",children:k.icon}),!f&&k.label]},k.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:C,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:y,onKeyDown:k=>k.key==="Escape"&&y()}),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:Dn(t,g)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:y,children:s.jsx(vt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(h)}),n.map(k=>s.jsxs("div",{className:k.className??"border-t border-border-subtle pt-2 mt-2",children:[!f&&k.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:k.title}):null,k.items.map(h)]},k.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(h),Dn(i,g),s.jsx(Fp,{collapsed:f}),Dn(c,g)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function kt({title:e,icon:t,description:r,accentColor:n,className:a,children:i}){return s.jsxs("div",{className:zt("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function an({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:zt("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 Up={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"},zp={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ss({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:zt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Up[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:zp[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 En({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:zt("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 $n(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:zt("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 Vp={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"},Gp={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function qp({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:zt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Vp[e],r),children:[s.jsx("span",{className:zt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Gp[e])}),n]})}function ts({label:e,description:t,checked:r,disabled:n,onChange:a,extra:i}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,s.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Yp({onPrefChange:e}){const[t,r]=wm(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(mn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>i("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Mt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>i("browserNotifications",c)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{vc().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(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(yu,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(vu,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Is,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function on(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Xp(e,t){const r=on(e),n=on(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 al(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function sr(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Xp(r,t)>=0)return!1;const n=on(r),a=on(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Jp(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Bn(e,t){return e instanceof Error?e.message:t}function Qp({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(an,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:t||"Install ADHDev on a machine and sign in to connect it here."}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>s.jsx(eh,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function ci({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return ar.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:i,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function Zp(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Ep,...$p,...Bp].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 eh({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var K,L;const[i,c]=o.useState("idle"),[l,d]=o.useState(""),[m,u]=o.useState(null),[f,x]=o.useState("idle"),[C,y]=o.useState(""),p=e.version||null,g=((K=e.machine)==null?void 0:K.platform)||((L=e.system)==null?void 0:L.platform)||"",b=Tt(e,{fallbackId:e.id}),h=g==="win32"?"🪟":g==="darwin"?"🍎":"🐧",k=t.filter(N=>N.daemonId===e.id&&N.transport==="cdp-page"),S=t.filter(N=>N.daemonId===e.id&&N.transport==="pty"),j=t.filter(N=>N.daemonId===e.id&&N.transport==="acp"),A=e.p2p,M=async()=>{if(r){c("upgrading"),d("Starting upgrade...");try{const N=Jp(await r(e.id,"daemon_upgrade",{}));N.alreadyLatest?(c("done"),d(`Already on v${N.version||"latest"}.`)):N.upgraded||N.success?(c("done"),d(`Upgrade to v${N.version||"latest"} started. Daemon is restarting...`)):(c("error"),d(N.error||"Upgrade failed"))}catch(N){c("error"),d(Bn(N,"Connection lost during upgrade"))}}},w=async()=>{if(u(null),!!n){x("loading");try{await n(e.id),x("done"),y("Machine disconnected.")}catch(N){x("error"),y(Bn(N,"Failed to disconnect"))}}},v=async()=>{if(u(null),!!a){x("loading");try{await a(e.id),x("done"),y("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(N){x("error"),y(Bn(N,"Failed to revoke token"))}}},B="0.9.75",_=al(e,B),T=sr(e,B),D=k.length+S.length+j.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:h}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:b}),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:M,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${B}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${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(qp,{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:[A&&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 ${A.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${A.state==="connecting"||A.state==="new"?"animate-pulse":""}`,style:A.state==="connecting"||A.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",A.state==="connected"?"connected":A.state==="connecting"||A.state==="new"?"connecting...":A.state||"off"]}),A.peers!==void 0&&A.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",A.peers," peer",A.peers!==1?"s":"",")"]})]}),A&&D>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),D>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[k.map(N=>{const I=Zp(N.type),F=N.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:I.icon}),s.jsx("span",{children:I.name}),F!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${F?"bg-green-400":"animate-pulse"}`,style:F?void 0:{background:"var(--status-warning)"},title:F?"CDP connected":"CDP connecting..."})]},N.id)}),S.map(N=>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:N.cliName||"CLI"})]},N.id)),j.map(N=>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:N.cliName||"ACP"})]},N.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||C)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-red-400":i==="done"||f==="done"?"text-green-400":"text-text-muted"}`,children:C||l})]}),m==="disconnect"&&s.jsx(ci,{title:"🔌 Disconnect Machine",message:`Disconnect "${b}" from ADHDev?
41
41
 
42
42
  This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
43
43
 
44
- Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:w,onCancel:()=>u(null)}),m==="revoke"&&s.jsx(oi,{title:"⚠️ Remove Machine",message:`Remove "${b}" from your dashboard?
44
+ Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:w,onCancel:()=>u(null)}),m==="revoke"&&s.jsx(ci,{title:"⚠️ Remove Machine",message:`Remove "${b}" from your dashboard?
45
45
 
46
46
  This will:
47
47
  • Immediately disconnect the machine
48
48
  • Delete the machine registration
49
49
  • Require restarting ADHDev on that machine
50
50
 
51
- Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:v,onCancel:()=>u(null)})]})}const Zp=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function eh(){const{preference:e,setPreference:t}=co();return s.jsx("div",{className:"flex gap-2",children:Zp.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 th(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 sh(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Bn(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function ii(e){const{r:t,g:r,b:n}=sh(e);return .2126*Bn(t)+.7152*Bn(r)+.0722*Bn(n)}function ci(e,t){const r=ii(e),n=ii(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function al(e){const t=th(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return ci(t,r)>=ci(t,n)?r:n}const Na={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},Ca={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},rh=[{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"}}}],ol="adhdev-chat-theme",il="adhdev-chat-theme-custom";function Fr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(ol)||"ember"}catch{return"ember"}}function Pt(e){try{const t=localStorage.getItem(il);if(t){const r=JSON.parse(t);return{...e==="dark"?Na:Ca,...r[e]}}}catch{}return e==="dark"?Na:Ca}function Ar(e,t){try{localStorage.setItem(il,JSON.stringify({dark:e,light:t}))}catch{}}function At(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 on(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 nh={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function rr(e,t){var a;const r=(a=nh[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",on(r,24)),n.style.setProperty("--accent-on-primary",al(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${on(r,18)})`),n.style.setProperty("--border-accent",At(r,.35)),n.style.setProperty("--nav-active-bg",At(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${At(r,.06)}`)}function is(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",At(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",At(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",At(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",At(e.borderSubtle,.5)),t.style.setProperty("--border-default",At(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",on(e.accentColor,30)),t.style.setProperty("--accent-on-primary",al(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${on(e.accentColor,40)})`),t.style.setProperty("--border-accent",At(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",At(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${At(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 ${At(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 lo(){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 ah(e){try{localStorage.setItem(ol,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=cs()?"dark":"light";is(Pt(t))}else lo(),rr(e,cs()?"dark":"light")}function oh(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Fr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=cs()?"dark":"light";is(Pt(t))}else lo(),rr(e,cs()?"dark":"light")}function cs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function wt({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 zs({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 ih({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=o.useState(()=>Pt(r));o.useEffect(()=>{a(Pt(r))},[r]);const i=o.useCallback((c,l)=>{a(d=>{const m={...d,[c]:l},f=Pt(r==="dark"?"light":"dark");return r==="dark"?Ar(m,f):Ar(f,m),is(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(zs,{title:"App Background",children:[s.jsx(wt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(wt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(wt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(zs,{title:"App Text",children:[s.jsx(wt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(wt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(wt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(zs,{title:"Borders & Accent",children:[s.jsx(wt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(wt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(wt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(zs,{title:"Chat Bubbles",children:[s.jsx(wt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(wt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(wt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(wt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(zs,{title:"Chat Layout",children:[s.jsx(wt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(wt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(wt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?Na:Ca,d=Pt(e?"light":"dark");e?Ar(c,d):Ar(d,c),a(c),is(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 ch(){const[e,t]=o.useState(Fr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Pt("dark"));o.useEffect(()=>{n(cs());const d=new MutationObserver(()=>{const f=cs();n(f);const x=Fr();x==="custom"?is(Pt(f?"dark":"light")):rr(x,f?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const f=cs();n(f);const x=Fr();x==="custom"?is(Pt(f?"dark":"light")):rr(x,f?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?is(Pt(r?"dark":"light")):(lo(),rr(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Pt(r?"dark":"light"))},[r]);const c=d=>{t(d),ah(d)},l=[...rh,{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(ih,{dark:r,onColorsChange:d=>i(d)})]})}const uo="adhdev_mobileDashboardMode_v1",Ta="adhdev:mobile-dashboard-mode-change";function mo(){try{return localStorage.getItem(uo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function lh(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??mo())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==uo||t()};return window.addEventListener(Ta,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Ta,r),window.removeEventListener("storage",n)}}function dh(e){try{localStorage.setItem(uo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ta,{detail:e}))}function uh(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(mo()==="chat")},[]),s.jsx(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ut,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{t(r),dh(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Kn=new Map,li=new Map;function mh(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 fh(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 cl(){const{sendCommand:e}=bt(),{injectEntries:t,getIdes:r}=or();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??pf,c=li.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=Kn.get(n);if(l)return l;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=mh(m);if(!u)return;const f=r().find(C=>C.id===n),x=fh(f,n,u.machine,u.timestamp||Date.now());t([x]),li.set(n,Date.now())})().finally(()=>{Kn.delete(n)});return Kn.set(n,d),d},[r,t,e])}function ph(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 hh(e,t){const{sendData:r}=bt(),{injectEntries:n,getIdes:a}=or(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(d=>Ht.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(C=>C.id===d),x=ph(f,d,u);n([x])}));return()=>{l.forEach(d=>d())}},[i,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function xh(e,t){const{sendData:r}=bt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(t!=null&&t.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const d=Ht.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)},gf):c(!1),()=>{l&&clearTimeout(l),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:a}}function bh(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function ll(e){const{sendData:t}=bt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=bh(e);if(!a||!e.sessionId||!t){n({});return}const i=Ht.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}),Ms.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return i.initialSendAccepted||n({}),()=>{i()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const dl="adhdev_hiddenTabs";function gh(){try{const e=localStorage.getItem(dl);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function gs(e){try{localStorage.setItem(dl,JSON.stringify([...e]))}catch{}}function Wn(e){return Za(e)}function fo(e,t){return Ts(t).some(r=>e.has(r))}function yh(){const[e,t]=o.useState(gh),r=o.useCallback(m=>{const u=Wn(m);t(f=>{const x=new Set(f);return x.has(u)?x.delete(u):x.add(u),gs(x),x})},[]),n=o.useCallback(m=>{const u=Wn(m);t(f=>{if(f.has(u))return f;const x=new Set(f);return x.add(u),gs(x),x})},[]),a=o.useCallback(m=>{const u=Wn(m);t(f=>{if(!f.has(u))return f;const x=new Set(f);return x.delete(u),gs(x),x})},[]),i=o.useCallback(()=>{t(m=>{if(m.size===0)return m;const u=new Set;return gs(u),u})},[]),c=o.useCallback((m,u)=>{t(f=>{const x=new Set(f);for(const C of u)x.add(C);return gs(x),x})},[]),l=o.useCallback((m,u)=>{t(f=>{const x=new Set(f);for(const C of u)x.delete(C);return gs(x),x})},[]),d=o.useCallback(m=>fo(e,m),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:d}}function ul(e){return e instanceof Error?e.message:String(e||"")}function ml(e){const t=ul(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 fl(e){const t=ul(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function pl({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!tt(e)||Ze(e))return;const i=Ks(e);if(i===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(bs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Kt(e),mode:t})}catch(l){const d=fl(l);c&&!d&&a(m=>{const u={...m};return i===hl(r,c)?delete u[c]:u[c]=i,u}),ml(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 di(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 vh(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let r=!1;const n=e.map(a=>{const i=di(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>di(d,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function hl(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 wh(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))hl(t,a)===i&&(delete n[a],r=!0);return r?n:e}function jh({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{yc()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Uc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return km(a),o.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]),o.useEffect(()=>{const i=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(i)},[n]),null}function ui(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 ls(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=ui(t==null?void 0:t.receivedAt)||ui(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function Ma(e,t=0){return ls(e)||e.lastUpdated||t||0}function xl(e){return ls(e)||e.lastUpdated||0}function bl(e,t,r=xl){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(t.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(t.displaySecondary);return c!==0?c:e.tabKey.localeCompare(t.tabKey)}function Aa(e){var r;const t=jt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function kh(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Aa(e)&&!e.title.trim()}function Sh(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(Aa(r))-Number(Aa(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:bl(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"),i=Sh(a);return n?i&&kh(n)?i:n:i||r[0]||null}function Nh(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const i=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function On(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 Ch(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 mi(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Ch(As(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 Th(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||""),mi(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||""),mi(r.activeChat)].join(":"))].join("|")}function Mh(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 Ah(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const i of Ts({routeId:n.routeId}))r.set(i,a);for(const i of Ts({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of Ts({tabKey:n.tabKey}))r.set(i,n)}return r}function Ih(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Rh(e){const t=Ih(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=As(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Lh({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>Nh(e),[e]),i=o.useMemo(()=>Jc(e),[e]),c=o.useRef([]),l=o.useRef([]),d=o.useRef([]),m=o.useRef(new Map),u=o.useRef(new Map),f=o.useMemo(()=>{const S=new Map,k=[];for(const v of a){const{connectionState:B="new",machineName:_}=Qc(v,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),T=Th(v),D=m.current.get(v.id);if(D&&D.ide===v&&D.sourceSignature===T&&D.connectionState===B&&D.machineName===_){S.set(v.id,D),k.push(...D.conversations);continue}const K=io(v,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),L={ide:v,sourceSignature:T,connectionState:B,machineName:_,conversations:K};S.set(v.id,L),k.push(...K)}m.current=S;const A=new Map,M=v=>{const B=Rh(v),_=u.current.get(v.tabKey);if(_&&_.signature===B)return A.set(v.tabKey,_),_.timestamp;const T={signature:B,timestamp:xl(v)||(_==null?void 0:_.timestamp)||0};return A.set(v.tabKey,T),T.timestamp},w=[...k].sort((v,B)=>bl(v,B,M));return u.current=A,w},[a,t,i]),x=o.useMemo(()=>{const S=Mh(f,r);return On(c.current,S)?c.current:(c.current=S,S)},[f,r]),C=o.useMemo(()=>{const S=new Map,k=Array.from(new Set(x.map(A=>A.routeId)));for(const A of k){const M=Dt(x,A);M&&S.set(A,M)}return S},[x]),g=o.useMemo(()=>{const S=new Map;for(const k of x){const A=C.get(k.routeId),M=k.streamSource==="native"&&A?A:k;for(const w of Ts({providerSessionId:k.providerSessionId,sessionId:k.sessionId}))S.set(w,M)}return S},[x,C]),p=o.useMemo(()=>Ah(x,C),[x,C]),j=o.useCallback(S=>{if(S)return g.get(S)},[g]),b=o.useCallback(S=>{if(S)return p.get(S)},[p]),h=o.useMemo(()=>{const S=x.filter(k=>!fo(n,k));return On(l.current,S)?l.current:(l.current=S,S)},[x,n]),y=o.useMemo(()=>{const S=h.map(k=>k.tabKey);return On(d.current,S)?d.current:(d.current=S,S)},[h]);return{chatIdes:a,conversations:x,visibleConversations:h,visibleTabKeys:y,resolveConversationBySessionId:j,resolveConversationByTarget:b}}function _h({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),i=o.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=o.useCallback(()=>{t&&n(l=>{const d=new URLSearchParams(l);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Ph({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{at.setIdes(e)},[e]),o.useEffect(()=>{at.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),o.useEffect(()=>{const a=at.onToast(i=>{r(l=>l.some(m=>m.message===i.message&&i.timestamp-m.timestamp<3e3)?l:[...l.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions}]);const c=i.duration||5e3;setTimeout(()=>r(l=>l.filter(d=>d.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=Oc.on("status_event",i=>{at.handleRawEvent(i,"ws")});return()=>{a()}},[]),o.useEffect(()=>{var i;const a=c=>{var p;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const d=l.targetSessionId||l.targetKey||l.daemonId,m=n(d),u=(m==null?void 0:m.routeId)||l.daemonId;if(!u)return;const f=Number(l.buttonIndex),x=l.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[f])||"Approve",C=String(x).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),g=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(C);t(u,"resolve_action",{action:g?"approve":"reject",button:x,...Number.isFinite(f)&&{buttonIndex:f},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(j=>console.error("[SW Action] approval failed:",j))};return(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,t])}const Dh="adhdev_dashboardLayout_v1",Eh="adhdev_dashboardDockview_v1",$h="adhdev_dashboardDockviewHiddenRestore_v1",Vs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function po(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Bh(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function gl(e){return`${Dh}:${e}`}function Kh(e){const t=gl(e);return po(t,null)}function Wh(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=gl(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function yl(e){return`${Eh}:${e}`}function Oh(e){const t=yl(e);return po(t,null)}function Fh(e,t){try{const r=yl(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function vl(e){return`${$h}:${e}`}function Hh(e){const t=vl(e);return po(t,{})}function Uh(e,t){try{const r=vl(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function zh(){return{groupAssignments:[...Vs.groupAssignments],focusedGroup:Vs.focusedGroup,groupActiveTabIds:{...Vs.groupActiveTabIds},groupTabOrders:{...Vs.groupTabOrders},groupSizes:[...Vs.groupSizes]}}function Vh(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Gh(){const[e]=o.useState(()=>Bh(typeof window<"u"?window.innerWidth:1280)),[t,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,d]=o.useState({}),[m,u]=o.useState([]),[f,x]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[C,g]=o.useState(!1),p=o.useCallback(()=>{if(C)return;const v=Kh(e)??zh();r(new Map(v.groupAssignments)),a(v.focusedGroup),c(v.groupActiveTabIds),d(v.groupTabOrders),u(v.groupSizes),g(!0)},[C,e]);o.useEffect(()=>{C&&Wh(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:m})},[C,e,t,n,i,l,m]),o.useEffect(()=>{const v=window.matchMedia("(max-width: 767px)"),B=_=>x(_.matches);return v.addEventListener("change",B),()=>v.removeEventListener("change",B)},[]);const j=o.useCallback(v=>{r(v)},[]),b=o.useCallback(v=>{a(v)},[]),h=o.useCallback(v=>{c(v)},[]),y=o.useCallback(v=>{d(v)},[]),S=o.useCallback(v=>{u(v)},[]),k=o.useCallback(v=>{b(v)},[b]),A=o.useCallback((v,B)=>{c(_=>(_[v]??null)===(B??null)?_:{..._,[v]:B})},[]),M=o.useCallback((v,B)=>{d(_=>{const T=_[v];return Vh(T,B)?_:{..._,[v]:B}})},[]),w=o.useCallback((v,B)=>{const _=B.get(v)??0;return A(_,v),k(_),_},[k,A]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:j,focusedGroup:n,updateFocusedGroup:b,focusGroup:k,groupActiveTabIds:i,updateGroupActiveTabIds:h,setGroupActiveTab:A,groupTabOrders:l,updateGroupTabOrders:y,setGroupTabOrder:M,groupSizes:m,updateGroupSizes:S,isMobile:f,hasHydratedStoredLayout:C,hydrateStoredLayout:p,focusConversationTab:w}}function qh(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Qa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Yh({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:f,handleRefreshHistory:x}){const C=o.useRef(!1),g=o.useRef(!1),p=o.useRef(null),j=o.useRef(!1);o.useEffect(()=>{if(!e||C.current||t.length===0)return;if(!a){i();return}const b=r(e);b&&(c(b.tabKey,n),C.current=!0,g.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(h=>{const y=new URLSearchParams(h);return y.delete("activeTab"),y},{replace:!0}))},[e,t,r,n,a,i,c,l]),o.useEffect(()=>{if(!(g.current||a)&&t.length!==0){if(!e){i(),g.current=!0;return}if(C.current){g.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(g.current||a)&&(i(),g.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,i]),o.useEffect(()=>{if(!d){j.current=!1;return}if(!m||j.current||u)return;const b=f.find(h=>h.id===m.routeId);b&&(!b.chats||b.chats.length===0||qh(b.chats,m))&&(j.current=!0,x())},[d,m,u,f,x])}function Fn(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=Qa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function wl({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[d,m]=o.useState(!1),u=o.useCallback(async g=>{try{await e("standalone","launch_ide",{ideType:g,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),f=o.useCallback(async(g,p)=>{try{const j=g||(t==null?void 0:t.daemonId)||"",b=await e(j,"switch_chat",{id:p,sessionId:p,...rs(t)}),h=b==null?void 0:b.result;if((b==null?void 0:b.success)===!0||h==="switched"||h==="switched-by-title")return;h===!1||h==="not_found"?Hs(a,"⚠️ Session tab not found — try refreshing history"):typeof h=="string"&&h.startsWith("error:")?Hs(a,`⚠️ Switch error: ${h}`):Hs(a,"⚠️ Session switch failed")}catch(j){console.error("Switch failed",j),Hs(a,`❌ Switch failed: ${j.message||"connection error"}`)}},[t,e,a]),x=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const g=Ls(t);await e(g,"new_chat",{...rs(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(g){console.error("New chat failed",g)}finally{l(!1)}}},[t,c,e,i]),C=o.useCallback(async()=>{var g,p;if(!(!t||d)){m(!0);try{const j=Ls(t),b=async()=>e(j,"list_chats",{forceExpand:!0,...rs(t)});let h=await b(),y=(h==null?void 0:h.chats)||((g=h==null?void 0:h.result)==null?void 0:g.chats);Fn(y,t)&&(await new Promise(S=>setTimeout(S,450)),h=await b(),y=(h==null?void 0:h.chats)||((p=h==null?void 0:h.result)==null?void 0:p.chats)),h!=null&&h.success&&Array.isArray(y)&&(n(t.routeId,y),Fn(y,t)&&!Fn(r,t)&&Hs(a,"⚠️ History dialog did not fully open — try once more"))}catch(j){console.error("Refresh history failed",j)}finally{m(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:f,handleNewChat:x,handleRefreshHistory:C}}function Xh(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 Jh(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function fi(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 Ir(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const d=a[l];typeof d=="number"&&d>0&&i.set(c,d)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function pi(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=t[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function Qh(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 Zh(e,t,r){if(t.length<=1)return[];const n=t.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===t.length?n:Array(r).fill(100/r),i=a.reduce((c,l)=>c+l,0);return i>0?a.map(c=>c/i*100):Array(r).fill(100/r)}function hi(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=t?i+1:i]=a}return r}function xi(e){return Array(e).fill(100/e)}function ex({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:d,visibleTabKeys:m}){const u=o.useRef(null),f=o.useMemo(()=>Ir(e,m),[e,m]),x=f.assignments,C=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),g=C>1,p=o.useCallback((k,A)=>{t(M=>{const w=new Map(Ir(M,m).assignments);return A===0?w.delete(k):w.set(k,A),w}),n(M=>({...M,[A]:k})),r(A)},[t,m,n,r]),j=o.useCallback(k=>{t(A=>{const M=Ir(A,m).assignments,w=new Map;for(const[v,B]of M)B!==k&&(B>k?w.set(v,B-1):w.set(v,B));return w}),c(A=>{if(A.length<=1)return[];const M=[...A];M.splice(k,1);const w=M.reduce((v,B)=>v+B,0);return w>0?M.map(v=>v/w*100):[]}),r(0)},[t,m,c,r]),b=o.useCallback((k,A)=>{A.preventDefault();const M=u.current;if(!M)return;const w=A.clientX,v=M.offsetWidth,B=i.length===C?[...i]:xi(C),_=D=>{const L=(D.clientX-w)/v*100,N=[...B];N[k]=Math.max(15,B[k]+L),N[k+1]=Math.max(15,B[k+1]-L),c(N)},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)},[i,C,c]),h=o.useCallback((k,A,M)=>{if(C>=4)return;const w=M==="left"?A:A+1;t(v=>{const B=Ir(v,m).assignments,_=new Map;for(const T of d){const D=B.get(T.tabKey)??0,K=D>=w?D+1:D;K>0&&_.set(T.tabKey,K)}return w>0&&_.set(k,w),_}),c(v=>{const B=v.length===C?[...v]:xi(C),_=B[A]??100/C,T=Math.max(15,_/2),D=Math.max(15,_/2),K=[...B];K[A]=T,K.splice(w,0,D);const L=K.reduce((N,I)=>N+I,0);return K.map(N=>N/L*100)}),n(v=>{const B=hi(v,w);return B[w]=k,B}),a(v=>{const B=hi(v,w);return B[w]=[k],B}),r(w)},[C,t,m,d,c,n,a,r]);o.useEffect(()=>{Xh(e,x)||t(x)},[e,x,t]),o.useEffect(()=>{const{mapping:k,usedGroups:A}=f;n(M=>{const w=pi(M,k);return fi(M,w)?M:w}),a(M=>{const w=pi(M,k);return fi(M,w)?M:w}),r(M=>{const w=l?0:Qh(M,A,k);return M===w?M:w}),c(M=>{const w=l?[]:Zh(M,A,f.groupCount);return Jh(M,w)?M:w})},[f,l,n,a,r,c]);const y=o.useMemo(()=>{const k=Array.from({length:C},()=>[]);for(const A of d){const M=x.get(A.tabKey)??0,w=Math.min(M,C-1);k[w].push(A)}return k},[d,x,C]),S=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:x,numGroups:C,isSplitMode:g,groupedConvs:y,moveTabToGroup:p,closeGroup:j,handleResizeStart:b,splitTabRelative:h,clearAllSplits:S}}function Hn(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 tx(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 Rr(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function ho(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=Hn(t.channel)||Hn(e.updateChannel)||Hn(e.releaseChannel)||void 0,n=tx(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=Rr(t.targetVersion)||Rr(e.serverVersion)||void 0,i=Rr(t.minVersion)||void 0,c=Rr(t.updateCommand)||(r?`adhdev update --channel ${r}`:void 0);return{...r?{channel:r}:{},...n?{npmTag:n}:{},...a?{targetVersion:a}:{},...i?{minVersion:i}:{},...c?{updateCommand:c}:{}}}function js(e,t=null){return ho(e).targetVersion||t}function jl(e){return ho(e).channel||null}function kl(e){const t=ho(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 sx({ides:e,sendDaemonCommand:t}){const r="0.9.75",n=o.useMemo(()=>e.filter(f=>f.type!=="adhdev-daemon"?!1:nl(f,js(f,r))).sort((f,x)=>Number(sr(x,js(x,r)))-Number(sr(f,js(f,r)))),[r,e]),a=o.useMemo(()=>n.some(f=>sr(f,js(f,r))),[r,n]),i=o.useMemo(()=>n.map(f=>js(f,r)).find(f=>typeof f=="string"&&f.trim().length>0)||r,[r,n]),[c,l]=o.useState(!1),[d,m]=o.useState({}),u=o.useCallback(async f=>{var C,g;const x=e.find(p=>p.id===f);if(x){m(p=>({...p,[f]:"upgrading"}));try{const p=await t(f,"daemon_upgrade",kl(x));(C=p==null?void 0:p.result)!=null&&C.upgraded||(g=p==null?void 0:p.result)!=null&&g.success?m(j=>({...j,[f]:"done"})):m(j=>({...j,[f]:"error"}))}catch{m(p=>({...p,[f]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:i,versionBannerDismissed:c,setVersionBannerDismissed:l,upgradingDaemons:d,handleBannerUpgrade:u}}const Sl=80;function Hr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function rx(e){return{...e,createdAt:Hr(e.createdAt),updatedAt:Hr(e.updatedAt,e.createdAt),lastEventAt:Hr(e.lastEventAt,e.updatedAt||e.createdAt)}}function nx(e){const t=Za(e);return t==="unknown:"?e.id:t}function ax(e){return[e.type,Pc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function ox(e,t=Sl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=nx(n),i=r.get(a);if(!i){r.set(a,n);continue}(n.updatedAt>i.updatedAt||n.updatedAt===i.updatedAt&&n.createdAt>i.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const i=a.updatedAt-n.updatedAt;return i!==0?i:a.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function ix(e,t){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?t.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=fn(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const d=Hr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),m=ax({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(i==null?void 0:i.lastUpdated)||a.lastUpdated});n.push(rx({id:m,dedupKey:m,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Sc(a),preview:qm(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return ox(n)}function cx(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function lx(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Sl}=e,a=o.useMemo(()=>ix(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>cx(a),[a]);return{notifications:a,unreadCount:i}}function dx({notifications:e,sendDaemonCommand:t}){const r=o.useCallback(i=>{const c=e.find(d=>d.id===i),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,t]),n=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const ux=o.createContext(null);function mx(){return o.useContext(ux)}function bn(...e){const t=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();t.has(c)||(t.add(c),r.push(i))};for(const a of e){if(Array.isArray(a)){for(const i of a)n(i);continue}n(a)}return r}function fx(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 gn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=fx(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 px(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 hx(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function yn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=hx(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.includes("\\")?"\\":"/",l=(m,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(i,m.name)})).sort((m,u)=>m.name.localeCompare(u.name)):[];return{path:i,directories:d}}function xx(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 Nl(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:xx(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function bx(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 Jt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function xo(e){return pr(e)||e.tabKey||e.routeId||null}function Cl(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(t)return t;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=Dt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?xo(a):null}function gx(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function bi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function gi(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function yx({ides:e,conversations:t,onOpenSession:r}){const[n,a]=o.useState(null),i=o.useCallback(c=>{a(c)},[]);return o.useEffect(()=>{if(!n)return;const c=bi(n.workspacePath),l=e.find(m=>{var g,p,j,b;if(!m||m.type==="adhdev-daemon"||gx(m.daemonId||m.id)!==n.machineId||(cr(m)?"cli":Ns(m)?"acp":"ide")!==n.kind||String(m.agentType||m.type||"")!==n.providerType)return!1;if(n.resumeSessionId)return String(m.providerSessionId||"")===n.resumeSessionId;if(c){const h=bi(m.workspace||m.runtimeWorkspaceLabel);return h?h===c:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((b=(j=(p=(g=m.activeChat)==null?void 0:g.messages)==null?void 0:p.at)==null?void 0:j.call(p,-1))==null?void 0:b.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const d=Cl({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});d&&(a(null),r(d))},[t,e,r,n]),o.useEffect(()=>{if(!n)return;const c=window.setTimeout(()=>{a(l=>!l||l.startedAt!==n.startedAt?l:null)},45e3);return()=>window.clearTimeout(c)},[n]),{trackPendingLaunch:i}}function vx({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=mx(),l=o.useCallback(async(p,j)=>yn(e,p,j),[e]),d=o.useCallback(async(p,j)=>{if(!j.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(p,"workspace_add",{path:j.trim()});return b!=null&&b.success?{ok:!0}:{ok:!1,error:(b==null?void 0:b.error)||"Could not save workspace"}}catch(b){return{ok:!1,error:b instanceof Error?b.message:"Could not save workspace"}}},[e]),m=o.useCallback(async(p,j,b)=>{var h;try{const y={ideType:j,enableCdp:!0};(h=b==null?void 0:b.workspacePath)!=null&&h.trim()&&(y.workspace=b.workspacePath.trim());const S=await e(p,"launch_ide",y);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:j,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(y){return{ok:!1,error:y instanceof Error?y.message:"Could not launch IDE"}}},[e,t]),u=o.useCallback(async(p,j,b,h)=>{var S,k,A;const y=Date.now();try{const M={cliType:b};(S=h==null?void 0:h.workspacePath)!=null&&S.trim()?M.dir=h.workspacePath.trim():h!=null&&h.workspaceId&&(M.workspaceId=h.workspaceId),(k=h==null?void 0:h.resumeSessionId)!=null&&k.trim()&&(M.resumeSessionId=h.resumeSessionId.trim()),Array.isArray(h==null?void 0:h.cliArgs)&&h.cliArgs.length>0&&(M.cliArgs=h.cliArgs),(A=h==null?void 0:h.initialModel)!=null&&A.trim()&&(M.initialModel=h.initialModel.trim());const w=await e(p,"launch_cli",M),v=(w==null?void 0:w.result)||w,B=(v==null?void 0:v.sessionId)||(v==null?void 0:v.id);return w!=null&&w.success&&B?(r(B),{ok:!0}):w!=null&&w.success?(t({machineId:p,kind:j,providerType:b,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:y}),{ok:!0}):{ok:!1,error:(w==null?void 0:w.error)||(v==null?void 0:v.error)||`Could not launch ${j.toUpperCase()} session`}}catch(M){return gi(M)?(t({machineId:p,kind:j,providerType:b,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:y}),{ok:!0}):{ok:!1,error:M instanceof Error?M.message:`Could not launch ${j.toUpperCase()} session`}}},[r,e,t]),f=o.useCallback(async p=>{var j;if(c!=null&&c.listMeshes)return c.listMeshes(p);if(!p)return[];try{const b=await e(p,"list_meshes",{}),h=(b==null?void 0:b.result)??b;if((h==null?void 0:h.success)===!1)throw new Error((h==null?void 0:h.error)||"Could not load meshes");return(Array.isArray(h==null?void 0:h.meshes)?h.meshes:Array.isArray((j=h==null?void 0:h.result)==null?void 0:j.meshes)?h.result.meshes:[]).map(S=>{var k;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(((k=S.nodes[0])==null?void 0:k.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(b){throw console.error("List meshes failed",b),b}},[c,e]),x=o.useCallback(async(p,j,b)=>{if(!j.trim())return{ok:!1,error:"Choose a mesh first."};if(c!=null&&c.launchMeshCoordinator)return c.launchMeshCoordinator(p,j,b);const h=Date.now();try{const y=await e(p,"launch_mesh_coordinator",{meshId:j.trim(),cliType:b.trim()||"claude-cli"}),S=(y==null?void 0:y.result)??y;if((S==null?void 0:S.success)===!1||(y==null?void 0:y.success)===!1){const A=String((S==null?void 0:S.code)||(y==null?void 0:y.code)||""),M=bx((S==null?void 0:S.meshCoordinatorSetup)||(S==null?void 0:S.manualSetup)||(y==null?void 0:y.meshCoordinatorSetup)||(y==null?void 0:y.manualSetup));return{ok:!1,error:(S==null?void 0:S.error)||(y==null?void 0:y.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:M}}const k=(S==null?void 0:S.sessionId)||(S==null?void 0:S.id);return k?r(k):t({machineId:p,kind:"cli",providerType:b,workspacePath:(S==null?void 0:S.workspace)||null,startedAt:h}),{ok:!0}}catch(y){return gi(y)?(t({machineId:p,kind:"cli",providerType:b,startedAt:h}),{ok:!0}):{ok:!1,error:y instanceof Error?y.message:"Could not launch mesh coordinator"}}},[c,r,e,t]),C=o.useCallback(async(p,j)=>{if(!p||!j)return[];try{const b=await e(p,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),h=(b==null?void 0:b.result)??b;return Array.isArray(h==null?void 0:h.sessions)?h.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),g=o.useCallback(async p=>{await pl({conversation:n,mode:p,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:i})},[n,a,e,i]);return{handleBrowseMachineDirectory:l,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:f,handleLaunchMeshCoordinator:x,handleListMachineSavedSessions:C,setActiveCliViewMode:g}}function wx(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 jx(e,t,r=Date.now()){return!e||!wx(t)?null:{tabKey:e,nonce:r}}function kx({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,d]=o.useState(null),[m,u]=o.useState(null),f=o.useMemo(()=>{var j,b;if(!e){if(l){const h=t.find(y=>y.tabKey===l);if(h)return h}return r[0]}const p=n[a];if(p){const h=t.find(y=>y.tabKey===p);if(h)return h}return((j=i[a])==null?void 0:j[0])||((b=i[0])==null?void 0:b[0])},[t,l,a,n,i,e,r]),x=o.useCallback(p=>{d(p)},[]),C=o.useCallback(p=>{d(p.tabKey),c(j=>{const b=new URLSearchParams(j),h=Xm(p);return h?b.set("activeTab",h):b.delete("activeTab"),b},{replace:!0})},[c]),g=o.useCallback((p,j)=>{const b=jx(p,j);b&&u(b)},[]);return{activeConv:f,openDesktopConversation:C,requestScrollToBottom:g,scrollToBottomRequest:m,setDesktopActiveTab:x}}function Sx(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 Nx(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&t&&t!==r),autoReadKey:i,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Cx({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=o.useRef(null),i=o.useRef(null),c=o.useRef(null),l=o.useRef(null),d=o.useRef(null);o.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),i.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const u=Qr(e,r),f=Nx({tabKey:e.tabKey,historySessionId:pr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:ls(e),liveState:u}),x=f.autoReadKey,C=Sx({autoReadKey:x,shouldMarkSeen:f.shouldMarkSeen,completedKey:a.current,pendingKey:i.current});if(!f.shouldMarkSeen){C.shouldCancelPending&&m(),a.current=x;return}if(!C.shouldSchedule)return;C.shouldCancelPending&&m();const g=()=>{if(document.visibilityState!=="visible"||a.current===x)return;a.current=x,i.current=null,c.current=null,l.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const j=f.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:j,completionMarker:f.completionMarker}).catch(()=>{})};if(i.current=C.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(g,1500);const j=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};d.current=j,document.addEventListener("visibilitychange",j);return}const p=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(g,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),o.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function Un(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 Tx({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:d}){var I;const[m,u]=o.useState(!1),[f,x]=o.useState([]),[C,g]=o.useState(()=>vt()),[p,j]=o.useState(!1),[b,h]=o.useState(null),y=o.useRef(null),S=o.useMemo(()=>r||t||e,[e,r,t]),k=!!S&&tt(S)&&!Ze(S),A=o.useMemo(()=>{if(!S||!k)return null;const W=S.daemonId||S.routeId||"",P=Kt(S),$=Un(S);return`${W}:${P}:${S.providerSessionId||""}:${$}`},[S,k]),M=o.useMemo(()=>!S||!k?"":Un(S),[S,k]),{isCreatingChat:w,isRefreshingHistory:v,handleSwitchSession:B,handleNewChat:_,handleRefreshHistory:T}=wl({sendDaemonCommand:a,activeConv:S,chats:(I=n.find(W=>W.id===(S==null?void 0:S.routeId)))==null?void 0:I.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),D=o.useCallback(()=>{u(!0)},[]),K=o.useCallback(()=>{u(!1)},[]),L=o.useCallback(async()=>{if(!(!S||!k||p)){j(!0);try{const W=S.daemonId||S.routeId,P=Kt(S),$=Un(S),H=await a(W,"list_saved_sessions",{agentType:P,providerType:P,kind:"cli",limit:50,...S.providerSessionId?{providerSessionId:S.providerSessionId}:{},...$?{workspace:$}:{}}),J=(H==null?void 0:H.result)??H;x(Array.isArray(J==null?void 0:J.sessions)?J.sessions:[])}catch(W){console.error("Refresh saved sessions failed",W),x([])}finally{j(!1)}}},[S,p,k,a]);o.useEffect(()=>{if(!m){y.current=null;return}if(!k){y.current=null,x([]),j(!1);return}!A||p||y.current!==A&&(y.current=A,L())},[L,m,p,k,A]);const N=o.useCallback(async W=>{if(!S||!k||!W.providerSessionId||!W.workspace)return;const P=S.daemonId||S.routeId,$=Kt(S);try{h(W.providerSessionId);const H=await a(P,"launch_cli",{cliType:$,dir:W.workspace,resumeSessionId:W.providerSessionId,initialModel:bc(W.summaryMetadata,"model",{preferShortValue:!0})||void 0}),J=(H==null?void 0:H.result)??H,he=typeof(J==null?void 0:J.sessionId)=="string"?J.sessionId:typeof(J==null?void 0:J.id)=="string"?J.id:"";he&&d(ie=>{const te=new URLSearchParams(ie);return te.set("activeTab",he),te},{replace:!0}),K()}catch(H){console.error("Resume saved session failed",H)}finally{h(null)}},[K,S,k,a,d]);return{historyModalOpen:m,openHistoryModal:D,closeHistoryModal:K,historyTargetConv:S,isSavedSessionHistoryTarget:k,isHistoryCreatingChat:w,isHistoryRefreshingHistory:v,handleHistorySwitchSession:B,handleHistoryNewChat:_,handleHistoryRefresh:T,savedHistorySessions:f,savedHistoryFilters:C,setSavedHistoryFilters:g,missingWorkspaceResumePath:M,isSavedHistoryLoading:p,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:L,handleResumeSavedHistorySession:N}}function Mx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[d,m]=o.useState(null),[u,f]=o.useState(null),x=o.useMemo(()=>{if(e||!n)return null;const b=l(n);return b&&!tt(b)&&!Ze(b)?b:null},[e,n,l]),C=o.useMemo(()=>{const b=d==null?void 0:d.routeId;if(!b)return null;const h=d!=null&&d.tabKey?i.find(y=>y.tabKey===d.tabKey):a?i.find(y=>y.tabKey===a):null;return(h==null?void 0:h.routeId)===b?h:Dt(i,b)},[i,d,a]),g=o.useMemo(()=>{if(C)return c.find(b=>b.id===C.routeId)},[c,C]);o.useEffect(()=>{x&&(m({routeId:x.routeId,tabKey:Vo(x)}),f(x),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,x]);const p=o.useCallback(b=>{b&&(m({routeId:b.routeId,tabKey:Vo(b)}),f(b))},[]),j=o.useCallback(()=>{m(null),f(null)},[]);return{remoteDialogConv:C,remoteDialogIdeEntry:g,remoteDialogActiveConv:u,setRemoteDialogActiveConv:f,openRemoteDialog:p,closeRemoteDialog:j}}function Ax({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:f,remoteDialogActiveConv:x,setRemoteDialogActiveConv:C,openRemoteDialog:g,closeRemoteDialog:p}=Mx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[j,b]=o.useState(!1),[h,y]=o.useState(null),S=o.useCallback(async M=>{const w=M||d;!w||!tt(w)&&!Ze(w)||(y(w),b(!0))},[d]),k=o.useCallback(()=>{b(!1),y(null)},[]),A=o.useCallback(async M=>{const w=h||d;if(!w||!tt(w)&&!Ze(w)){k();return}b(!1);try{const v=Kt(w),B=w.routeId||w.daemonId||"";await m(B,"stop_cli",{cliType:v,targetSessionId:w.sessionId,mode:M})}catch(v){console.error("Stop CLI failed:",v)}finally{y(null)}},[d,k,h,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:f,remoteDialogActiveConv:x,setRemoteDialogActiveConv:C,openRemoteDialog:g,closeRemoteDialog:p,cliStopDialogOpen:j,cliStopTargetConv:h,requestCliStop:S,cancelCliStop:k,confirmCliStop:A}}function Tl({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:i=!1}){var b;const c=$s(),l=bs(e),d=i?null:kc(e),m=!i&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!i&&e.streamSource==="agent-stream"&&!!e.agentName,f=!i&&!u&&(e.transport==="pty"||e.transport==="acp"),x=Rs(e),C=Ym(e),g=(b=e.settings)==null?void 0:b.meshNodeFor;if(!m&&!u&&!f&&!d&&!g)return null;const p=o.useCallback(()=>{if(n){n();return}l&&c("/dashboard",{state:{openMachineId:l}})},[l,c,n]),j=o.useCallback(()=>{if(r){r();return}const h=xo(e);h&&c(Jt(h))},[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:j,title:C,children:[s.jsx(Mt,{size:12}),s.jsx("span",{children:C})]}):s.jsxs("span",{className:"conversation-meta-chip",title:C,children:[s.jsx(Mt,{size:12}),s.jsx("span",{children:C})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Is,{size:12}),s.jsx("span",{children:x})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Is,{size:12}),s.jsx("span",{children:x})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:p,title:d,children:[s.jsx(Yt,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(Yt,{size:12}),s.jsx("span",{children:d})]})),g&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Yt,{size:12}),s.jsx("span",{children:"Mesh Node"})]})]})}function zn(e,t=!0){return(e??!0)&&t}const bo=o.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u=null,handleFocusAgent:f,isFocusingAgent:x,actionLogs:C,userName:g,scrollToBottomRequestNonce:p,isInputActive:j=!0,isVisible:b=!0}){const h=n,y=!n,S=zn(b,h),k=zn(b,y),A=zn(b),M=ll(t),w=M.status||M.modalMessage||M.modalButtons?{...t,...M.status?{status:M.status}:{},...M.modalMessage!==void 0?{modalMessage:M.modalMessage}:{},...M.modalButtons!==void 0?{modalButtons:M.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(fc,{activeConv:w,onModalButton:c}),s.jsx(Tl,{conversation:w,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),w.transport!=="pty"&&w.transport!=="acp"&&w.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(ir,{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,w.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:h?"visible":"hidden",pointerEvents:h?"auto":"none"},children:s.jsx(ip,{activeConv:w,clearToken:r,terminalRef:i,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,isVisible:S,isInputActive:j&&S})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:y?"visible":"hidden",pointerEvents:y?"auto":"none"},children:s.jsx(ka,{activeConv:w,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:x,actionLogs:C,userName:g,scrollToBottomRequestNonce:p,isInputActive:j&&k,isVisible:k})})]}):s.jsx(ka,{activeConv:w,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:x,actionLogs:C,userName:g,scrollToBottomRequestNonce:p,isInputActive:j&&A,isVisible:A})]})},(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 Ix({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:f,onOpenHistory:x,onOpenRemote:C,onStopCli:g,cliViewMode:p,onSetCliViewMode:j,handleSendChat:b,handleFocusAgent:h,handleModalButton:y,handleRelaunch:S}){const k=o.useRef(null),A=tt(e)&&!t,M=A&&p==="terminal",w=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 ${w} 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(Ba,{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:lt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(Tl,{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:[A&&p&&s.jsx(to,{mode:p,onChange:j,compact:!0}),A&&g&&s.jsx("button",{onClick:()=>{g(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(yt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",children:s.jsx(Ka,{size:14})}),!t&&!A&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>C(e),type:"button",children:s.jsx(Mt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(bo,{activeConv:e,clearToken:0,isCliTerminal:M,ideEntry:n,terminalRef:k,handleModalButton:y,handleRelaunch:S,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:h,isFocusingAgent:d,actionLogs:a,userName:i})})]})}const Vn={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 Rx(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Ml(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(Rx())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Vn[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:Vn[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Vn[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 Al({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Mt},{key:"chats",label:"Chats",icon:Ut}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:i})=>{const c=e===n;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(n),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(i,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function Lr({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 ys({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 Gs({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 Lx({conversation:e,onCancel:t,onConfirm:r}){const n=lt(e),a=ps(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(yt,{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 _r({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onCollectChatDebugBundle:i}){const c=t==="needs_attention"||t==="task_complete",l=t==="working",d=t==="earlier",m=t==="task_complete",{isReconnecting:u,isConnecting:f}=Bs(e.conversation),x=lt(e.conversation),C=ps(e.conversation),g=Hc(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",j=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",b=d?"text-text-secondary":"text-text-primary",h=d?"text-text-muted":"text-text-secondary",y=d?"text-text-secondary opacity-80":"text-text-muted",S=d?"text-text-muted opacity-80":"text-text-muted",k=!l&&!m,A="text-[color:var(--status-warning)]",M=w=>{if(!i)return;w.preventDefault(),w.stopPropagation();const v=i==null?void 0:i(e.conversation);Promise.resolve(v).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 ${j}`,style:c?{color:"var(--accent-on-primary)"}:void 0,children:r(x)}),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:w=>{w.preventDefault(),w.stopPropagation(),a()},"aria-label":`Hide ${x}`,title:"Hide conversation",children:[s.jsx(Wa,{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:M,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 ${b}`,children:x}),k&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${S}`,children:mc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${h}`,children:[s.jsx("span",{className:"truncate",children:C}),s.jsx(_s,{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:`${A} 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…"})]}):g==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:A,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,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 yi({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 _x({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:f,onHideConversation:x,onOpenNewSession:C,onOpenMachine:g,onOpenSettings:p,onSectionChange:j,wsStatus:b="connected",isStandalone:h=!1,onCollectChatDebugBundle:y}){const[S,k]=o.useState(null),A=b==="disconnected"||b==="reconnecting"||b==="offline"||b==="auth_failed",M=c.length>0,w=t.length>0||r.length>0||n.length>0||a.length>0,v=e==="machines"?"Machines":"Chats",B=h?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",_=h?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",T=o.useCallback(async L=>{const N=Ls(L);if(!N)return;const I=Array.isArray(L.messages)?L.messages:[],W=Ac({activeConv:L,visibleMessages:I,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:I.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),P=await m(N,"get_chat_debug_bundle",{...rs(L),delivery:"daemon_file",frontendSnapshot:W}),$=tn(P),H=Lc($),J=await Rc(H);J==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),at.showToast(Ic($,{locatorCopyStatus:J}),J==="failed"?"warning":"success")},[d,m]),D=y||T,K=o.useCallback(()=>{S&&(x==null||x(S),k(null))},[S,x]);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:v}),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(un,{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(dn,{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:A?s.jsx(Gs,{icon:s.jsx(yi,{}),title:b==="offline"?"Network offline":b==="auth_failed"?"Session expired":"Reconnecting",subtitle:b==="offline"?"Waiting for network…":b==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(Gs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:h?"Waiting for your daemon":"Connect your machines",subtitle:h?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!h&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Ml,{})})}):s.jsx(ys,{children:c.map((L,N)=>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] ${N>0?"border-t border-border-subtle/70":""}`,onClick:()=>g(L.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(L.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:L.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:L.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[L.unread," new"]}):L.total>0?`${L.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:L.subtitle}),L.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[L.total," chat",L.total!==1?"s":"",L.unread>0?` · ${L.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},L.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(Lr,{title:"Needs attention",className:"mb-0"}),s.jsx(ys,{children:t.map((L,N)=>s.jsx("div",{className:N>0?"border-t border-border-subtle/70":"",children:s.jsx(_r,{item:L,type:"needs_attention",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>k(L.conversation):void 0,onCollectChatDebugBundle:D})},L.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(Lr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(ys,{children:r.map((L,N)=>s.jsx("div",{className:N>0?"border-t border-border-subtle/70":"",children:s.jsx(_r,{item:L,type:"task_complete",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>k(L.conversation):void 0,onCollectChatDebugBundle:D})},L.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(Lr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(ys,{children:n.map((L,N)=>s.jsx("div",{className:N>0?"border-t border-border-subtle/70":"",children:s.jsx(_r,{item:L,type:"working",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>k(L.conversation):void 0,onCollectChatDebugBundle:D})},L.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(Lr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(ys,{children:a.map((L,N)=>s.jsx("div",{className:N>0?"border-t border-border-subtle/70":"",children:s.jsx(_r,{item:L,type:"earlier",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>k(L.conversation):void 0,onCollectChatDebugBundle:D})},L.conversation.tabKey))}):w?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):A?s.jsx(Gs,{icon:s.jsx(yi,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):M?s.jsx(Gs,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Ut,{size:20})}),title:"No conversations yet",subtitle:Vc,children:C&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:C,"aria-label":$t,title:$t,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:$t})]})}):s.jsx(Gs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(ys,{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:[i.length," collapsed ",i.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"&&C&&w&&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:C,"aria-label":$t,title:$t,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),S&&s.jsx(Lx,{conversation:S,onCancel:()=>k(null),onConfirm:K}),s.jsx(Al,{section:e,onSectionChange:j})]})}function Px(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 Il(e){const t=[e.workspace||"Workspace unknown"],r=fs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Px(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function vn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:d,onConfirm:m}){const[u,f]=o.useState(r);o.useEffect(()=>{f(r)},[r]);const x=px(r),C=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(yt,{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:()=>{!x||a||d(x)},disabled:!x||a,children:[s.jsx(Ba,{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:g=>f(g.target.value),onKeyDown:g=>{g.key!=="Enter"||!C||a||(g.preventDefault(),d(C))},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:()=>{!C||a||d(C)},disabled:!C||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(g=>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(g.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(ms,{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:g.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:g.path})]})]},g.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(C||r),disabled:!C&&!r||a,children:c})]})]})})}function go({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:f,showModelInput:x,modelValue:C,onModelChange:g,historyProviderNode:p,onConfirm:j,onCancel:b}){const h=n==null?void 0:n.find(y=>y.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:b,"aria-label":"Close launch confirmation",children:s.jsx(yt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:y=>i(y.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(y=>s.jsx("option",{value:y.key,children:y.label},y.key))}),(h==null?void 0:h.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),p,r.map(y=>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:y.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:y.value})]},`${y.label}:${y.value}`)),x&&g&&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:C||"",onChange:y=>g(y.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:y=>f(y.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:b,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:j,disabled:d,children:[s.jsx(Fa,{size:14}),d?l:c]})]})]})})}function vi(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ds(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])i.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${vi(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(d=>d.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:vi(c),description:c,workspaceId:null,workspacePath:c}),n){const d=`saved:${n}`;if(i.some(m=>m.key===d))return{options:i,selectedKey:d}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Dx(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Ex(e){return[Dx(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function $x(e){return e.lastLaunchedAt?mn(e.lastLaunchedAt):""}function Rl(e){return{metaText:Ex(e),updatedLabel:$x(e)}}function Gn(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Bx({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var st,mt,ht,xt;const c=fr(),[l,d]=o.useState(!1),m=(((st=e.detectedIdes)==null?void 0:st.length)||0)>0,u=o.useMemo(()=>(e.workspaces||[]).map(Ne=>({id:Ne.id,path:Ne.path,label:Ne.label})),[e]),f=e.defaultWorkspaceId||null,[x,C]=o.useState(f||((mt=u[0])==null?void 0:mt.id)||""),[g,p]=o.useState(""),[j,b]=o.useState(""),[h,y]=o.useState([]),[S,k]=o.useState(!1),[A,M]=o.useState(""),[w,v]=o.useState(!1),[B,_]=o.useState(Gn(m,t.length,r.length)),T=o.useRef(null),[D,K]=o.useState(null),L=o.useRef("__home__"),[N,I]=o.useState("__home__"),[W,P]=o.useState(""),[$,H]=o.useState(""),[J,he]=o.useState(""),[ie,te]=o.useState([]),[be,we]=o.useState(()=>vt().textQuery),[ge,X]=o.useState(()=>vt().workspaceQuery),[ce,ye]=o.useState(()=>vt().modelQuery),[ne,de]=o.useState(()=>vt().resumableOnly),[je,me]=o.useState(()=>vt().sortMode),[pe,ee]=o.useState(!1),[ue,oe]=o.useState(!1),q=o.useRef(null),V=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const le=x==="__custom__"?g.trim():((ht=u.find(Ne=>Ne.id===x))==null?void 0:ht.path)||"",ke=x==="__custom__"&&!!le&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),Z=x!=="__custom__"&&((xt=u.find(Ne=>Ne.id===x))==null?void 0:xt.path)||"",De=o.useMemo(()=>(e.recentLaunches||[]).map(Ne=>Ne.workspace),[e]),$e=o.useCallback(async Ne=>{k(!0),M("");try{const ze=await a(Ne);b(ze.path),p(ze.path),y(ze.directories)}catch(ze){M(ze instanceof Error?ze.message:"Could not load folder")}finally{k(!1)}},[a]),Fe=o.useCallback(()=>{var ze;C("__custom__"),v(!0);const Ne=gn(e.platform,bn(g.trim(),Z,De,e.defaultWorkspacePath,(ze=u.find(Je=>Je.id===f))==null?void 0:ze.path,u.map(Je=>Je.path)));$e(Ne)},[g,f,$e,De,Z,e.platform,u]),Ue=o.useCallback(Ne=>{if(Ne!=null&&Ne.workspaceId){C(Ne.workspaceId),p("");return}if(Ne!=null&&Ne.workspacePath){C("__custom__"),p(Ne.workspacePath);return}C(""),p("")},[]),O=o.useCallback(Ne=>{if(C(Ne),Ne==="__custom__"){Fe();return}p("")},[Fe]),Ce=o.useCallback(Ne=>{C("__custom__"),p(Ne)},[]),Te=o.useCallback((Ne,ze)=>{T.current=ze,L.current=Ne.selectedWorkspaceKey||"__home__",I(Ne.selectedWorkspaceKey||"__home__"),P(Ne.initialArgs||""),H(Ne.initialModel||""),he(""),te([]);const Je=Ne.providerType?`${e.id}:${Ne.providerType}`:null;if(gp(V.current,Je)){const Ge=vt();we(Ge.textQuery),X(Ge.workspaceQuery),ye(Ge.modelQuery),de(Ge.resumableOnly),me(Ge.sortMode)}V.current=Je,K(Ne),Ne.providerType&&i&&(ee(!0),i(Ne.providerType).then(Ge=>te(Ge||[])).catch(Ge=>console.warn("Failed to load saved sessions",Ge)).finally(()=>ee(!1)))},[i,e.id]),_e=o.useMemo(()=>Gc(ie,{textQuery:be,workspaceQuery:ge,modelQuery:ce,resumableOnly:ne,sortMode:je}),[ce,ne,ie,je,be,ge]);o.useEffect(()=>{J&&(_e.some(Ne=>Ne.providerSessionId===J)||he(""))},[_e,J]);const Be=o.useCallback(()=>{T.current&&(oe(!0),T.current().finally(()=>{T.current=null,oe(!1),K(null)}))},[]),He=o.useCallback(()=>{T.current=null,K(null)},[]),Xe=o.useCallback(Ne=>{L.current=Ne,I(Ne)},[]);return o.useEffect(()=>{var Ne;q.current!==e.id&&(q.current=e.id,C(f||((Ne=u[0])==null?void 0:Ne.id)||"__custom__"),p(""),b(""),y([]),M(""),v(!1),we(vt().textQuery),X(vt().workspaceQuery),ye(vt().modelQuery),de(vt().resumableOnly),me(vt().sortMode),V.current=null,_(Gn(m,t.length,r.length)))},[r.length,t.length,f,m,e.id,u]),o.useEffect(()=>{var Ne;x!=="__custom__"&&(x&&u.some(ze=>ze.id===x)||C(f||((Ne=u[0])==null?void 0:Ne.id)||"__custom__"))},[f,x,u]),o.useEffect(()=>{B==="ide"&&m||B==="cli"&&t.length>0||B==="acp"&&r.length>0||_(Gn(m,t.length,r.length))},[B,r.length,t.length,m]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:f,workspaceChoice:x,customWorkspacePath:g,browseCurrentPath:j,browseDirectories:h,browseBusy:S,browseError:A,browseDialogOpen:w,activeLauncherKind:B,launchConfirm:D,launchConfirmWorkspaceKeyRef:L,launchConfirmWorkspaceKey:N,launchConfirmArgs:W,launchConfirmModel:$,launchConfirmResumeId:J,launchConfirmSavedSessions:ie,launchConfirmTextFilter:be,launchConfirmWorkspaceFilter:ge,launchConfirmModelFilter:ce,launchConfirmResumableOnly:ne,launchConfirmSortMode:je,filteredLaunchConfirmSavedSessions:_e,launchConfirmSessionsLoading:pe,launchConfirmBusy:ue,resolvedWorkspacePath:le,canCreateMissingWorkspace:ke,openBrowseDialog:Fe,loadBrowsePath:$e,handleWorkspaceChoiceChange:O,chooseCustomWorkspacePath:Ce,setCustomWorkspacePath:p,setBrowseDialogOpen:v,setActiveLauncherKind:_,openLaunchConfirm:Te,handleConfirmLaunch:Be,closeLaunchConfirm:He,setWorkspaceSelectionFromOption:Ue,setLaunchConfirmWorkspaceKeyAndSync:Xe,setLaunchConfirmArgs:P,setLaunchConfirmModel:H,setLaunchConfirmResumeId:he,setLaunchConfirmTextFilter:we,setLaunchConfirmWorkspaceFilter:X,setLaunchConfirmModelFilter:ye,setLaunchConfirmResumableOnly:de,setLaunchConfirmSortMode:me}}function Kx({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:d,section:m,showBottomNav:u,onBack:f,onSectionChange:x,onOpenConversation:C,onOpenRecent:g,onOpenMachineDetails:p,onMachineUpgrade:j,onLaunchDetectedIde:b,onAddWorkspace:h,onBrowseDirectory:y,onLaunchWorkspaceProvider:S,onListSavedSessions:k}){const A=N=>N==="ide"?"IDE":N==="cli"?"CLI":"ACP",M=r.slice(0,4),w=t.slice(0,3),v=Bx({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:y,onListSavedSessions:k}),B=o.useMemo(()=>M.map(N=>{const{metaText:I,updatedLabel:W}=Rl(N);return{key:`recent-launch:${N.id}`,primary:N.label,secondary:I,updatedLabel:W,onClick:()=>{const{options:P,selectedKey:$}=ds({machine:{workspaces:v.workspaceRows,defaultWorkspaceId:v.defaultWorkspaceId},currentWorkspacePath:N.workspace});v.openLaunchConfirm({title:N.kind==="ide"?as("restart-ide",N.label):N.providerSessionId?no(N.label):as("start-fresh",N.label),description:N.kind==="ide"?os("restart-ide"):N.providerSessionId?ao():os("start-fresh"),confirmLabel:N.kind==="ide"?Ps("restart-ide"):N.providerSessionId?rn(!0):Ps("start-fresh"),busyLabel:N.kind==="ide"?Ds("restart-ide"):N.providerSessionId?so(!0):Ds("start-fresh"),workspaceOptions:P,selectedWorkspaceKey:$,details:[{label:"Mode",value:A(N.kind)},...N.providerType?[{label:"Provider",value:N.providerType}]:[]]},async()=>{const H=P.find(J=>J.key===v.launchConfirmWorkspaceKeyRef.current);v.setWorkspaceSelectionFromOption(H),await g({...N,workspace:(H==null?void 0:H.workspacePath)??null})})}}}),[v,g,M]),_=o.useMemo(()=>w.map(N=>({key:`recent-chat:${N.conversation.tabKey}`,primary:lt(N.conversation),secondary:rp(N.conversation,{timestampLabel:N.timestamp?mc(N.timestamp):null}),unread:N.unread,onClick:()=>C(N.conversation)})),[C,w]),T=v.showAllRecent?B:B.slice(0,4),D=B.length>0,K=_.length>0,L=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 ${L} 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(Ba,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Tt(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[K&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:_.map(N=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${N.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:N.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:N.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))})]}),D&&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(N=>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:N.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:N.primary}),N.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:N.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.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:()=>v.setShowAllRecent(N=>!N),children:v.showAllRecent?"Show fewer":`Show ${B.length-4} more`})})]}),(v.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:v.workspaceChoice,onChange:N=>v.handleWorkspaceChoiceChange(N.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:v.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[v.workspaceRows.map(N=>s.jsxs("option",{value:N.id,children:[N.id===v.defaultWorkspaceId?"⭐ ":"",pn(N.path,N.label)||N.path]},N.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),v.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(ms,{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:v.resolvedWorkspacePath||v.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:v.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:()=>{v.resolvedWorkspacePath&&h(v.resolvedWorkspacePath)},disabled:!v.resolvedWorkspacePath||v.browseBusy,children:"Save as workspace"})]})]}),v.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:v.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[v.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${v.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:()=>v.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${v.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:()=>v.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${v.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:()=>v.setActiveLauncherKind("acp"),children:"ACP"})]}),v.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:v.activeLauncherKind==="ide"?"Choose an IDE":v.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:v.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(N=>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:I,selectedKey:W}=ds({machine:{workspaces:v.workspaceRows,defaultWorkspaceId:v.defaultWorkspaceId},currentWorkspaceId:v.workspaceChoice!=="__custom__"?v.workspaceChoice:null,currentWorkspacePath:v.resolvedWorkspacePath});v.openLaunchConfirm({title:`Launch ${N.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:I,selectedWorkspaceKey:W,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:N.name}]},async()=>{const P=I.find($=>$.key===v.launchConfirmWorkspaceKeyRef.current);v.setWorkspaceSelectionFromOption(P),b(N.type,{workspacePath:(P==null?void 0:P.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:N.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:v.resolvedWorkspacePath||"Use selected workspace"})]},N.type)):(v.activeLauncherKind==="cli"?n:a).map(N=>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 I=v.activeLauncherKind==="cli"?"cli":"acp",{options:W,selectedKey:P}=ds({machine:{workspaces:v.workspaceRows,defaultWorkspaceId:v.defaultWorkspaceId},currentWorkspaceId:v.workspaceChoice!=="__custom__"?v.workspaceChoice:null,currentWorkspacePath:v.resolvedWorkspacePath});v.openLaunchConfirm({title:`Launch ${N.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${I.toUpperCase()}`,workspaceOptions:W,selectedWorkspaceKey:P,details:[{label:"Mode",value:I.toUpperCase()},{label:"Provider",value:N.displayName}],showArgsInput:!0,showModelInput:I==="acp",initialArgs:"",initialModel:"",providerType:N.type},async()=>{const $=W.find(H=>H.key===v.launchConfirmWorkspaceKeyRef.current);v.setWorkspaceSelectionFromOption($),S(I,N.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.workspacePath)??null,args:v.launchConfirmArgs,model:v.launchConfirmModel,resumeSessionId:v.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[N.icon?`${N.icon} `:"",N.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:v.resolvedWorkspacePath||"Use selected workspace"})]},N.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,v.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:()=>h(v.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:j,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"})]})]})]})]}),v.browseDialogOpen&&s.jsx(vn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:v.browseCurrentPath,directories:v.browseDirectories,busy:v.browseBusy,error:v.browseError,confirmLabel:"Use this folder",onClose:()=>v.setBrowseDialogOpen(!1),onNavigate:N=>{v.loadBrowsePath(N)},onConfirm:N=>{v.chooseCustomWorkspacePath(N),v.setBrowseDialogOpen(!1)}}),v.launchConfirm&&s.jsx(go,{title:v.launchConfirm.title,description:v.launchConfirm.description,details:v.launchConfirm.details,workspaceOptions:v.launchConfirm.workspaceOptions,selectedWorkspaceKey:v.launchConfirmWorkspaceKey,onWorkspaceChange:v.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:v.launchConfirm.providerType?rn(!!v.launchConfirmResumeId):v.launchConfirm.confirmLabel,busyLabel:v.launchConfirm.providerType?void 0:v.launchConfirm.busyLabel,busy:v.launchConfirmBusy,showArgsInput:v.launchConfirm.showArgsInput,argsValue:v.launchConfirmArgs,onArgsChange:v.setLaunchConfirmArgs,showModelInput:v.launchConfirm.showModelInput,modelValue:v.launchConfirmModel,onModelChange:v.setLaunchConfirmModel,historyProviderNode:v.launchConfirm.providerType&&(v.launchConfirmSessionsLoading||v.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"}),v.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:ro()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:v.launchConfirmTextFilter,onChange:N=>v.setLaunchConfirmTextFilter(N.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:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:v.launchConfirmWorkspaceFilter,onChange:N=>v.setLaunchConfirmWorkspaceFilter(N.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:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:v.launchConfirmModelFilter,onChange:N=>v.setLaunchConfirmModelFilter(N.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:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),s.jsxs("select",{value:v.launchConfirmSortMode,onChange:N=>v.setLaunchConfirmSortMode(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.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:v.launchConfirmResumableOnly,onChange:N=>v.setLaunchConfirmResumableOnly(N.target.checked),disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:v.launchConfirmResumeId,onChange:N=>v.setLaunchConfirmResumeId(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:wp()}),v.filteredLaunchConfirmSavedSessions.map(N=>s.jsxs("option",{value:N.providerSessionId,disabled:!N.canResume,children:[N.title||N.providerSessionId," ",N.canResume?"":"(workspace missing)"]},N.providerSessionId))]}),!v.launchConfirmSessionsLoading&&v.launchConfirmSavedSessions.length>0&&v.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),v.launchConfirmResumeId&&(()=>{const N=v.filteredLaunchConfirmSavedSessions.find(W=>W.providerSessionId===v.launchConfirmResumeId);if(!N)return null;const I=Il(N);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:I.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:I.providerSessionId}),s.jsx("div",{className:"mt-1",children:I.metaLine}),I.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:I.updatedLabel}),I.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:I.preview})]})})()]}),onConfirm:v.handleConfirmLaunch,onCancel:v.closeLaunchConfirm}),u&&s.jsx(Al,{section:m,onSectionChange:x})]})}function Ur(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Wx(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:Ur(e)}function Ox(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 Fx(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:fs(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,d,m,u;const a=cr(n)?"cli":Ns(n)?"acp":"ide",i=fs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(cr(n)?n.cliName||n.type:Ns(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ns(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((u=(m=(d=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:d.at)==null?void 0:m.call(d,-1))==null?void 0:u.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Hx(e,t){const r=new Map;for(const n of t){const a=bs(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((f,x)=>x.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=ga(n),d=a.filter(f=>f.unread||f.requiresAction).length,m=Ox(n),u=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Tt(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?np(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const i=n.latestTimestamp||n.fallbackActivityAt||0,c=a.latestTimestamp||a.fallbackActivityAt||0;return c!==i?c-i:n.label.localeCompare(a.label)})}function Ux(e){return e==="chat"}function Pr(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 zx({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:C,setSelectedTabKey:g,setScreen:p,setSelectedMachineId:j,setSection:b,setMachineBackTarget:h,resetMachineAction:y}){const S=o.useRef(null),k=o.useCallback(A=>{if(!(A!=null&&A.sessionId))return;const M=Qr(A,c),w=Math.max(Date.now(),ls(A),M.lastUpdated||0);Pr("mark_read:start",{tabKey:A.tabKey,sessionId:A.sessionId,displayPrimary:lt(A),inboxBucket:M.inboxBucket,unread:M.unread,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,activityAt:ls(A),readAt:w}),l(bs(A)||A.routeId,"mark_session_seen",{sessionId:A.sessionId,providerSessionId:A.providerSessionId,seenAt:w,completionMarker:M.completionMarker}).then(v=>{Pr("mark_read:result",{tabKey:A.tabKey,sessionId:A.sessionId,result:v})}).catch(v=>{Pr("mark_read:error",{tabKey:A.tabKey,sessionId:A.sessionId,error:v instanceof Error?v.message:String(v)})})},[c,l]);return o.useEffect(()=>{var M;if(!n){Ux(i)&&p("inbox"),g(((M=e[0])==null?void 0:M.tabKey)||null),S.current=null;return}if(i!=="chat"){S.current=null;return}const A=`${n.tabKey}:${n.sessionId||""}`;S.current!==A&&(S.current=A,k(n))},[e,k,i,n,p,g]),o.useEffect(()=>{if(!d)return;const A=e.find(M=>M.tabKey===d);A&&(g(A.tabKey),p("chat"),m==null||m())},[e,m,d,p,g]),o.useEffect(()=>{if(!u)return;const A=t.find(M=>M.id===u);A&&(j(A.id),y(),b("machines"),h("inbox"),p("machine"),f==null||f())},[t,f,u,y,h,p,b,j]),o.useEffect(()=>{x&&(b(x),p("inbox"),C==null||C())},[C,x,p,b]),o.useEffect(()=>{const A=r.filter(M=>M.inboxBucket==="task_complete"||M.unread);A.length!==0&&Pr("inbox_state",{screen:i,selectedTabKey:a,items:A.map(M=>{const w=Qr(M.conversation,c);return{liveState:w,tabKey:M.conversation.tabKey,sessionId:M.conversation.sessionId,displayPrimary:lt(M.conversation),serverBucket:w.inboxBucket,computedBucket:M.inboxBucket,serverUnread:w.unread,computedUnread:M.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:ls(M.conversation)}})})},[r,c,i,a]),{markConversationRead:k}}function Vx(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function wi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Gx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function qx({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[d,m]=o.useState(null),u=o.useCallback(()=>{i("idle"),l(""),m(null)},[]),f=o.useCallback(async(h,y,S)=>{var k;try{i("loading"),l(`Launching ${y}…`);const A={ideType:y,enableCdp:!0};(k=S==null?void 0:S.workspacePath)!=null&&k.trim()&&(A.workspace=S.workspacePath.trim()),await e(h,"launch_ide",A),i("done"),l(`${y} launch requested`)}catch(A){i("error"),l(A instanceof Error?A.message:"Launch IDE failed"),console.error("Launch IDE failed",A)}},[e]),x=o.useCallback(async(h,y,S)=>{if(y.trim())try{i("loading"),l(S!=null&&S.createIfMissing?"Creating folder…":"Saving workspace…");const k=await e(h,"workspace_add",{path:y.trim(),createIfMissing:(S==null?void 0:S.createIfMissing)===!0});if(k!=null&&k.success){i("done"),l(S!=null&&S.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((k==null?void 0:k.error)||"Could not save workspace")}catch(k){i("error"),l(k instanceof Error?k.message:"Could not save workspace")}},[e]),C=o.useCallback(async h=>{var y,S,k,A,M,w;try{i("loading"),l("Starting daemon upgrade…");const v=await e(h,"daemon_upgrade",{});if((y=v==null?void 0:v.result)!=null&&y.alreadyLatest){i("done"),l(`Already on v${((S=v==null?void 0:v.result)==null?void 0:S.version)||"latest"}.`);return}if((k=v==null?void 0:v.result)!=null&&k.upgraded||(A=v==null?void 0:v.result)!=null&&A.success){i("done"),l(`Upgrade to v${((M=v==null?void 0:v.result)==null?void 0:M.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((w=v==null?void 0:v.result)==null?void 0:w.error)||"Upgrade failed")}catch(v){i("error"),l(v instanceof Error?v.message:"Upgrade failed")}},[e]),g=o.useCallback(async(h,y,S,k)=>{var w,v,B;const A=Date.now(),M={machineId:h,kind:y,providerType:S,workspaceId:(k==null?void 0:k.workspaceId)||null,workspacePath:(k==null?void 0:k.workspacePath)||null,resumeSessionId:(k==null?void 0:k.resumeSessionId)||null,startedAt:A};try{i("loading"),l(`Launching ${S}…`),m(M);const _={cliType:S};(w=k==null?void 0:k.workspacePath)!=null&&w.trim()?_.dir=k.workspacePath.trim():k!=null&&k.workspaceId&&(_.workspaceId=k.workspaceId),k!=null&&k.resumeSessionId&&(_.resumeSessionId=k.resumeSessionId),(v=k==null?void 0:k.args)!=null&&v.trim()&&(_.cliArgs=k.args.trim().split(/\s+/).filter(Boolean)),(B=k==null?void 0:k.model)!=null&&B.trim()&&(_.initialModel=k.model.trim());const T=await e(h,"launch_cli",_),D=(T==null?void 0:T.result)||T,K=(D==null?void 0:D.sessionId)||(D==null?void 0:D.id);if(T!=null&&T.success&&K){m(null),i("done"),l(`${S} launched`),t(Jt(K));return}if(T!=null&&T.success){i("loading"),l(`${S} launch requested — waiting for session…`);return}m(null),i("error"),l((T==null?void 0:T.error)||(D==null?void 0:D.error)||`Could not launch ${y.toUpperCase()} workspace`)}catch(_){if(Gx(_)){i("loading"),l(`${S} launch requested — waiting for session…`);return}m(null),i("error"),l(_ instanceof Error?_.message:`Could not launch ${y.toUpperCase()} workspace`)}},[t,e]),p=o.useCallback(async(h,y)=>{try{const S=await e(h,"list_saved_sessions",{providerType:y,kind:"cli",limit:30}),k=(S==null?void 0:S.result)??S;return Array.isArray(k==null?void 0:k.sessions)?k.sessions:[]}catch(S){return console.error("Failed to list saved sessions on mobile:",S),[]}},[e]),j=o.useCallback(async(h,y)=>yn(e,h,y),[e]);o.useEffect(()=>{if(!d)return;const h=wi(d.workspacePath),y=r.find(k=>{var _,T,D,K;if(!k||k.type==="adhdev-daemon"||Vx(k.daemonId||k.id)!==d.machineId||(k.transport==="acp"?"acp":k.transport==="pty"?"cli":null)!==d.kind||String(k.agentType||k.type||"")!==d.providerType)return!1;const v=String(k.providerSessionId||"");if(d.resumeSessionId&&v)return v===d.resumeSessionId;if(h){const L=wi(k.workspace||k.runtimeWorkspaceLabel);return L?L===h:!1}return Number(k.lastUpdated||k._lastUpdate||k.timestamp||((K=(D=(T=(_=k.activeChat)==null?void 0:_.messages)==null?void 0:T.at)==null?void 0:D.call(T,-1))==null?void 0:K.timestamp)||0)>=d.startedAt-5e3});if(!y)return;const S=Cl({entrySessionId:y.sessionId,entryInstanceId:y.instanceId,entryRouteId:y.id,conversations:n});S&&(m(null),i("done"),l(`${d.providerType} launched`),t(Jt(S)))},[n,r,t,d]),o.useEffect(()=>{if(!d)return;const h=window.setTimeout(()=>{m(y=>!y||y.startedAt!==d.startedAt?y:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[d]);const b=o.useCallback(async(h,y)=>{if(y.kind==="ide"&&y.providerType){await f(h,y.providerType,{workspacePath:y.workspace||null});return}(y.kind==="cli"||y.kind==="acp")&&y.providerType&&await g(h,y.kind,y.providerType,{workspacePath:y.workspace||null,resumeSessionId:y.providerSessionId||null})},[f,g]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:f,handleAddWorkspace:x,handleMachineUpgrade:C,handleLaunchWorkspaceProvider:g,handleListSavedSessions:p,handleBrowseDirectory:j,handleOpenRecent:b}}function Yx({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:d,setMachineBackTarget:m}){const u=o.useCallback(b=>{i(b.tabKey),c("chat"),n(b)},[n,c,i]),f=o.useCallback(b=>{const h=e.find(y=>y.routeId===b.routeId&&y.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),x=o.useCallback(()=>{n(t),c("inbox")},[n,t,c]),C=o.useCallback((b,h="inbox")=>{l(b),a(),d("machines"),m(h),c("machine")},[a,m,c,d,l]),g=o.useCallback(b=>{const h=bs(b);h&&C(h,"chat")},[C]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),j=o.useCallback(b=>{d(b),c("inbox")},[c,d]);return{openConversation:u,openNativeConversation:f,backFromConversation:x,openMachine:C,openConversationMachine:g,backFromMachine:p,changeMachineSection:j}}function hs(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function Xx(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Jx({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:C,onOpenHistory:g,onOpenRemote:p,onStopCli:j,wsStatus:b,isConnected:h,onShowAllHiddenConversations:y,onHideConversation:S,onOpenNewSession:k,liveSessionInboxState:A,setCliViewModeOverrides:M}){const[w,v]=o.useState(()=>{var Z;return((Z=e[0])==null?void 0:Z.tabKey)||null}),[B,_]=o.useState(()=>e[0]?"chat":"inbox"),[T,D]=o.useState("chats"),[K,L]=o.useState(null),[N,I]=o.useState("inbox"),W=o.useRef([]),P=$s(),$="0.9.75",H=o.useMemo(()=>e.find(Z=>Z.tabKey===w)||e[0]||null,[e,w]),J=o.useMemo(()=>H?r.find(Z=>Z.id===H.routeId):void 0,[r,H]),he=o.useMemo(()=>!H||Ze(H)||!tt(H)?null:Ks(H),[H]),ie=o.useMemo(()=>r.filter(Z=>Z.type==="adhdev-daemon").sort(Va),[r]),te=o.useMemo(()=>ie.find(Z=>Z.id===K)||null,[ie,K]),be=xn({sendDaemonCommand:a,activeConv:H||void 0,setActionLogs:i,isStandalone:c}),we=qx({sendDaemonCommand:a,navigate:P,ides:r,conversations:e}),ge=o.useMemo(()=>e.map(Z=>{const De=B==="chat"&&(H==null?void 0:H.tabKey)===Z.tabKey,$e=fn(Z,A,{hideOpenTaskCompleteUnread:!0,isOpenConversation:De}),Fe=ls(Z),Ue=Fc(Z);return{conversation:Z,timestamp:Fe,preview:Ue,unread:$e.unread,requiresAction:$e.requiresAction,isWorking:$e.isWorking,inboxBucket:$e.inboxBucket}}),[e,A,B,H]),{markConversationRead:X}=zx({conversations:e,machineEntries:ie,items:ge,selectedConversation:H,selectedTabKey:w,screen:B,liveSessionInboxState:A,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:C,setSelectedTabKey:v,setScreen:_,setSelectedMachineId:L,setSection:D,setMachineBackTarget:I,resetMachineAction:we.resetMachineAction}),ce=Yx({conversations:e,selectedConversation:H,machineBackTarget:N,markConversationRead:X,resetMachineAction:we.resetMachineAction,setSelectedTabKey:v,setScreen:_,setSelectedMachineId:L,setSection:D,setMachineBackTarget:I}),ye=o.useMemo(()=>Ur(ge.filter(Z=>Z.requiresAction)),[ge]),ne=o.useMemo(()=>Ur(ge.filter(Z=>Z.unread&&!Z.requiresAction)),[ge]),de=o.useMemo(()=>Wx(ge.filter(Z=>!Z.unread&&!Z.requiresAction&&Z.isWorking),W.current),[ge]);o.useEffect(()=>{W.current=de.map(Z=>Z.conversation.tabKey)},[de]);const je=o.useMemo(()=>Ur(ge.filter(Z=>!Z.unread&&!Z.requiresAction&&!Z.isWorking)),[ge]),me=o.useMemo(()=>te?ge.filter(Z=>bs(Z.conversation)===te.id):[],[ge,te]),pe=o.useMemo(()=>Fx(te,r),[r,te]),ee=(te==null?void 0:te.version)||null,ue=!!te&&!!ee&&!0&&ee!==$,oe=o.useMemo(()=>(te==null?void 0:te.availableProviders)||[],[te]),q=o.useMemo(()=>oe.filter(Z=>hs(Z,"cli")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[oe]),V=o.useMemo(()=>oe.filter(Z=>hs(Z,"acp")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[oe]),le=o.useMemo(()=>Hx(ie,ge),[ge,ie]),ke=o.useCallback(async Z=>{te&&await we.handleOpenRecent(te.id,Z)},[we,te]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:B==="chat"&&H?s.jsx(Ix,{selectedConversation:H,isAcp:Ze(H),isStandalone:c,selectedIdeEntry:J,actionLogs:n,userName:l,isSendingChat:be.isSendingChat,sendFeedbackMessage:be.sendFeedbackMessage,isFocusingAgent:be.isFocusingAgent,handleModalButton:be.handleModalButton,handleRelaunch:be.handleRelaunch,onBack:ce.backFromConversation,onOpenNativeConversation:ce.openNativeConversation,onOpenMachine:ce.openConversationMachine,onOpenHistory:g,onOpenRemote:p,onStopCli:j,cliViewMode:he,onSetCliViewMode:async Z=>{await pl({conversation:H,mode:Z,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:M})},handleSendChat:be.handleSendChat,handleFocusAgent:be.handleFocusAgent}):B==="machine"&&te?s.jsx(Kx,{selectedMachineEntry:te,selectedMachineConversations:me,selectedMachineRecentLaunches:pe,cliProviders:q,acpProviders:V,selectedMachineNeedsUpgrade:ue,appVersion:$,machineAction:we.machineAction,isStandalone:c,section:T,showBottomNav:N==="inbox",onBack:ce.backFromMachine,onSectionChange:ce.changeMachineSection,onOpenConversation:ce.openConversation,onOpenRecent:ke,onOpenMachineDetails:()=>P(`/machines/${te.id}`),onMachineUpgrade:()=>we.handleMachineUpgrade(te.id),onLaunchDetectedIde:(Z,De)=>we.handleLaunchDetectedIde(te.id,Z,De),onAddWorkspace:(Z,De)=>we.handleAddWorkspace(te.id,Z,De),onBrowseDirectory:Z=>we.handleBrowseDirectory(te.id,Z),onLaunchWorkspaceProvider:(Z,De,$e)=>we.handleLaunchWorkspaceProvider(te.id,Z,De,$e),onListSavedSessions:Z=>we.handleListSavedSessions(te.id,Z)}):s.jsx(_x,{section:T,attentionItems:ye,unreadItems:ne,workingItems:de,completedItems:je,hiddenConversations:t,machineCards:le,getAvatarText:Xx,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ce.openConversation,onShowAllHidden:y,onHideConversation:S,onOpenNewSession:k,onOpenMachine:ce.openMachine,onOpenSettings:()=>P("/settings"),onSectionChange:D,wsStatus:b,isConnected:h,isStandalone:c})})}function qn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Qx({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,d]=o.useState(!1),[m,u]=o.useState(null),f=o.useCallback(()=>{c.current=0,d(!1),u(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const x=o.useCallback(j=>{j.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,d(!0))},[]),C=o.useCallback(j=>{if(!j.dataTransfer.types.includes("text/tab-key"))return;if(j.preventDefault(),!qn(t,r)){u("merge");return}const b=j.currentTarget.getBoundingClientRect(),h=j.clientX-b.left,y=b.width/3;h<y?u("split-left"):h>y*2?u("split-right"):u("merge")},[t,r]),g=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,d(!1),u(null))},[]),p=o.useCallback(j=>{c.current=0,d(!1);const b=j.dataTransfer.getData("text/tab-key"),h=b?e.some(S=>S.tabKey===b):!1,y=m;if(u(null),i(),!!b){if(j.preventDefault(),y==="split-left"&&qn(t,r)){r==null||r(b,"split-left");return}if(y==="split-right"&&qn(t,r)){r==null||r(b,"split-right");return}if(h){a(b);return}n==null||n(b)}},[e,m,t,r,n,a,i]);return{dragOver:l,dropAction:m,resetDragState:f,handleDragEnter:x,handleDragOver:C,handleDragLeave:g,handleDrop:p}}function Zx(e,t){const r=new Set(t.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=t.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function eb({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(t??null),[l,d]=o.useState(r??[]),[m,u]=o.useState(null),f=o.useRef(null),x=o.useRef(null),C=o.useRef(n),g=o.useRef(a);o.useEffect(()=>{C.current=n},[n]),o.useEffect(()=>{g.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{d(M=>{const w=Zx(M,e);return w.length===M.length&&w.every((v,B)=>v===M[B])?M:w})},[e]);const p=o.useMemo(()=>{const M=m??l;if(M.length===0)return e;const w=new Map(M.map((v,B)=>[v,B]));return[...e].sort((v,B)=>{const _=w.get(v.tabKey)??999,T=w.get(B.tabKey)??999;return _-T})},[e,m,l]);o.useEffect(()=>{var w,v;if(p.length===0){i!==null&&(c(null),(w=C.current)==null||w.call(C,null));return}if(i&&p.some(B=>B.tabKey===i))return;const M=p[0].tabKey;M!==i&&(c(M),(v=C.current)==null||v.call(C,M))},[p,i]);const j=o.useMemo(()=>p.find(M=>M.tabKey===i),[p,i]),b=o.useCallback(M=>{var w;c(M),(w=C.current)==null||w.call(C,M)},[]),h=o.useCallback((M,w,v)=>{d(B=>{var K;const _=B.filter(L=>L!==M),T=_.indexOf(w);if(T<0)return B;const D=v==="left"?T:T+1;return _.splice(D,0,M),(K=g.current)==null||K.call(g,_),_}),u(null)},[]),y=o.useCallback((M,w,v)=>{const _=(l.length>0?l:e.map(K=>K.tabKey)).filter(K=>K!==M),T=_.indexOf(w);if(T<0)return;const D=v==="left"?T:T+1;_.splice(D,0,M),f.current=_,u(_)},[l,e]),S=o.useCallback(()=>{var w;const M=f.current;M&&(d(M),(w=g.current)==null||w.call(g,M))},[]),k=o.useCallback(()=>{f.current=null,u(null)},[]),A=o.useCallback(M=>{d(w=>{var B;const v=w.filter(_=>_!==M);return v.push(M),(B=g.current)==null||B.call(g,v),v})},[]);return{activeTabId:i,activeConv:j,sortedConversations:p,previewOrderRef:f,draggingTabRef:x,selectTab:b,handleTabReorder:h,updatePreviewOrder:y,commitPreviewOrder:S,clearPreviewOrder:k,moveTabToEnd:A,setDraggingTabKey:M=>{x.current=M}}}function tb({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 yo({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:i}){if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!r&&!n,l=n&&!!i,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?Vc:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),l&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:i,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:$t,"aria-label":$t,children:[s.jsx(ac,{size:14}),s.jsx("span",{children:$t})]})}),c&&s.jsx(Ml,{}),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 Ll="adhdev-tab-shortcuts";function _l(){try{return JSON.parse(localStorage.getItem(Ll)||"{}")}catch{return{}}}function Pl({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>_l()),[l,d]=o.useState(null),m=o.useCallback(f=>{const x=[];return f.metaKey&&x.push(a?"⌘":"Meta"),f.ctrlKey&&x.push("Ctrl"),f.altKey&&x.push(a?"⌥":"Alt"),f.shiftKey&&x.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(x.push(f.key.length===1?f.key.toUpperCase():f.key),x.join("+"))},[a]),u=o.useCallback(f=>{c(f);try{localStorage.setItem(Ll,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){d(null);return}const C=m(x);if(!C)return;const g={...i};for(const[p,j]of Object.entries(g))j===C&&delete g[p];g[l]=C,u(g),d(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,i,u,m]),o.useEffect(()=>{if(!e)return;const f=x=>{if(!(!x.ctrlKey&&!x.metaKey&&!x.altKey)){for(const[C,g]of Object.entries(i))if(t.includes(C)&&m(x)===g){x.preventDefault(),r(),n(C);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,i,t,r,n,m]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const Yn=e=>{e.preventDefault()},sb=o.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:f,onReorderTab:x,onCommitPreviewOrder:C,onClearPreviewOrder:g,onDragStateReset:p,onDragTabKeyChange:j,onReceiveTab:b,onOpenContextMenu:h,longPressTimer:y,isGroupActive:S}){const k=Bs(t),A=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",M=k.isReconnecting,w=o.useCallback(I=>{l.current=t.tabKey,j(t.tabKey),I.dataTransfer.setData("text/tab-key",t.tabKey),I.dataTransfer.effectAllowed="move"},[t.tabKey,l,j]),v=o.useCallback(()=>{l.current=null,j(null),C(),g(),p()},[l,j,C,g,p]),B=o.useCallback(I=>{const W=l.current;if(!(!W||W===t.tabKey)&&I.dataTransfer.types.includes("text/tab-key")){I.preventDefault(),I.stopPropagation();const P=I.currentTarget.getBoundingClientRect(),$=I.clientX<P.left+P.width/2?"left":"right";f(W,t.tabKey,$)}},[t.tabKey,l,f]),_=o.useCallback(I=>{I.preventDefault(),I.stopPropagation();const W=I.dataTransfer.getData("text/tab-key");if(W&&W!==t.tabKey){const P=I.currentTarget.getBoundingClientRect(),$=I.clientX<P.left+P.width/2?"left":"right";c.includes(W)?x(W,t.tabKey,$):b&&b(W)}g()},[t.tabKey,c,x,b,g]),T=o.useCallback(I=>{I.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),D=o.useCallback(I=>{I.preventDefault(),h(I.clientX,I.clientY,t.tabKey)},[t.tabKey,h]),K=o.useCallback(I=>{const W=I.touches[0];y.current=setTimeout(()=>{h(W.clientX,W.clientY,t.tabKey)},600)},[t.tabKey,y,h]),L=o.useCallback(()=>{y.current&&clearTimeout(y.current)},[y]),N=["adhdev-dockview-tab",A,r&&"is-active",S&&"is-group-active",M&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:N,draggable:!0,onDragStart:w,onDragEnd:v,onDragOver:B,onDrop:_,onClick:T,onContextMenu:D,onTouchStart:K,onTouchEnd:L,onTouchMove:L,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:k.isGenerating?s.jsx("div",{className:"tab-spinner"}):k.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):M?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.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:lt(t),children:lt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[M?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:ns(t)}):k.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[ns(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:ns(t)}),s.jsx(_s,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),i&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function rb({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:C,onReceiveTab:g,onHideTab:p,isGroupActive:j,allowTabShortcuts:b=!0}){const[h,y]=o.useState(null),S=o.useRef(null),k=o.useRef(null),A=o.useMemo(()=>e.map(D=>D.tabKey),[e]);ur("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:M,tabShortcuts:w,shortcutListening:v,setShortcutListening:B,saveShortcuts:_}=Pl({enabled:b,sortedTabKeys:e.map(D=>D.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const D=K=>{const L=document.querySelector("[data-pane-context-menu]");L&&L.contains(K.target)||y(null)};return window.addEventListener("mousedown",D,!0),()=>window.removeEventListener("mousedown",D,!0)},[h]),o.useEffect(()=>{const D=k.current;if(!D)return;const K=L=>{Math.abs(L.deltaY)<=Math.abs(L.deltaX)||(L.preventDefault(),D.scrollLeft+=L.deltaY)};return D.addEventListener("wheel",K,{passive:!1}),()=>D.removeEventListener("wheel",K)},[]);const T=o.useCallback((D,K,L)=>{y({x:D,y:K,tabKey:L})},[]);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:k,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(D=>s.jsx(sb,{conv:D,isActive:t===D.tabKey,isDraggedTab:a.current===D.tabKey,isTaskCompleteUnread:n.has(D.tabKey),shortcut:b?w[D.tabKey]:void 0,conversationKeys:A,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:C,onReceiveTab:g,onOpenContextMenu:T,longPressTimer:S,isGroupActive:j},D.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),h&&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:h.x,top:h.y},children:[b&&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:Yn,onClick:D=>{D.stopPropagation(),B(h.tabKey),y(null)},children:["⌨ ",w[h.tabKey]?`Change shortcut (${w[h.tabKey]})`:"Set shortcut"]}),w[h.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:Yn,onClick:()=>{const D={...w};delete D[h.tabKey],_(D),y(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[b&&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:Yn,onClick:()=>{p(h.tabKey),y(null)},children:"🚫 Hide from Dashboard"})]})]}),b&&v&&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:D=>D.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. ",M?"⌘+1":"Ctrl+1",", ",M?"⌥+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 nb({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:d,groupIndex:m,onFocus:u,isSplitMode:f,numGroups:x,onMoveTab:C,onReceiveTab:g,style:p,onActiveTabChange:j,initialActiveTabId:b,initialTabOrder:h,onTabOrderChange:y,onHideTab:S,isFocused:k,allowTabShortcuts:A=!0,onOpenNewSession:M,liveSessionInboxState:w}){const{sendCommand:v}=bt(),B=o.useRef(null),{activeTabId:_,activeConv:T,sortedConversations:D,draggingTabRef:K,selectTab:L,handleTabReorder:N,updatePreviewOrder:I,commitPreviewOrder:W,clearPreviewOrder:P,moveTabToEnd:$,setDraggingTabKey:H}=eb({conversations:e,initialActiveTabId:b,initialTabOrder:h,onActiveTabChange:j,onTabOrderChange:y}),J=xn({sendDaemonCommand:a,activeConv:T,setActionLogs:i,isStandalone:c}),{dragOver:he,dropAction:ie,resetDragState:te,handleDragEnter:be,handleDragOver:we,handleDragLeave:ge,handleDrop:X}=Qx({conversations:e,numGroups:x,onMoveTab:C,onReceiveTab:g,onOwnTabDrop:$,onClearPreviewOrder:P}),ce=T&&!Ze(T)&&Ks(T)==="terminal",ye=o.useMemo(()=>T?t.find(me=>me.id===T.routeId):void 0,[t,T]),ne=o.useMemo(()=>T?n.filter(me=>me.routeId===T.tabKey):[],[n,T]),de=o.useMemo(()=>new Set(D.filter(me=>Qu(me,w,{isOpenConversation:me.tabKey===_})).map(me=>me.tabKey)),[_,w,D]);ur("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:_,dragOver:he});const je=o.useCallback(me=>{me.streamSource==="agent-stream"&&me.agentType&&v(me.routeId,Mc(),{agentType:me.agentType,...me.sessionId&&{targetSessionId:me.sessionId}}).catch(()=>{})},[v]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...p,outline:he?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(rb,{conversations:D,activeTabId:_,groupIndex:m,numGroups:x,unreadTabKeys:de,draggingTabRef:K,onFocus:u,onSelectTab:L,onConversationActivated:je,onPreviewReorder:I,onReorderTab:N,onCommitPreviewOrder:W,onClearPreviewOrder:P,onDragStateReset:te,onDragTabKeyChange:H,onMoveTab:C,onReceiveTab:g,onHideTab:S,isGroupActive:k??!1,allowTabShortcuts:A}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:be,onDragOver:we,onDragLeave:ge,onDrop:X,children:[he&&s.jsx(tb,{dropAction:ie,canSplit:!!(x<4&&C)}),T?s.jsx(bo,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!ce,ideEntry:ye,terminalRef:B,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:ne,userName:d,isInputActive:!f||!!k}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(yo,{conversationsCount:e.length,isSplitMode:f,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:M})})]})]})}function ab({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:f,userName:x,focusedGroup:C,focusGroup:g,moveTabToGroup:p,splitTabRelative:j,closeGroup:b,handleResizeStart:h,groupActiveTabIds:y,setGroupActiveTab:S,groupTabOrders:k,setGroupTabOrder:A,toggleHiddenTab:M,onOpenNewSession:w,allowTabShortcuts:v=!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 D=t&&n.length===r?`${n[T]}%`:void 0;return s.jsxs(Ct.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:K=>h(T-1,K),onDoubleClick:()=>b(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(nb,{style:t?{flexBasis:D??`${100/r}%`,flexGrow:D?0:1,flexShrink:D?0:1}:void 0,conversations:_,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:f,userName:x,groupIndex:T,isFocused:t&&C===T,onFocus:()=>g(T),isSplitMode:t,numGroups:r,onMoveTab:(K,L)=>{L==="left"&&T>0?p(K,T-1):L==="right"&&T<r-1?p(K,T+1):L==="split-left"&&r<4?j(K,T,"left"):L==="split-right"&&r<4&&j(K,T,"right")},onReceiveTab:K=>p(K,T),onActiveTabChange:K=>S(T,K),initialActiveTabId:y[T],initialTabOrder:k[T],onTabOrderChange:K=>A(T,K),onHideTab:M,onOpenNewSession:w,allowTabShortcuts:v,liveSessionInboxState:B})]},T)})})}function Dl({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?ut.onScreenshot("ide-page",(u,f)=>{if(u!==e)return;const x=new FileReader;x.onload=()=>i(x.result),x.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var u;return e?((u=ut.onStatus)==null?void 0:u.call(ut,(f,x)=>{f===e&&x!=null&&x.screenshotUsage&&l(x.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,t]),o.useEffect(()=>{const m=e?ut.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=o.useCallback(async(m,u)=>{const f=e?ut.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 El="adhdev-dashboard-action-shortcuts",ob=1200,ib=[["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 cb(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function nt(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 $l(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:nt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:nt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:nt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:nt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:nt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:nt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:nt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:nt("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:nt("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:nt("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:nt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:nt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:nt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:nt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:nt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:nt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:nt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:nt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:nt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:nt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:nt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:nt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:nt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:nt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:nt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:nt("toggleCliView",e)}]}function Ia(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function cn(e){const t=Object.fromEntries($l(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(El)||"{}"),n={...t,...r};for(const[a,i]of ib)n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function Bl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function lb({enabled:e=!0,onTrigger:t}){const r=cb(),[n,a]=o.useState(()=>cn(r)),[i,c]=o.useState(null),[l,d]=o.useState([]),m=o.useRef({parts:[],timer:null}),u=o.useCallback(p=>{const j=[];return p.metaKey&&j.push(r?"⌘":"Meta"),p.ctrlKey&&j.push("Ctrl"),p.altKey&&j.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&j.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(j.push(Bl(p.key)),j.join("+"))},[r]),f=o.useCallback(p=>{a(p);try{localStorage.setItem(El,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=cn(r),j=Object.entries(n),b=Object.entries(p);j.length===b.length&&j.every(([h,y])=>p[h]===y)||f(p)},[n,r,f]);const x=o.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),C=o.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},ob))},[]);o.useEffect(()=>{if(!i)return;const p=j=>{if(j.preventDefault(),j.stopPropagation(),j.key==="Escape"){c(null),d([]);return}const b=u(j);if(!b)return;const y=!(j.metaKey||j.ctrlKey||j.altKey)&&/^[A-Z0-9]$/.test(b);if(l.length===0&&y){d([b]);return}const k=[...l,b].slice(0,2).join(" "),A={...n};for(const[M,w]of Object.entries(A))w===k&&delete A[M];A[i]=k,f(A),c(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,u,f,i,l]),o.useEffect(()=>{if(!e||i)return;const p=j=>{if(j.defaultPrevented)return;const b=u(j);if(!b)return;const h=j.metaKey||j.ctrlKey||j.altKey;if(Ia(j.target))return;const y=m.current.parts,S=h?[b]:[...y.slice(-1),b].slice(-2),k=S.join(" "),A=S[S.length-1],M=Object.entries(n).filter(([,T])=>!!T),w=M.find(([,T])=>T===k);if(w){j.preventDefault(),x(),t(w[0]);return}if(M.some(([,T])=>T.startsWith(`${k} `))){j.preventDefault(),m.current.parts=S,C();return}const B=M.find(([,T])=>T===A);if(B){j.preventDefault(),x(),t(B[0]);return}if(M.some(([,T])=>T.startsWith(`${A} `))){j.preventDefault(),m.current.parts=[A],C();return}x()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,C,e,u,t,x,i]),o.useEffect(()=>()=>x(),[x]);const g=o.useMemo(()=>$l(r),[r]);return{isMac:r,actionDefinitions:g,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:f}}function db({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 Kl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function ji({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!Kl(n):!0}function ub({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:Kl(r)}const Wl=1e3,mb=4;function ki(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Si(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function fb({detachDelayMs:e=Wl,stillnessThresholdPx:t=mb,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let i=null,c=null,l=null,d=null,m=null,u=!1;const f=()=>{m!=null&&(a(m),m=null)},x=()=>{f(),l=null},C=()=>{f(),i=null,c=null,l=null,d=null,u=!1},g=()=>{!i||!l||!d||u||m!=null||(m=n(()=>{m=null,!(!i||!l||!d||u)&&ki(d,c)&&(Si(l,d,t)||(u=!0,r({panelId:i,clientX:d.clientX,clientY:d.clientY})))},e))},p=b=>{if(!(!i||u)){if(!ki(b,c)){d={clientX:b.clientX,clientY:b.clientY},x();return}(!l||Si(l,b,t))&&(f(),l={clientX:b.clientX,clientY:b.clientY}),d={clientX:b.clientX,clientY:b.clientY},g()}},j=b=>{!i||u||(b&&(d={clientX:b.clientX,clientY:b.clientY}),x())};return{startDrag:b=>{f(),i=b.panelId,c=b.selfPanelBounds??null,l=null,d={clientX:b.clientX,clientY:b.clientY},u=!1},markSelfPanel:p,markNonSelfPanel:j,markNoDropTarget:j,markDockTarget:j,endDrag:C,isDragging:()=>i!=null,hasDetached:()=>u,dispose:C}}function pb(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Dr(e){return e.isActive}function Ni(e){return e.isVisible}const Ol=o.createContext(null);function wn(){const e=o.useContext(Ol);if(!e)throw new Error("DashboardDockviewContext missing");return e}function zr(e){return lt(e)||e.tabKey}function hb(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function Ci(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function xb(e){e.preventDefault()}function Xn(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 Jn(e,t){e.classList.remove(ua.className,ma.className),e.classList.add(t==="light"?ua.className:ma.className)}function Ti(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 bb(e){const[,t]=o.useState(0);o.useEffect(()=>{const r=()=>t(a=>a+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const a of n)a.dispose()}},[e.api,e.containerApi])}function gb(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:zr(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 Mi(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])Lt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==zr(n)&&a.api.setTitle(zr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:zr(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function Ai(e,t,r){var d,m;const n=r?hb(r):null;for(const u of[...e.panels])Lt(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 i=e.getPanel(n),c=zc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((m=e.panels.find(u=>!Lt(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 yb({params:e,api:t}){var C;const r=wn(),n=o.useRef(null),[a,i]=o.useState(()=>Dr(t)),[c,l]=o.useState(()=>Ni(t)),d=r.conversationsByTabKey.get(e.tabKey),m=xn({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(Dr(t)),l(Ni(t));const g=[t.onDidActiveChange(p=>i(p.isActive)),t.onDidActiveGroupChange(p=>{if(!Dr(t)&&!p.isActive){i(!1);return}i(Dr(t))}),t.onDidVisibilityChange(p=>l(p.isVisible))];return()=>{for(const p of g)p.dispose()}},[t]);const u=o.useMemo(()=>d?r.ides.find(g=>g.id===d.routeId):void 0,[r.ides,d]),f=o.useMemo(()=>d?r.actionLogs.filter(g=>g.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(yo,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const x=!Ze(d)&&Ks(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(bo,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:x,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:((C=r.scrollToBottomRequest)==null?void 0:C.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:c})})}function vb({params:e}){var d;const t=wn(),r=o.useMemo(()=>Dt([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=Dl({doId:a,targetSessionId:r?Tc(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(uc,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:l})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function wb(){const e=wn();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(yo,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function jb(e){var C,g;bb(e);const t=wn(),r=o.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),j=((C=e.api.group.activePanel)==null?void 0:C.id)===e.api.id,b=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${j?" is-active":""}${b?" 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=((g=e.api.group.activePanel)==null?void 0:g.id)===e.api.id,i=e.api.isGroupActive,c=fn(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,d=c.isConnecting,m=c.isGenerating,u=c.isWaiting,f=c.unread,x=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:lt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var j;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((j=p.target)==null?void 0:j.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:lt(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ns(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ns(n)}):s.jsx("span",{children:ns(n)})})]}),x&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:x,children:x})]})}function kb({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:f,registerActionHandlers:x,onActiveTabChange:C,onOpenNewSession:g,onRequestScrollToBottom:p,requestedActiveTabKey:j,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:h,scrollToBottomRequest:y,liveSessionInboxState:S,layoutProfile:k}){var Je,Ge,rt;const{theme:A}=co(),{sendCommand:M}=bt(),w=o.useRef(null),v=o.useRef(null),B=o.useRef(null),_=o.useRef(!1),T=o.useRef(!1),D=o.useRef(!1),K=o.useRef(null),L=o.useRef([]),[N,I]=o.useState(null),[W,P]=o.useState(0),$=o.useRef(typeof window>"u"?{}:Hh(k)),H=o.useMemo(()=>new Map(e.map(F=>[F.tabKey,F])),[e]),J=o.useMemo(()=>{const F=w.current;return F?F.groups.some(U=>{try{const G=U.model.location.type;return G!=="floating"&&G!=="popout"?!1:U.panels.some(se=>H.has(se.id))}catch{return!1}}):!1},[H,W,e]),he=o.useCallback(()=>{var F;(F=w.current)==null||F.focus()},[]),ie=o.useCallback((F,U)=>{p==null||p(F,U)},[p]),te=o.useCallback(F=>{const U=document,G=F.document;for(const re of U.querySelectorAll('link[rel="stylesheet"]')){const ve=G.createElement("link");ve.rel="stylesheet",ve.href=re.href,re.crossOrigin&&(ve.crossOrigin=re.crossOrigin),G.head.appendChild(ve)}for(const re of U.querySelectorAll("style")){const ve=G.createElement("style");ve.textContent=re.textContent,G.head.appendChild(ve)}const se=[];for(const re of U.styleSheets)try{for(const ve of re.cssRules)ve instanceof CSSStyleRule&&(ve.selectorText===":root"||ve.selectorText==="html")&&se.push(ve.cssText)}catch{}if(se.length>0){const re=G.createElement("style");re.textContent=se.join(`
52
- `),G.head.appendChild(re)}const E=U.documentElement.getAttribute("data-theme");E&&G.documentElement.setAttribute("data-theme",E),G.documentElement.style.colorScheme=E==="light"?"light":"dark",G.body.className=U.body.className;const Y=U.documentElement.getAttribute("style");Y&&G.documentElement.setAttribute("style",Y);const Q=G.getElementById("dv-popout-window");Q instanceof HTMLElement&&(Q.classList.add("adhdev-dockview"),Jn(Q,A))},[A]),be=o.useCallback(()=>{var U;const F=w.current;if(F)for(const G of F.groups)try{const se=(U=G.element)==null?void 0:U.ownerDocument;if(!se||se===document)continue;const E=se.getElementById("dv-popout-window");E instanceof HTMLElement&&(E.classList.add("adhdev-dockview"),Jn(E,A));const Y=document.documentElement.getAttribute("data-theme");Y&&se.documentElement.setAttribute("data-theme",Y),se.documentElement.style.colorScheme=Y==="light"?"light":"dark",se.body.className=document.body.className;const Q=document.documentElement.getAttribute("style");Q?se.documentElement.setAttribute("style",Q):se.documentElement.removeAttribute("style")}catch{}},[A]),we=o.useCallback(F=>{const U=w.current;if(!U)return;const G=U.getPanel(F);G&&U.addPopoutGroup(G,{popoutUrl:"/popout.html",onDidOpen:({window:se})=>{te(se),pe();const E=H.get(F);se.document.title=E?`${lt(E)} — ADHDev`:"ADHDev — Popout"}})},[H,te]),ge=o.useCallback(F=>{const U=w.current,G=U==null?void 0:U.getPanel(F);if(!U||!G)return;const se=U.groups.filter(E=>{var Y;try{return((Y=E.element)==null?void 0:Y.ownerDocument)===document}catch{return!0}});se.length>0?G.api.moveTo({group:se[0],position:"center"}):G.api.moveTo({position:"center"}),G.api.setActive()},[]),X=o.useCallback(F=>{var se;const U=w.current;if(!U)return!1;const G=U.getPanel(F);if(!G)return!1;try{return((se=G.group.element)==null?void 0:se.ownerDocument)!==document}catch{return!1}},[]),ce=o.useCallback(F=>{X(F)&&ge(F),u(F)},[X,ge,u]),ye=o.useCallback(F=>{const U=w.current,G=U==null?void 0:U.getPanel(F);!U||!G||U.addFloatingGroup(G,{width:600,height:500})},[]),ne=o.useCallback(F=>{var G;const U=(G=w.current)==null?void 0:G.getPanel(F);if(!U)return!1;try{return U.group.model.location.type==="floating"}catch{return!1}},[]),de=o.useCallback(()=>{var U,G;const F=(G=(U=w.current)==null?void 0:U.activePanel)==null?void 0:G.id;return!F||Lt(F)?null:H.has(F)?F:null},[H]),je=o.useCallback(F=>{const U=w.current,G=U==null?void 0:U.getPanel(F);if(!U||!G)return;const se=U.groups.filter(E=>{try{return E.model.location.type==="grid"}catch{return!0}});se.length>0?G.api.moveTo({group:se[0],position:"center"}):G.api.moveTo({position:"center"}),G.api.setActive()},[]),me=o.useCallback(()=>{var Y;const F=w.current;if(!F)return;const G=F.groups.filter(Q=>{var re;try{return((re=Q.element)==null?void 0:re.ownerDocument)===document&&Q.model.location.type==="grid"}catch{return!1}})[0]||null,se=[...F.panels];for(const Q of se){const re=(Y=Q.group.element)==null?void 0:Y.ownerDocument,ve=Q.group.model.location.type;re===document&&ve==="grid"||(G&&G.id!==Q.group.id?Q.api.moveTo({group:G,position:"center"}):Q.api.moveTo({position:"center"}))}const E=F.activePanel;E&&(E.group.model.openPanel(E),E.api.setActive()),Xn(document)},[]),pe=o.useCallback(()=>{var U,G;const F=w.current;if(F)for(const se of F.groups){const E=(U=se.element)==null?void 0:U.ownerDocument;if(!E||E===document)continue;const Y=E.getElementById("dv-popout-window");if(!(Y instanceof HTMLElement))continue;let Q=null,re=E.title||"ADHDev",ve="Popout workspace";const Ie=se.activePanel;if(Ie)if(Q=Ie.id,Lt(Ie.id)){const Ae=((G=Ie.params)==null?void 0:G.routeId)||Ie.id.slice(7),qe=Dt([...H.values()],Ae);re=zc(qe),ve=qe!=null&&qe.machineName?`Remote view · ${qe.machineName}`:"Remote view"}else{const Ae=H.get(Ie.id);re=Ae?lt(Ae):Ie.title||Ie.id,ve=Ae?ns(Ae):"Dockview panel"}E.title=`${re} — ADHDev`;const Le=Array.from(E.querySelectorAll("#adhdev-popout-header"));for(const Ae of Le)Ae.remove();const Se=E.createElement("div");Se.id="adhdev-popout-header",E.body.appendChild(Se),Se.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(";")),Se.innerHTML=`
51
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:v,onCancel:()=>u(null)})]})}const th=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function sh(){const{preference:e,setPreference:t}=lo();return s.jsx("div",{className:"flex gap-2",children:th.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 rh(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 nh(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Kn(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function li(e){const{r:t,g:r,b:n}=nh(e);return .2126*Kn(t)+.7152*Kn(r)+.0722*Kn(n)}function di(e,t){const r=li(e),n=li(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function ol(e){const t=rh(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return di(t,r)>=di(t,n)?r:n}const Ca={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},Ta={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},ah=[{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"}}}],il="adhdev-chat-theme",cl="adhdev-chat-theme-custom";function Fr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(il)||"ember"}catch{return"ember"}}function Pt(e){try{const t=localStorage.getItem(cl);if(t){const r=JSON.parse(t);return{...e==="dark"?Ca:Ta,...r[e]}}}catch{}return e==="dark"?Ca:Ta}function Ar(e,t){try{localStorage.setItem(cl,JSON.stringify({dark:e,light:t}))}catch{}}function At(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 cn(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 oh={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function rr(e,t){var a;const r=(a=oh[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",cn(r,24)),n.style.setProperty("--accent-on-primary",ol(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${cn(r,18)})`),n.style.setProperty("--border-accent",At(r,.35)),n.style.setProperty("--nav-active-bg",At(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${At(r,.06)}`)}function is(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",At(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",At(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",At(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",At(e.borderSubtle,.5)),t.style.setProperty("--border-default",At(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",cn(e.accentColor,30)),t.style.setProperty("--accent-on-primary",ol(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${cn(e.accentColor,40)})`),t.style.setProperty("--border-accent",At(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",At(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${At(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 ${At(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 uo(){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 ih(e){try{localStorage.setItem(il,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=cs()?"dark":"light";is(Pt(t))}else uo(),rr(e,cs()?"dark":"light")}function ch(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Fr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=cs()?"dark":"light";is(Pt(t))}else uo(),rr(e,cs()?"dark":"light")}function cs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function jt({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 zs({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 lh({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=o.useState(()=>Pt(r));o.useEffect(()=>{a(Pt(r))},[r]);const i=o.useCallback((c,l)=>{a(d=>{const m={...d,[c]:l},f=Pt(r==="dark"?"light":"dark");return r==="dark"?Ar(m,f):Ar(f,m),is(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(zs,{title:"App Background",children:[s.jsx(jt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(jt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(jt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(zs,{title:"App Text",children:[s.jsx(jt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(jt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(jt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(zs,{title:"Borders & Accent",children:[s.jsx(jt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(jt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(jt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(zs,{title:"Chat Bubbles",children:[s.jsx(jt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(jt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(jt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(jt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(zs,{title:"Chat Layout",children:[s.jsx(jt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(jt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(jt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?Ca:Ta,d=Pt(e?"light":"dark");e?Ar(c,d):Ar(d,c),a(c),is(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 dh(){const[e,t]=o.useState(Fr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Pt("dark"));o.useEffect(()=>{n(cs());const d=new MutationObserver(()=>{const f=cs();n(f);const x=Fr();x==="custom"?is(Pt(f?"dark":"light")):rr(x,f?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const f=cs();n(f);const x=Fr();x==="custom"?is(Pt(f?"dark":"light")):rr(x,f?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?is(Pt(r?"dark":"light")):(uo(),rr(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Pt(r?"dark":"light"))},[r]);const c=d=>{t(d),ih(d)},l=[...ah,{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(lh,{dark:r,onColorsChange:d=>i(d)})]})}const mo="adhdev_mobileDashboardMode_v1",Ma="adhdev:mobile-dashboard-mode-change";function fo(){try{return localStorage.getItem(mo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function uh(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??fo())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==mo||t()};return window.addEventListener(Ma,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Ma,r),window.removeEventListener("storage",n)}}function mh(e){try{localStorage.setItem(mo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ma,{detail:e}))}function fh(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(fo()==="chat")},[]),s.jsx(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ut,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{t(r),mh(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Wn=new Map,ui=new Map;function ph(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 hh(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 ll(){const{sendCommand:e}=gt(),{injectEntries:t,getIdes:r}=or();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??xf,c=ui.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=Wn.get(n);if(l)return l;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=ph(m);if(!u)return;const f=r().find(C=>C.id===n),x=hh(f,n,u.machine,u.timestamp||Date.now());t([x]),ui.set(n,Date.now())})().finally(()=>{Wn.delete(n)});return Wn.set(n,d),d},[r,t,e])}function xh(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 bh(e,t){const{sendData:r}=gt(),{injectEntries:n,getIdes:a}=or(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(d=>Ht.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(C=>C.id===d),x=xh(f,d,u);n([x])}));return()=>{l.forEach(d=>d())}},[i,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function gh(e,t){const{sendData:r}=gt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(t!=null&&t.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const d=Ht.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)},vf):c(!1),()=>{l&&clearTimeout(l),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:a}}function yh(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function dl(e){const{sendData:t}=gt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=yh(e);if(!a||!e.sessionId||!t){n({});return}const i=Ht.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}),Ms.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return i.initialSendAccepted||n({}),()=>{i()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const ul="adhdev_hiddenTabs";function vh(){try{const e=localStorage.getItem(ul);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function gs(e){try{localStorage.setItem(ul,JSON.stringify([...e]))}catch{}}function On(e){return eo(e)}function po(e,t){return Ts(t).some(r=>e.has(r))}function wh(){const[e,t]=o.useState(vh),r=o.useCallback(m=>{const u=On(m);t(f=>{const x=new Set(f);return x.has(u)?x.delete(u):x.add(u),gs(x),x})},[]),n=o.useCallback(m=>{const u=On(m);t(f=>{if(f.has(u))return f;const x=new Set(f);return x.add(u),gs(x),x})},[]),a=o.useCallback(m=>{const u=On(m);t(f=>{if(!f.has(u))return f;const x=new Set(f);return x.delete(u),gs(x),x})},[]),i=o.useCallback(()=>{t(m=>{if(m.size===0)return m;const u=new Set;return gs(u),u})},[]),c=o.useCallback((m,u)=>{t(f=>{const x=new Set(f);for(const C of u)x.add(C);return gs(x),x})},[]),l=o.useCallback((m,u)=>{t(f=>{const x=new Set(f);for(const C of u)x.delete(C);return gs(x),x})},[]),d=o.useCallback(m=>po(e,m),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:d}}function ml(e){return e instanceof Error?e.message:String(e||"")}function fl(e){const t=ml(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 pl(e){const t=ml(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function hl({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!tt(e)||Ze(e))return;const i=Ks(e);if(i===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(bs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Kt(e),mode:t})}catch(l){const d=pl(l);c&&!d&&a(m=>{const u={...m};return i===xl(r,c)?delete u[c]:u[c]=i,u}),fl(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 mi(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 jh(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let r=!1;const n=e.map(a=>{const i=mi(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>mi(d,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function xl(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 kh(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))xl(t,a)===i&&(delete n[a],r=!0);return r?n:e}function Sh({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{vc()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:zc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Nm(a),o.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]),o.useEffect(()=>{const i=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(i)},[n]),null}function fi(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 ls(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=fi(t==null?void 0:t.receivedAt)||fi(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function Aa(e,t=0){return ls(e)||e.lastUpdated||t||0}function bl(e){return ls(e)||e.lastUpdated||0}function gl(e,t,r=bl){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(t.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(t.displaySecondary);return c!==0?c:e.tabKey.localeCompare(t.tabKey)}function Ia(e){var r;const t=bt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Nh(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Ia(e)&&!e.title.trim()}function Ch(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(Ia(r))-Number(Ia(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:gl(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"),i=Ch(a);return n?i&&Nh(n)?i:n:i||r[0]||null}function Th(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const i=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function Fn(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 Mh(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 pi(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Mh(As(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 Ah(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||""),pi(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||""),pi(r.activeChat)].join(":"))].join("|")}function Ih(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 Rh(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const i of Ts({routeId:n.routeId}))r.set(i,a);for(const i of Ts({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of Ts({tabKey:n.tabKey}))r.set(i,n)}return r}function Lh(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function _h(e){const t=Lh(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=As(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Ph({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>Th(e),[e]),i=o.useMemo(()=>Qc(e),[e]),c=o.useRef([]),l=o.useRef([]),d=o.useRef([]),m=o.useRef(new Map),u=o.useRef(new Map),f=o.useMemo(()=>{const S=new Map,j=[];for(const v of a){const{connectionState:B="new",machineName:_}=Zc(v,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),T=Ah(v),D=m.current.get(v.id);if(D&&D.ide===v&&D.sourceSignature===T&&D.connectionState===B&&D.machineName===_){S.set(v.id,D),j.push(...D.conversations);continue}const K=co(v,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),L={ide:v,sourceSignature:T,connectionState:B,machineName:_,conversations:K};S.set(v.id,L),j.push(...K)}m.current=S;const A=new Map,M=v=>{const B=_h(v),_=u.current.get(v.tabKey);if(_&&_.signature===B)return A.set(v.tabKey,_),_.timestamp;const T={signature:B,timestamp:bl(v)||(_==null?void 0:_.timestamp)||0};return A.set(v.tabKey,T),T.timestamp},w=[...j].sort((v,B)=>gl(v,B,M));return u.current=A,w},[a,t,i]),x=o.useMemo(()=>{const S=Ih(f,r);return Fn(c.current,S)?c.current:(c.current=S,S)},[f,r]),C=o.useMemo(()=>{const S=new Map,j=Array.from(new Set(x.map(A=>A.routeId)));for(const A of j){const M=Dt(x,A);M&&S.set(A,M)}return S},[x]),y=o.useMemo(()=>{const S=new Map;for(const j of x){const A=C.get(j.routeId),M=j.streamSource==="native"&&A?A:j;for(const w of Ts({providerSessionId:j.providerSessionId,sessionId:j.sessionId}))S.set(w,M)}return S},[x,C]),p=o.useMemo(()=>Rh(x,C),[x,C]),g=o.useCallback(S=>{if(S)return y.get(S)},[y]),b=o.useCallback(S=>{if(S)return p.get(S)},[p]),h=o.useMemo(()=>{const S=x.filter(j=>!po(n,j));return Fn(l.current,S)?l.current:(l.current=S,S)},[x,n]),k=o.useMemo(()=>{const S=h.map(j=>j.tabKey);return Fn(d.current,S)?d.current:(d.current=S,S)},[h]);return{chatIdes:a,conversations:x,visibleConversations:h,visibleTabKeys:k,resolveConversationBySessionId:g,resolveConversationByTarget:b}}function Dh({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),i=o.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=o.useCallback(()=>{t&&n(l=>{const d=new URLSearchParams(l);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Eh({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{at.setIdes(e)},[e]),o.useEffect(()=>{at.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),o.useEffect(()=>{const a=at.onToast(i=>{r(l=>l.some(m=>m.message===i.message&&i.timestamp-m.timestamp<3e3)?l:[...l.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions}]);const c=i.duration||5e3;setTimeout(()=>r(l=>l.filter(d=>d.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=Fc.on("status_event",i=>{at.handleRawEvent(i,"ws")});return()=>{a()}},[]),o.useEffect(()=>{var i;const a=c=>{var p;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const d=l.targetSessionId||l.targetKey||l.daemonId,m=n(d),u=(m==null?void 0:m.routeId)||l.daemonId;if(!u)return;const f=Number(l.buttonIndex),x=l.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[f])||"Approve",C=String(x).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),y=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(C);t(u,"resolve_action",{action:y?"approve":"reject",button:x,...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(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,t])}const $h="adhdev_dashboardLayout_v1",Bh="adhdev_dashboardDockview_v1",Kh="adhdev_dashboardDockviewHiddenRestore_v1",Vs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function ho(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Wh(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function yl(e){return`${$h}:${e}`}function Oh(e){const t=yl(e);return ho(t,null)}function Fh(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=yl(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function vl(e){return`${Bh}:${e}`}function Hh(e){const t=vl(e);return ho(t,null)}function Uh(e,t){try{const r=vl(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function wl(e){return`${Kh}:${e}`}function zh(e){const t=wl(e);return ho(t,{})}function Vh(e,t){try{const r=wl(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Gh(){return{groupAssignments:[...Vs.groupAssignments],focusedGroup:Vs.focusedGroup,groupActiveTabIds:{...Vs.groupActiveTabIds},groupTabOrders:{...Vs.groupTabOrders},groupSizes:[...Vs.groupSizes]}}function qh(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Yh(){const[e]=o.useState(()=>Wh(typeof window<"u"?window.innerWidth:1280)),[t,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,d]=o.useState({}),[m,u]=o.useState([]),[f,x]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[C,y]=o.useState(!1),p=o.useCallback(()=>{if(C)return;const v=Oh(e)??Gh();r(new Map(v.groupAssignments)),a(v.focusedGroup),c(v.groupActiveTabIds),d(v.groupTabOrders),u(v.groupSizes),y(!0)},[C,e]);o.useEffect(()=>{C&&Fh(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:m})},[C,e,t,n,i,l,m]),o.useEffect(()=>{const v=window.matchMedia("(max-width: 767px)"),B=_=>x(_.matches);return v.addEventListener("change",B),()=>v.removeEventListener("change",B)},[]);const g=o.useCallback(v=>{r(v)},[]),b=o.useCallback(v=>{a(v)},[]),h=o.useCallback(v=>{c(v)},[]),k=o.useCallback(v=>{d(v)},[]),S=o.useCallback(v=>{u(v)},[]),j=o.useCallback(v=>{b(v)},[b]),A=o.useCallback((v,B)=>{c(_=>(_[v]??null)===(B??null)?_:{..._,[v]:B})},[]),M=o.useCallback((v,B)=>{d(_=>{const T=_[v];return qh(T,B)?_:{..._,[v]:B}})},[]),w=o.useCallback((v,B)=>{const _=B.get(v)??0;return A(_,v),j(_),_},[j,A]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:g,focusedGroup:n,updateFocusedGroup:b,focusGroup:j,groupActiveTabIds:i,updateGroupActiveTabIds:h,setGroupActiveTab:A,groupTabOrders:l,updateGroupTabOrders:k,setGroupTabOrder:M,groupSizes:m,updateGroupSizes:S,isMobile:f,hasHydratedStoredLayout:C,hydrateStoredLayout:p,focusConversationTab:w}}function Xh(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Za(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Jh({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:f,handleRefreshHistory:x}){const C=o.useRef(!1),y=o.useRef(!1),p=o.useRef(null),g=o.useRef(!1);o.useEffect(()=>{if(!e||C.current||t.length===0)return;if(!a){i();return}const b=r(e);b&&(c(b.tabKey,n),C.current=!0,y.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(h=>{const k=new URLSearchParams(h);return k.delete("activeTab"),k},{replace:!0}))},[e,t,r,n,a,i,c,l]),o.useEffect(()=>{if(!(y.current||a)&&t.length!==0){if(!e){i(),y.current=!0;return}if(C.current){y.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(y.current||a)&&(i(),y.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,i]),o.useEffect(()=>{if(!d){g.current=!1;return}if(!m||g.current||u)return;const b=f.find(h=>h.id===m.routeId);b&&(!b.chats||b.chats.length===0||Xh(b.chats,m))&&(g.current=!0,x())},[d,m,u,f,x])}function Hn(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=Za(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function jl({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[d,m]=o.useState(!1),u=o.useCallback(async y=>{try{await e("standalone","launch_ide",{ideType:y,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),f=o.useCallback(async(y,p)=>{try{const g=y||(t==null?void 0:t.daemonId)||"",b=await e(g,"switch_chat",{id:p,sessionId:p,...rs(t)}),h=b==null?void 0:b.result;if((b==null?void 0:b.success)===!0||h==="switched"||h==="switched-by-title")return;h===!1||h==="not_found"?Hs(a,"⚠️ Session tab not found — try refreshing history"):typeof h=="string"&&h.startsWith("error:")?Hs(a,`⚠️ Switch error: ${h}`):Hs(a,"⚠️ Session switch failed")}catch(g){console.error("Switch failed",g),Hs(a,`❌ Switch failed: ${g.message||"connection error"}`)}},[t,e,a]),x=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const y=Ls(t);await e(y,"new_chat",{...rs(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(y){console.error("New chat failed",y)}finally{l(!1)}}},[t,c,e,i]),C=o.useCallback(async()=>{var y,p;if(!(!t||d)){m(!0);try{const g=Ls(t),b=async()=>e(g,"list_chats",{forceExpand:!0,...rs(t)});let h=await b(),k=(h==null?void 0:h.chats)||((y=h==null?void 0:h.result)==null?void 0:y.chats);Hn(k,t)&&(await new Promise(S=>setTimeout(S,450)),h=await b(),k=(h==null?void 0:h.chats)||((p=h==null?void 0:h.result)==null?void 0:p.chats)),h!=null&&h.success&&Array.isArray(k)&&(n(t.routeId,k),Hn(k,t)&&!Hn(r,t)&&Hs(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:x,handleRefreshHistory:C}}function Qh(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 Zh(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function hi(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 Ir(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const d=a[l];typeof d=="number"&&d>0&&i.set(c,d)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function xi(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=t[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function ex(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 tx(e,t,r){if(t.length<=1)return[];const n=t.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===t.length?n:Array(r).fill(100/r),i=a.reduce((c,l)=>c+l,0);return i>0?a.map(c=>c/i*100):Array(r).fill(100/r)}function bi(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=t?i+1:i]=a}return r}function gi(e){return Array(e).fill(100/e)}function sx({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:d,visibleTabKeys:m}){const u=o.useRef(null),f=o.useMemo(()=>Ir(e,m),[e,m]),x=f.assignments,C=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),y=C>1,p=o.useCallback((j,A)=>{t(M=>{const w=new Map(Ir(M,m).assignments);return A===0?w.delete(j):w.set(j,A),w}),n(M=>({...M,[A]:j})),r(A)},[t,m,n,r]),g=o.useCallback(j=>{t(A=>{const M=Ir(A,m).assignments,w=new Map;for(const[v,B]of M)B!==j&&(B>j?w.set(v,B-1):w.set(v,B));return w}),c(A=>{if(A.length<=1)return[];const M=[...A];M.splice(j,1);const w=M.reduce((v,B)=>v+B,0);return w>0?M.map(v=>v/w*100):[]}),r(0)},[t,m,c,r]),b=o.useCallback((j,A)=>{A.preventDefault();const M=u.current;if(!M)return;const w=A.clientX,v=M.offsetWidth,B=i.length===C?[...i]:gi(C),_=D=>{const L=(D.clientX-w)/v*100,N=[...B];N[j]=Math.max(15,B[j]+L),N[j+1]=Math.max(15,B[j+1]-L),c(N)},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)},[i,C,c]),h=o.useCallback((j,A,M)=>{if(C>=4)return;const w=M==="left"?A:A+1;t(v=>{const B=Ir(v,m).assignments,_=new Map;for(const T of d){const D=B.get(T.tabKey)??0,K=D>=w?D+1:D;K>0&&_.set(T.tabKey,K)}return w>0&&_.set(j,w),_}),c(v=>{const B=v.length===C?[...v]:gi(C),_=B[A]??100/C,T=Math.max(15,_/2),D=Math.max(15,_/2),K=[...B];K[A]=T,K.splice(w,0,D);const L=K.reduce((N,I)=>N+I,0);return K.map(N=>N/L*100)}),n(v=>{const B=bi(v,w);return B[w]=j,B}),a(v=>{const B=bi(v,w);return B[w]=[j],B}),r(w)},[C,t,m,d,c,n,a,r]);o.useEffect(()=>{Qh(e,x)||t(x)},[e,x,t]),o.useEffect(()=>{const{mapping:j,usedGroups:A}=f;n(M=>{const w=xi(M,j);return hi(M,w)?M:w}),a(M=>{const w=xi(M,j);return hi(M,w)?M:w}),r(M=>{const w=l?0:ex(M,A,j);return M===w?M:w}),c(M=>{const w=l?[]:tx(M,A,f.groupCount);return Zh(M,w)?M:w})},[f,l,n,a,r,c]);const k=o.useMemo(()=>{const j=Array.from({length:C},()=>[]);for(const A of d){const M=x.get(A.tabKey)??0,w=Math.min(M,C-1);j[w].push(A)}return j},[d,x,C]),S=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:x,numGroups:C,isSplitMode:y,groupedConvs:k,moveTabToGroup:p,closeGroup:g,handleResizeStart:b,splitTabRelative:h,clearAllSplits:S}}function Un(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 rx(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 Rr(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function xo(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=Un(t.channel)||Un(e.updateChannel)||Un(e.releaseChannel)||void 0,n=rx(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=Rr(t.targetVersion)||Rr(e.serverVersion)||void 0,i=Rr(t.minVersion)||void 0,c=Rr(t.updateCommand)||(r?`adhdev update --channel ${r}`:void 0);return{...r?{channel:r}:{},...n?{npmTag:n}:{},...a?{targetVersion:a}:{},...i?{minVersion:i}:{},...c?{updateCommand:c}:{}}}function js(e,t=null){return xo(e).targetVersion||t}function kl(e){return xo(e).channel||null}function Sl(e){const t=xo(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 nx({ides:e,sendDaemonCommand:t}){const r="0.9.75",n=o.useMemo(()=>e.filter(f=>f.type!=="adhdev-daemon"?!1:al(f,js(f,r))).sort((f,x)=>Number(sr(x,js(x,r)))-Number(sr(f,js(f,r)))),[r,e]),a=o.useMemo(()=>n.some(f=>sr(f,js(f,r))),[r,n]),i=o.useMemo(()=>n.map(f=>js(f,r)).find(f=>typeof f=="string"&&f.trim().length>0)||r,[r,n]),[c,l]=o.useState(!1),[d,m]=o.useState({}),u=o.useCallback(async f=>{var C,y;const x=e.find(p=>p.id===f);if(x){m(p=>({...p,[f]:"upgrading"}));try{const p=await t(f,"daemon_upgrade",Sl(x));(C=p==null?void 0:p.result)!=null&&C.upgraded||(y=p==null?void 0:p.result)!=null&&y.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:i,versionBannerDismissed:c,setVersionBannerDismissed:l,upgradingDaemons:d,handleBannerUpgrade:u}}const Nl=80;function Hr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function ax(e){return{...e,createdAt:Hr(e.createdAt),updatedAt:Hr(e.updatedAt,e.createdAt),lastEventAt:Hr(e.lastEventAt,e.updatedAt||e.createdAt)}}function ox(e){const t=eo(e);return t==="unknown:"?e.id:t}function ix(e){return[e.type,Dc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function cx(e,t=Nl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=ox(n),i=r.get(a);if(!i){r.set(a,n);continue}(n.updatedAt>i.updatedAt||n.updatedAt===i.updatedAt&&n.createdAt>i.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const i=a.updatedAt-n.updatedAt;return i!==0?i:a.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function lx(e,t){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?t.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=pn(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const d=Hr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),m=ix({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(i==null?void 0:i.lastUpdated)||a.lastUpdated});n.push(ax({id:m,dedupKey:m,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Nc(a),preview:Xm(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return cx(n)}function dx(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function ux(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Nl}=e,a=o.useMemo(()=>lx(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>dx(a),[a]);return{notifications:a,unreadCount:i}}function mx({notifications:e,sendDaemonCommand:t}){const r=o.useCallback(i=>{const c=e.find(d=>d.id===i),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,t]),n=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const fx=o.createContext(null);function px(){return o.useContext(fx)}function gn(...e){const t=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();t.has(c)||(t.add(c),r.push(i))};for(const a of e){if(Array.isArray(a)){for(const i of a)n(i);continue}n(a)}return r}function hx(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 yn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=hx(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 xx(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 bx(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function vn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=bx(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.includes("\\")?"\\":"/",l=(m,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(i,m.name)})).sort((m,u)=>m.name.localeCompare(u.name)):[];return{path:i,directories:d}}function gx(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 Cl(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:gx(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function yx(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 Jt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function bo(e){return pr(e)||e.tabKey||e.routeId||null}function Tl(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(t)return t;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=Dt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?bo(a):null}function vx(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function yi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function vi(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function wx({ides:e,conversations:t,onOpenSession:r}){const[n,a]=o.useState(null),i=o.useCallback(c=>{a(c)},[]);return o.useEffect(()=>{if(!n)return;const c=yi(n.workspacePath),l=e.find(m=>{var y,p,g,b;if(!m||m.type==="adhdev-daemon"||vx(m.daemonId||m.id)!==n.machineId||(cr(m)?"cli":Ns(m)?"acp":"ide")!==n.kind||String(m.agentType||m.type||"")!==n.providerType)return!1;if(n.resumeSessionId)return String(m.providerSessionId||"")===n.resumeSessionId;if(c){const h=yi(m.workspace||m.runtimeWorkspaceLabel);return h?h===c:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((b=(g=(p=(y=m.activeChat)==null?void 0:y.messages)==null?void 0:p.at)==null?void 0:g.call(p,-1))==null?void 0:b.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const d=Tl({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});d&&(a(null),r(d))},[t,e,r,n]),o.useEffect(()=>{if(!n)return;const c=window.setTimeout(()=>{a(l=>!l||l.startedAt!==n.startedAt?l:null)},45e3);return()=>window.clearTimeout(c)},[n]),{trackPendingLaunch:i}}function jx({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=px(),l=o.useCallback(async(p,g)=>vn(e,p,g),[e]),d=o.useCallback(async(p,g)=>{if(!g.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(p,"workspace_add",{path:g.trim()});return b!=null&&b.success?{ok:!0}:{ok:!1,error:(b==null?void 0:b.error)||"Could not save workspace"}}catch(b){return{ok:!1,error:b instanceof Error?b.message:"Could not save workspace"}}},[e]),m=o.useCallback(async(p,g,b)=>{var h;try{const k={ideType:g,enableCdp:!0};(h=b==null?void 0:b.workspacePath)!=null&&h.trim()&&(k.workspace=b.workspacePath.trim());const S=await e(p,"launch_ide",k);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:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(k){return{ok:!1,error:k instanceof Error?k.message:"Could not launch IDE"}}},[e,t]),u=o.useCallback(async(p,g,b,h)=>{var S,j,A;const k=Date.now();try{const M={cliType:b};(S=h==null?void 0:h.workspacePath)!=null&&S.trim()?M.dir=h.workspacePath.trim():h!=null&&h.workspaceId&&(M.workspaceId=h.workspaceId),(j=h==null?void 0:h.resumeSessionId)!=null&&j.trim()&&(M.resumeSessionId=h.resumeSessionId.trim()),Array.isArray(h==null?void 0:h.cliArgs)&&h.cliArgs.length>0&&(M.cliArgs=h.cliArgs),(A=h==null?void 0:h.initialModel)!=null&&A.trim()&&(M.initialModel=h.initialModel.trim());const w=await e(p,"launch_cli",M),v=(w==null?void 0:w.result)||w,B=(v==null?void 0:v.sessionId)||(v==null?void 0:v.id);return w!=null&&w.success&&B?(r(B),{ok:!0}):w!=null&&w.success?(t({machineId:p,kind:g,providerType:b,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:(w==null?void 0:w.error)||(v==null?void 0:v.error)||`Could not launch ${g.toUpperCase()} session`}}catch(M){return vi(M)?(t({machineId:p,kind:g,providerType:b,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:M instanceof Error?M.message:`Could not launch ${g.toUpperCase()} session`}}},[r,e,t]),f=o.useCallback(async p=>{var g;if(c!=null&&c.listMeshes)return c.listMeshes(p);if(!p)return[];try{const b=await e(p,"list_meshes",{}),h=(b==null?void 0:b.result)??b;if((h==null?void 0:h.success)===!1)throw new Error((h==null?void 0:h.error)||"Could not load meshes");return(Array.isArray(h==null?void 0:h.meshes)?h.meshes:Array.isArray((g=h==null?void 0:h.result)==null?void 0:g.meshes)?h.result.meshes:[]).map(S=>{var j;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(((j=S.nodes[0])==null?void 0:j.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(b){throw console.error("List meshes failed",b),b}},[c,e]),x=o.useCallback(async(p,g,b)=>{if(!g.trim())return{ok:!1,error:"Choose a mesh first."};if(c!=null&&c.launchMeshCoordinator)return c.launchMeshCoordinator(p,g,b);const h=Date.now();try{const k=await e(p,"launch_mesh_coordinator",{meshId:g.trim(),cliType:b.trim()||"claude-cli"}),S=(k==null?void 0:k.result)??k;if((S==null?void 0:S.success)===!1||(k==null?void 0:k.success)===!1){const A=String((S==null?void 0:S.code)||(k==null?void 0:k.code)||""),M=yx((S==null?void 0:S.meshCoordinatorSetup)||(S==null?void 0:S.manualSetup)||(k==null?void 0:k.meshCoordinatorSetup)||(k==null?void 0:k.manualSetup));return{ok:!1,error:(S==null?void 0:S.error)||(k==null?void 0:k.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:M}}const j=(S==null?void 0:S.sessionId)||(S==null?void 0:S.id);return j?r(j):t({machineId:p,kind:"cli",providerType:b,workspacePath:(S==null?void 0:S.workspace)||null,startedAt:h}),{ok:!0}}catch(k){return vi(k)?(t({machineId:p,kind:"cli",providerType:b,startedAt:h}),{ok:!0}):{ok:!1,error:k instanceof Error?k.message:"Could not launch mesh coordinator"}}},[c,r,e,t]),C=o.useCallback(async(p,g)=>{if(!p||!g)return[];try{const b=await e(p,"list_saved_sessions",{providerType:g,kind:"cli",limit:30}),h=(b==null?void 0:b.result)??b;return Array.isArray(h==null?void 0:h.sessions)?h.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),y=o.useCallback(async p=>{await hl({conversation:n,mode:p,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:i})},[n,a,e,i]);return{handleBrowseMachineDirectory:l,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:f,handleLaunchMeshCoordinator:x,handleListMachineSavedSessions:C,setActiveCliViewMode:y}}function kx(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 Sx(e,t,r=Date.now()){return!e||!kx(t)?null:{tabKey:e,nonce:r}}function Nx({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,d]=o.useState(null),[m,u]=o.useState(null),f=o.useMemo(()=>{var g,b;if(!e){if(l){const h=t.find(k=>k.tabKey===l);if(h)return h}return r[0]}const p=n[a];if(p){const h=t.find(k=>k.tabKey===p);if(h)return h}return((g=i[a])==null?void 0:g[0])||((b=i[0])==null?void 0:b[0])},[t,l,a,n,i,e,r]),x=o.useCallback(p=>{d(p)},[]),C=o.useCallback(p=>{d(p.tabKey),c(g=>{const b=new URLSearchParams(g),h=Qm(p);return h?b.set("activeTab",h):b.delete("activeTab"),b},{replace:!0})},[c]),y=o.useCallback((p,g)=>{const b=Sx(p,g);b&&u(b)},[]);return{activeConv:f,openDesktopConversation:C,requestScrollToBottom:y,scrollToBottomRequest:m,setDesktopActiveTab:x}}function Cx(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 Tx(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&t&&t!==r),autoReadKey:i,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Mx({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=o.useRef(null),i=o.useRef(null),c=o.useRef(null),l=o.useRef(null),d=o.useRef(null);o.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),i.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const u=Qr(e,r),f=Tx({tabKey:e.tabKey,historySessionId:pr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:ls(e),liveState:u}),x=f.autoReadKey,C=Cx({autoReadKey:x,shouldMarkSeen:f.shouldMarkSeen,completedKey:a.current,pendingKey:i.current});if(!f.shouldMarkSeen){C.shouldCancelPending&&m(),a.current=x;return}if(!C.shouldSchedule)return;C.shouldCancelPending&&m();const y=()=>{if(document.visibilityState!=="visible"||a.current===x)return;a.current=x,i.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(i.current=C.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(y,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(y,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),o.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function zn(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 Ax({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:d}){var I;const[m,u]=o.useState(!1),[f,x]=o.useState([]),[C,y]=o.useState(()=>wt()),[p,g]=o.useState(!1),[b,h]=o.useState(null),k=o.useRef(null),S=o.useMemo(()=>r||t||e,[e,r,t]),j=!!S&&tt(S)&&!Ze(S),A=o.useMemo(()=>{if(!S||!j)return null;const F=S.daemonId||S.routeId||"",P=Kt(S),$=zn(S);return`${F}:${P}:${S.providerSessionId||""}:${$}`},[S,j]),M=o.useMemo(()=>!S||!j?"":zn(S),[S,j]),{isCreatingChat:w,isRefreshingHistory:v,handleSwitchSession:B,handleNewChat:_,handleRefreshHistory:T}=jl({sendDaemonCommand:a,activeConv:S,chats:(I=n.find(F=>F.id===(S==null?void 0:S.routeId)))==null?void 0:I.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),D=o.useCallback(()=>{u(!0)},[]),K=o.useCallback(()=>{u(!1)},[]),L=o.useCallback(async()=>{if(!(!S||!j||p)){g(!0);try{const F=S.daemonId||S.routeId,P=Kt(S),$=zn(S),H=await a(F,"list_saved_sessions",{agentType:P,providerType:P,kind:"cli",limit:50,...S.providerSessionId?{providerSessionId:S.providerSessionId}:{},...$?{workspace:$}:{}}),J=(H==null?void 0:H.result)??H;x(Array.isArray(J==null?void 0:J.sessions)?J.sessions:[])}catch(F){console.error("Refresh saved sessions failed",F),x([])}finally{g(!1)}}},[S,p,j,a]);o.useEffect(()=>{if(!m){k.current=null;return}if(!j){k.current=null,x([]),g(!1);return}!A||p||k.current!==A&&(k.current=A,L())},[L,m,p,j,A]);const N=o.useCallback(async F=>{if(!S||!j||!F.providerSessionId||!F.workspace)return;const P=S.daemonId||S.routeId,$=Kt(S);try{h(F.providerSessionId);const H=await a(P,"launch_cli",{cliType:$,dir:F.workspace,resumeSessionId:F.providerSessionId,initialModel:gc(F.summaryMetadata,"model",{preferShortValue:!0})||void 0}),J=(H==null?void 0:H.result)??H,he=typeof(J==null?void 0:J.sessionId)=="string"?J.sessionId:typeof(J==null?void 0:J.id)=="string"?J.id:"";he&&d(ie=>{const te=new URLSearchParams(ie);return te.set("activeTab",he),te},{replace:!0}),K()}catch(H){console.error("Resume saved session failed",H)}finally{h(null)}},[K,S,j,a,d]);return{historyModalOpen:m,openHistoryModal:D,closeHistoryModal:K,historyTargetConv:S,isSavedSessionHistoryTarget:j,isHistoryCreatingChat:w,isHistoryRefreshingHistory:v,handleHistorySwitchSession:B,handleHistoryNewChat:_,handleHistoryRefresh:T,savedHistorySessions:f,savedHistoryFilters:C,setSavedHistoryFilters:y,missingWorkspaceResumePath:M,isSavedHistoryLoading:p,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:L,handleResumeSavedHistorySession:N}}function Ix({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[d,m]=o.useState(null),[u,f]=o.useState(null),x=o.useMemo(()=>{if(e||!n)return null;const b=l(n);return b&&!tt(b)&&!Ze(b)?b:null},[e,n,l]),C=o.useMemo(()=>{const b=d==null?void 0:d.routeId;if(!b)return null;const h=d!=null&&d.tabKey?i.find(k=>k.tabKey===d.tabKey):a?i.find(k=>k.tabKey===a):null;return(h==null?void 0:h.routeId)===b?h:Dt(i,b)},[i,d,a]),y=o.useMemo(()=>{if(C)return c.find(b=>b.id===C.routeId)},[c,C]);o.useEffect(()=>{x&&(m({routeId:x.routeId,tabKey:qo(x)}),f(x),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,x]);const p=o.useCallback(b=>{b&&(m({routeId:b.routeId,tabKey:qo(b)}),f(b))},[]),g=o.useCallback(()=>{m(null),f(null)},[]);return{remoteDialogConv:C,remoteDialogIdeEntry:y,remoteDialogActiveConv:u,setRemoteDialogActiveConv:f,openRemoteDialog:p,closeRemoteDialog:g}}function Rx({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:f,remoteDialogActiveConv:x,setRemoteDialogActiveConv:C,openRemoteDialog:y,closeRemoteDialog:p}=Ix({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[g,b]=o.useState(!1),[h,k]=o.useState(null),S=o.useCallback(async M=>{const w=M||d;!w||!tt(w)&&!Ze(w)||(k(w),b(!0))},[d]),j=o.useCallback(()=>{b(!1),k(null)},[]),A=o.useCallback(async M=>{const w=h||d;if(!w||!tt(w)&&!Ze(w)){j();return}b(!1);try{const v=Kt(w),B=w.routeId||w.daemonId||"";await m(B,"stop_cli",{cliType:v,targetSessionId:w.sessionId,mode:M})}catch(v){console.error("Stop CLI failed:",v)}finally{k(null)}},[d,j,h,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:f,remoteDialogActiveConv:x,setRemoteDialogActiveConv:C,openRemoteDialog:y,closeRemoteDialog:p,cliStopDialogOpen:g,cliStopTargetConv:h,requestCliStop:S,cancelCliStop:j,confirmCliStop:A}}function Ml({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:i=!1}){var b;const c=$s(),l=bs(e),d=i?null:Sc(e),m=!i&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!i&&e.streamSource==="agent-stream"&&!!e.agentName,f=!i&&!u&&(e.transport==="pty"||e.transport==="acp"),x=Rs(e),C=Jm(e),y=(b=e.settings)==null?void 0:b.meshNodeFor;if(!m&&!u&&!f&&!d&&!y)return null;const p=o.useCallback(()=>{if(n){n();return}l&&c("/dashboard",{state:{openMachineId:l}})},[l,c,n]),g=o.useCallback(()=>{if(r){r();return}const h=bo(e);h&&c(Jt(h))},[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:g,title:C,children:[s.jsx(Mt,{size:12}),s.jsx("span",{children:C})]}):s.jsxs("span",{className:"conversation-meta-chip",title:C,children:[s.jsx(Mt,{size:12}),s.jsx("span",{children:C})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Is,{size:12}),s.jsx("span",{children:x})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Is,{size:12}),s.jsx("span",{children:x})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:p,title:d,children:[s.jsx(Yt,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(Yt,{size:12}),s.jsx("span",{children:d})]})),y&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Yt,{size:12}),s.jsx("span",{children:"Mesh Node"})]})]})}function Vn(e,t=!0){return(e??!0)&&t}const go=o.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u=null,handleFocusAgent:f,isFocusingAgent:x,actionLogs:C,userName:y,scrollToBottomRequestNonce:p,isInputActive:g=!0,isVisible:b=!0}){const h=n,k=!n,S=Vn(b,h),j=Vn(b,k),A=Vn(b),M=dl(t),w=M.status||M.modalMessage||M.modalButtons?{...t,...M.status?{status:M.status}:{},...M.modalMessage!==void 0?{modalMessage:M.modalMessage}:{},...M.modalButtons!==void 0?{modalButtons:M.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(hc,{activeConv:w,onModalButton:c}),s.jsx(Ml,{conversation:w,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),w.transport!=="pty"&&w.transport!=="acp"&&w.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(ir,{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,w.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:h?"visible":"hidden",pointerEvents:h?"auto":"none"},children:s.jsx(lp,{activeConv:w,clearToken:r,terminalRef:i,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:k?"visible":"hidden",pointerEvents:k?"auto":"none"},children:s.jsx(Sa,{activeConv:w,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:x,actionLogs:C,userName:y,scrollToBottomRequestNonce:p,isInputActive:g&&j,isVisible:j})})]}):s.jsx(Sa,{activeConv:w,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:x,actionLogs:C,userName:y,scrollToBottomRequestNonce:p,isInputActive:g&&A,isVisible:A})]})},(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 Lx({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:f,onOpenHistory:x,onOpenRemote:C,onStopCli:y,cliViewMode:p,onSetCliViewMode:g,handleSendChat:b,handleFocusAgent:h,handleModalButton:k,handleRelaunch:S}){const j=o.useRef(null),A=tt(e)&&!t,M=A&&p==="terminal",w=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 ${w} 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(Ka,{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:lt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(Ml,{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:[A&&p&&s.jsx(so,{mode:p,onChange:g,compact:!0}),A&&y&&s.jsx("button",{onClick:()=>{y(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(vt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",children:s.jsx(Wa,{size:14})}),!t&&!A&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>C(e),type:"button",children:s.jsx(Mt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(go,{activeConv:e,clearToken:0,isCliTerminal:M,ideEntry:n,terminalRef:j,handleModalButton:k,handleRelaunch:S,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:h,isFocusingAgent:d,actionLogs:a,userName:i})})]})}const Gn={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 _x(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Al(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(_x())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Gn[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:Gn[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Gn[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 Il({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Mt},{key:"chats",label:"Chats",icon:Ut}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:i})=>{const c=e===n;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(n),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(i,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function Lr({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 ys({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 Gs({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 Px({conversation:e,onCancel:t,onConfirm:r}){const n=lt(e),a=ps(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(vt,{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 _r({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onCollectChatDebugBundle:i}){const c=t==="needs_attention"||t==="task_complete",l=t==="working",d=t==="earlier",m=t==="task_complete",{isReconnecting:u,isConnecting:f}=Bs(e.conversation),x=lt(e.conversation),C=ps(e.conversation),y=Uc(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",b=d?"text-text-secondary":"text-text-primary",h=d?"text-text-muted":"text-text-secondary",k=d?"text-text-secondary opacity-80":"text-text-muted",S=d?"text-text-muted opacity-80":"text-text-muted",j=!l&&!m,A="text-[color:var(--status-warning)]",M=w=>{if(!i)return;w.preventDefault(),w.stopPropagation();const v=i==null?void 0:i(e.conversation);Promise.resolve(v).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(x)}),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:w=>{w.preventDefault(),w.stopPropagation(),a()},"aria-label":`Hide ${x}`,title:"Hide conversation",children:[s.jsx(Oa,{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:M,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 ${b}`,children:x}),j&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${S}`,children:pc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${h}`,children:[s.jsx("span",{className:"truncate",children:C}),s.jsx(_s,{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:`${A} 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…"})]}):y==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:A,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${k}`,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 wi({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 Dx({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:f,onHideConversation:x,onOpenNewSession:C,onOpenMachine:y,onOpenSettings:p,onSectionChange:g,wsStatus:b="connected",isStandalone:h=!1,onCollectChatDebugBundle:k}){const[S,j]=o.useState(null),A=b==="disconnected"||b==="reconnecting"||b==="offline"||b==="auth_failed",M=c.length>0,w=t.length>0||r.length>0||n.length>0||a.length>0,v=e==="machines"?"Machines":"Chats",B=h?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",_=h?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",T=o.useCallback(async L=>{const N=Ls(L);if(!N)return;const I=Array.isArray(L.messages)?L.messages:[],F=Ic({activeConv:L,visibleMessages:I,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:I.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),P=await m(N,"get_chat_debug_bundle",{...rs(L),delivery:"daemon_file",frontendSnapshot:F}),$=sn(P),H=_c($),J=await Lc(H);J==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),at.showToast(Rc($,{locatorCopyStatus:J}),J==="failed"?"warning":"success")},[d,m]),D=k||T,K=o.useCallback(()=>{S&&(x==null||x(S),j(null))},[S,x]);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:v}),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(mn,{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(un,{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:A?s.jsx(Gs,{icon:s.jsx(wi,{}),title:b==="offline"?"Network offline":b==="auth_failed"?"Session expired":"Reconnecting",subtitle:b==="offline"?"Waiting for network…":b==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(Gs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:h?"Waiting for your daemon":"Connect your machines",subtitle:h?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!h&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Al,{})})}):s.jsx(ys,{children:c.map((L,N)=>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] ${N>0?"border-t border-border-subtle/70":""}`,onClick:()=>y(L.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(L.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:L.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:L.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[L.unread," new"]}):L.total>0?`${L.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:L.subtitle}),L.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[L.total," chat",L.total!==1?"s":"",L.unread>0?` · ${L.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},L.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(Lr,{title:"Needs attention",className:"mb-0"}),s.jsx(ys,{children:t.map((L,N)=>s.jsx("div",{className:N>0?"border-t border-border-subtle/70":"",children:s.jsx(_r,{item:L,type:"needs_attention",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>j(L.conversation):void 0,onCollectChatDebugBundle:D})},L.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(Lr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(ys,{children:r.map((L,N)=>s.jsx("div",{className:N>0?"border-t border-border-subtle/70":"",children:s.jsx(_r,{item:L,type:"task_complete",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>j(L.conversation):void 0,onCollectChatDebugBundle:D})},L.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(Lr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(ys,{children:n.map((L,N)=>s.jsx("div",{className:N>0?"border-t border-border-subtle/70":"",children:s.jsx(_r,{item:L,type:"working",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>j(L.conversation):void 0,onCollectChatDebugBundle:D})},L.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(Lr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(ys,{children:a.map((L,N)=>s.jsx("div",{className:N>0?"border-t border-border-subtle/70":"",children:s.jsx(_r,{item:L,type:"earlier",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:x?()=>j(L.conversation):void 0,onCollectChatDebugBundle:D})},L.conversation.tabKey))}):w?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):A?s.jsx(Gs,{icon:s.jsx(wi,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):M?s.jsx(Gs,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Ut,{size:20})}),title:"No conversations yet",subtitle:Gc,children:C&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:C,"aria-label":$t,title:$t,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:$t})]})}):s.jsx(Gs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(ys,{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:[i.length," collapsed ",i.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"&&C&&w&&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:C,"aria-label":$t,title:$t,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),S&&s.jsx(Px,{conversation:S,onCancel:()=>j(null),onConfirm:K}),s.jsx(Il,{section:e,onSectionChange:g})]})}function Ex(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 Rl(e){const t=[e.workspace||"Workspace unknown"],r=fs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Ex(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function wn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:d,onConfirm:m}){const[u,f]=o.useState(r);o.useEffect(()=>{f(r)},[r]);const x=xx(r),C=u.trim();return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!x||a||d(x)},disabled:!x||a,children:[s.jsx(Ka,{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:y=>f(y.target.value),onKeyDown:y=>{y.key!=="Enter"||!C||a||(y.preventDefault(),d(C))},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:()=>{!C||a||d(C)},disabled:!C||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(y=>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(y.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(ms,{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:y.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:y.path})]})]},y.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(C||r),disabled:!C&&!r||a,children:c})]})]})})}function yo({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:f,showModelInput:x,modelValue:C,onModelChange:y,historyProviderNode:p,onConfirm:g,onCancel:b}){const h=n==null?void 0:n.find(k=>k.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:b,"aria-label":"Close launch confirmation",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:k=>i(k.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(k=>s.jsx("option",{value:k.key,children:k.label},k.key))}),(h==null?void 0:h.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),p,r.map(k=>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:k.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:k.value})]},`${k.label}:${k.value}`)),x&&y&&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:C||"",onChange:k=>y(k.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:k=>f(k.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:b,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(Ha,{size:14}),d?l:c]})]})]})})}function ji(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ds(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])i.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${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&&i.push({key:`custom:${c}`,label:ji(c),description:c,workspaceId:null,workspacePath:c}),n){const d=`saved:${n}`;if(i.some(m=>m.key===d))return{options:i,selectedKey:d}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function $x(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Bx(e){return[$x(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Kx(e){return e.lastLaunchedAt?fn(e.lastLaunchedAt):""}function Ll(e){return{metaText:Bx(e),updatedLabel:Kx(e)}}function qn(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Wx({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var st,mt,ht,xt;const c=fr(),[l,d]=o.useState(!1),m=(((st=e.detectedIdes)==null?void 0:st.length)||0)>0,u=o.useMemo(()=>(e.workspaces||[]).map(Ne=>({id:Ne.id,path:Ne.path,label:Ne.label})),[e]),f=e.defaultWorkspaceId||null,[x,C]=o.useState(f||((mt=u[0])==null?void 0:mt.id)||""),[y,p]=o.useState(""),[g,b]=o.useState(""),[h,k]=o.useState([]),[S,j]=o.useState(!1),[A,M]=o.useState(""),[w,v]=o.useState(!1),[B,_]=o.useState(qn(m,t.length,r.length)),T=o.useRef(null),[D,K]=o.useState(null),L=o.useRef("__home__"),[N,I]=o.useState("__home__"),[F,P]=o.useState(""),[$,H]=o.useState(""),[J,he]=o.useState(""),[ie,te]=o.useState([]),[be,we]=o.useState(()=>wt().textQuery),[ge,X]=o.useState(()=>wt().workspaceQuery),[ce,ye]=o.useState(()=>wt().modelQuery),[ne,de]=o.useState(()=>wt().resumableOnly),[je,me]=o.useState(()=>wt().sortMode),[pe,ee]=o.useState(!1),[ue,oe]=o.useState(!1),q=o.useRef(null),V=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const le=x==="__custom__"?y.trim():((ht=u.find(Ne=>Ne.id===x))==null?void 0:ht.path)||"",ke=x==="__custom__"&&!!le&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),Z=x!=="__custom__"&&((xt=u.find(Ne=>Ne.id===x))==null?void 0:xt.path)||"",De=o.useMemo(()=>(e.recentLaunches||[]).map(Ne=>Ne.workspace),[e]),$e=o.useCallback(async Ne=>{j(!0),M("");try{const ze=await a(Ne);b(ze.path),p(ze.path),k(ze.directories)}catch(ze){M(ze instanceof Error?ze.message:"Could not load folder")}finally{j(!1)}},[a]),Fe=o.useCallback(()=>{var ze;C("__custom__"),v(!0);const Ne=yn(e.platform,gn(y.trim(),Z,De,e.defaultWorkspacePath,(ze=u.find(Je=>Je.id===f))==null?void 0:ze.path,u.map(Je=>Je.path)));$e(Ne)},[y,f,$e,De,Z,e.platform,u]),Ue=o.useCallback(Ne=>{if(Ne!=null&&Ne.workspaceId){C(Ne.workspaceId),p("");return}if(Ne!=null&&Ne.workspacePath){C("__custom__"),p(Ne.workspacePath);return}C(""),p("")},[]),W=o.useCallback(Ne=>{if(C(Ne),Ne==="__custom__"){Fe();return}p("")},[Fe]),Ce=o.useCallback(Ne=>{C("__custom__"),p(Ne)},[]),Te=o.useCallback((Ne,ze)=>{T.current=ze,L.current=Ne.selectedWorkspaceKey||"__home__",I(Ne.selectedWorkspaceKey||"__home__"),P(Ne.initialArgs||""),H(Ne.initialModel||""),he(""),te([]);const Je=Ne.providerType?`${e.id}:${Ne.providerType}`:null;if(vp(V.current,Je)){const Ge=wt();we(Ge.textQuery),X(Ge.workspaceQuery),ye(Ge.modelQuery),de(Ge.resumableOnly),me(Ge.sortMode)}V.current=Je,K(Ne),Ne.providerType&&i&&(ee(!0),i(Ne.providerType).then(Ge=>te(Ge||[])).catch(Ge=>console.warn("Failed to load saved sessions",Ge)).finally(()=>ee(!1)))},[i,e.id]),_e=o.useMemo(()=>qc(ie,{textQuery:be,workspaceQuery:ge,modelQuery:ce,resumableOnly:ne,sortMode:je}),[ce,ne,ie,je,be,ge]);o.useEffect(()=>{J&&(_e.some(Ne=>Ne.providerSessionId===J)||he(""))},[_e,J]);const Be=o.useCallback(()=>{T.current&&(oe(!0),T.current().finally(()=>{T.current=null,oe(!1),K(null)}))},[]),He=o.useCallback(()=>{T.current=null,K(null)},[]),Xe=o.useCallback(Ne=>{L.current=Ne,I(Ne)},[]);return o.useEffect(()=>{var Ne;q.current!==e.id&&(q.current=e.id,C(f||((Ne=u[0])==null?void 0:Ne.id)||"__custom__"),p(""),b(""),k([]),M(""),v(!1),we(wt().textQuery),X(wt().workspaceQuery),ye(wt().modelQuery),de(wt().resumableOnly),me(wt().sortMode),V.current=null,_(qn(m,t.length,r.length)))},[r.length,t.length,f,m,e.id,u]),o.useEffect(()=>{var Ne;x!=="__custom__"&&(x&&u.some(ze=>ze.id===x)||C(f||((Ne=u[0])==null?void 0:Ne.id)||"__custom__"))},[f,x,u]),o.useEffect(()=>{B==="ide"&&m||B==="cli"&&t.length>0||B==="acp"&&r.length>0||_(qn(m,t.length,r.length))},[B,r.length,t.length,m]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:f,workspaceChoice:x,customWorkspacePath:y,browseCurrentPath:g,browseDirectories:h,browseBusy:S,browseError:A,browseDialogOpen:w,activeLauncherKind:B,launchConfirm:D,launchConfirmWorkspaceKeyRef:L,launchConfirmWorkspaceKey:N,launchConfirmArgs:F,launchConfirmModel:$,launchConfirmResumeId:J,launchConfirmSavedSessions:ie,launchConfirmTextFilter:be,launchConfirmWorkspaceFilter:ge,launchConfirmModelFilter:ce,launchConfirmResumableOnly:ne,launchConfirmSortMode:je,filteredLaunchConfirmSavedSessions:_e,launchConfirmSessionsLoading:pe,launchConfirmBusy:ue,resolvedWorkspacePath:le,canCreateMissingWorkspace:ke,openBrowseDialog:Fe,loadBrowsePath:$e,handleWorkspaceChoiceChange:W,chooseCustomWorkspacePath:Ce,setCustomWorkspacePath:p,setBrowseDialogOpen:v,setActiveLauncherKind:_,openLaunchConfirm:Te,handleConfirmLaunch:Be,closeLaunchConfirm:He,setWorkspaceSelectionFromOption:Ue,setLaunchConfirmWorkspaceKeyAndSync:Xe,setLaunchConfirmArgs:P,setLaunchConfirmModel:H,setLaunchConfirmResumeId:he,setLaunchConfirmTextFilter:we,setLaunchConfirmWorkspaceFilter:X,setLaunchConfirmModelFilter:ye,setLaunchConfirmResumableOnly:de,setLaunchConfirmSortMode:me}}function Ox({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:d,section:m,showBottomNav:u,onBack:f,onSectionChange:x,onOpenConversation:C,onOpenRecent:y,onOpenMachineDetails:p,onMachineUpgrade:g,onLaunchDetectedIde:b,onAddWorkspace:h,onBrowseDirectory:k,onLaunchWorkspaceProvider:S,onListSavedSessions:j}){const A=N=>N==="ide"?"IDE":N==="cli"?"CLI":"ACP",M=r.slice(0,4),w=t.slice(0,3),v=Wx({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:k,onListSavedSessions:j}),B=o.useMemo(()=>M.map(N=>{const{metaText:I,updatedLabel:F}=Ll(N);return{key:`recent-launch:${N.id}`,primary:N.label,secondary:I,updatedLabel:F,onClick:()=>{const{options:P,selectedKey:$}=ds({machine:{workspaces:v.workspaceRows,defaultWorkspaceId:v.defaultWorkspaceId},currentWorkspacePath:N.workspace});v.openLaunchConfirm({title:N.kind==="ide"?as("restart-ide",N.label):N.providerSessionId?ao(N.label):as("start-fresh",N.label),description:N.kind==="ide"?os("restart-ide"):N.providerSessionId?oo():os("start-fresh"),confirmLabel:N.kind==="ide"?Ps("restart-ide"):N.providerSessionId?nn(!0):Ps("start-fresh"),busyLabel:N.kind==="ide"?Ds("restart-ide"):N.providerSessionId?ro(!0):Ds("start-fresh"),workspaceOptions:P,selectedWorkspaceKey:$,details:[{label:"Mode",value:A(N.kind)},...N.providerType?[{label:"Provider",value:N.providerType}]:[]]},async()=>{const H=P.find(J=>J.key===v.launchConfirmWorkspaceKeyRef.current);v.setWorkspaceSelectionFromOption(H),await y({...N,workspace:(H==null?void 0:H.workspacePath)??null})})}}}),[v,y,M]),_=o.useMemo(()=>w.map(N=>({key:`recent-chat:${N.conversation.tabKey}`,primary:lt(N.conversation),secondary:ap(N.conversation,{timestampLabel:N.timestamp?pc(N.timestamp):null}),unread:N.unread,onClick:()=>C(N.conversation)})),[C,w]),T=v.showAllRecent?B:B.slice(0,4),D=B.length>0,K=_.length>0,L=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 ${L} 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(Ka,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Tt(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[K&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:_.map(N=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${N.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:N.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:N.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))})]}),D&&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(N=>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:N.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:N.primary}),N.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:N.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.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:()=>v.setShowAllRecent(N=>!N),children:v.showAllRecent?"Show fewer":`Show ${B.length-4} more`})})]}),(v.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:v.workspaceChoice,onChange:N=>v.handleWorkspaceChoiceChange(N.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:v.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[v.workspaceRows.map(N=>s.jsxs("option",{value:N.id,children:[N.id===v.defaultWorkspaceId?"⭐ ":"",hn(N.path,N.label)||N.path]},N.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),v.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(ms,{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:v.resolvedWorkspacePath||v.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:v.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:()=>{v.resolvedWorkspacePath&&h(v.resolvedWorkspacePath)},disabled:!v.resolvedWorkspacePath||v.browseBusy,children:"Save as workspace"})]})]}),v.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:v.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[v.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${v.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:()=>v.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${v.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:()=>v.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${v.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:()=>v.setActiveLauncherKind("acp"),children:"ACP"})]}),v.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:v.activeLauncherKind==="ide"?"Choose an IDE":v.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:v.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(N=>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:I,selectedKey:F}=ds({machine:{workspaces:v.workspaceRows,defaultWorkspaceId:v.defaultWorkspaceId},currentWorkspaceId:v.workspaceChoice!=="__custom__"?v.workspaceChoice:null,currentWorkspacePath:v.resolvedWorkspacePath});v.openLaunchConfirm({title:`Launch ${N.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:I,selectedWorkspaceKey:F,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:N.name}]},async()=>{const P=I.find($=>$.key===v.launchConfirmWorkspaceKeyRef.current);v.setWorkspaceSelectionFromOption(P),b(N.type,{workspacePath:(P==null?void 0:P.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:N.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:v.resolvedWorkspacePath||"Use selected workspace"})]},N.type)):(v.activeLauncherKind==="cli"?n:a).map(N=>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 I=v.activeLauncherKind==="cli"?"cli":"acp",{options:F,selectedKey:P}=ds({machine:{workspaces:v.workspaceRows,defaultWorkspaceId:v.defaultWorkspaceId},currentWorkspaceId:v.workspaceChoice!=="__custom__"?v.workspaceChoice:null,currentWorkspacePath:v.resolvedWorkspacePath});v.openLaunchConfirm({title:`Launch ${N.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${I.toUpperCase()}`,workspaceOptions:F,selectedWorkspaceKey:P,details:[{label:"Mode",value:I.toUpperCase()},{label:"Provider",value:N.displayName}],showArgsInput:!0,showModelInput:I==="acp",initialArgs:"",initialModel:"",providerType:N.type},async()=>{const $=F.find(H=>H.key===v.launchConfirmWorkspaceKeyRef.current);v.setWorkspaceSelectionFromOption($),S(I,N.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.workspacePath)??null,args:v.launchConfirmArgs,model:v.launchConfirmModel,resumeSessionId:v.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[N.icon?`${N.icon} `:"",N.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:v.resolvedWorkspacePath||"Use selected workspace"})]},N.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,v.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:()=>h(v.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick: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"})]})]})]})]}),v.browseDialogOpen&&s.jsx(wn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:v.browseCurrentPath,directories:v.browseDirectories,busy:v.browseBusy,error:v.browseError,confirmLabel:"Use this folder",onClose:()=>v.setBrowseDialogOpen(!1),onNavigate:N=>{v.loadBrowsePath(N)},onConfirm:N=>{v.chooseCustomWorkspacePath(N),v.setBrowseDialogOpen(!1)}}),v.launchConfirm&&s.jsx(yo,{title:v.launchConfirm.title,description:v.launchConfirm.description,details:v.launchConfirm.details,workspaceOptions:v.launchConfirm.workspaceOptions,selectedWorkspaceKey:v.launchConfirmWorkspaceKey,onWorkspaceChange:v.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:v.launchConfirm.providerType?nn(!!v.launchConfirmResumeId):v.launchConfirm.confirmLabel,busyLabel:v.launchConfirm.providerType?void 0:v.launchConfirm.busyLabel,busy:v.launchConfirmBusy,showArgsInput:v.launchConfirm.showArgsInput,argsValue:v.launchConfirmArgs,onArgsChange:v.setLaunchConfirmArgs,showModelInput:v.launchConfirm.showModelInput,modelValue:v.launchConfirmModel,onModelChange:v.setLaunchConfirmModel,historyProviderNode:v.launchConfirm.providerType&&(v.launchConfirmSessionsLoading||v.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"}),v.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:no()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:v.launchConfirmTextFilter,onChange:N=>v.setLaunchConfirmTextFilter(N.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:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:v.launchConfirmWorkspaceFilter,onChange:N=>v.setLaunchConfirmWorkspaceFilter(N.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:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:v.launchConfirmModelFilter,onChange:N=>v.setLaunchConfirmModelFilter(N.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:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),s.jsxs("select",{value:v.launchConfirmSortMode,onChange:N=>v.setLaunchConfirmSortMode(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.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:v.launchConfirmResumableOnly,onChange:N=>v.setLaunchConfirmResumableOnly(N.target.checked),disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:v.launchConfirmResumeId,onChange:N=>v.setLaunchConfirmResumeId(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:kp()}),v.filteredLaunchConfirmSavedSessions.map(N=>s.jsxs("option",{value:N.providerSessionId,disabled:!N.canResume,children:[N.title||N.providerSessionId," ",N.canResume?"":"(workspace missing)"]},N.providerSessionId))]}),!v.launchConfirmSessionsLoading&&v.launchConfirmSavedSessions.length>0&&v.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),v.launchConfirmResumeId&&(()=>{const N=v.filteredLaunchConfirmSavedSessions.find(F=>F.providerSessionId===v.launchConfirmResumeId);if(!N)return null;const I=Rl(N);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:I.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:I.providerSessionId}),s.jsx("div",{className:"mt-1",children:I.metaLine}),I.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:I.updatedLabel}),I.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:I.preview})]})})()]}),onConfirm:v.handleConfirmLaunch,onCancel:v.closeLaunchConfirm}),u&&s.jsx(Il,{section:m,onSectionChange:x})]})}function Ur(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Fx(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:Ur(e)}function Hx(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 Ux(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:fs(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,d,m,u;const a=cr(n)?"cli":Ns(n)?"acp":"ide",i=fs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(cr(n)?n.cliName||n.type:Ns(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ns(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((u=(m=(d=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:d.at)==null?void 0:m.call(d,-1))==null?void 0:u.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function zx(e,t){const r=new Map;for(const n of t){const a=bs(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((f,x)=>x.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=ya(n),d=a.filter(f=>f.unread||f.requiresAction).length,m=Hx(n),u=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Tt(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?op(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const i=n.latestTimestamp||n.fallbackActivityAt||0,c=a.latestTimestamp||a.fallbackActivityAt||0;return c!==i?c-i:n.label.localeCompare(a.label)})}function Vx(e){return e==="chat"}function Pr(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 Gx({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:C,setSelectedTabKey:y,setScreen:p,setSelectedMachineId:g,setSection:b,setMachineBackTarget:h,resetMachineAction:k}){const S=o.useRef(null),j=o.useCallback(A=>{if(!(A!=null&&A.sessionId))return;const M=Qr(A,c),w=Math.max(Date.now(),ls(A),M.lastUpdated||0);Pr("mark_read:start",{tabKey:A.tabKey,sessionId:A.sessionId,displayPrimary:lt(A),inboxBucket:M.inboxBucket,unread:M.unread,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,activityAt:ls(A),readAt:w}),l(bs(A)||A.routeId,"mark_session_seen",{sessionId:A.sessionId,providerSessionId:A.providerSessionId,seenAt:w,completionMarker:M.completionMarker}).then(v=>{Pr("mark_read:result",{tabKey:A.tabKey,sessionId:A.sessionId,result:v})}).catch(v=>{Pr("mark_read:error",{tabKey:A.tabKey,sessionId:A.sessionId,error:v instanceof Error?v.message:String(v)})})},[c,l]);return o.useEffect(()=>{var M;if(!n){Vx(i)&&p("inbox"),y(((M=e[0])==null?void 0:M.tabKey)||null),S.current=null;return}if(i!=="chat"){S.current=null;return}const A=`${n.tabKey}:${n.sessionId||""}`;S.current!==A&&(S.current=A,j(n))},[e,j,i,n,p,y]),o.useEffect(()=>{if(!d)return;const A=e.find(M=>M.tabKey===d);A&&(y(A.tabKey),p("chat"),m==null||m())},[e,m,d,p,y]),o.useEffect(()=>{if(!u)return;const A=t.find(M=>M.id===u);A&&(g(A.id),k(),b("machines"),h("inbox"),p("machine"),f==null||f())},[t,f,u,k,h,p,b,g]),o.useEffect(()=>{x&&(b(x),p("inbox"),C==null||C())},[C,x,p,b]),o.useEffect(()=>{const A=r.filter(M=>M.inboxBucket==="task_complete"||M.unread);A.length!==0&&Pr("inbox_state",{screen:i,selectedTabKey:a,items:A.map(M=>{const w=Qr(M.conversation,c);return{liveState:w,tabKey:M.conversation.tabKey,sessionId:M.conversation.sessionId,displayPrimary:lt(M.conversation),serverBucket:w.inboxBucket,computedBucket:M.inboxBucket,serverUnread:w.unread,computedUnread:M.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:ls(M.conversation)}})})},[r,c,i,a]),{markConversationRead:j}}function qx(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ki(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Yx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Xx({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[d,m]=o.useState(null),u=o.useCallback(()=>{i("idle"),l(""),m(null)},[]),f=o.useCallback(async(h,k,S)=>{var j;try{i("loading"),l(`Launching ${k}…`);const A={ideType:k,enableCdp:!0};(j=S==null?void 0:S.workspacePath)!=null&&j.trim()&&(A.workspace=S.workspacePath.trim()),await e(h,"launch_ide",A),i("done"),l(`${k} launch requested`)}catch(A){i("error"),l(A instanceof Error?A.message:"Launch IDE failed"),console.error("Launch IDE failed",A)}},[e]),x=o.useCallback(async(h,k,S)=>{if(k.trim())try{i("loading"),l(S!=null&&S.createIfMissing?"Creating folder…":"Saving workspace…");const j=await e(h,"workspace_add",{path:k.trim(),createIfMissing:(S==null?void 0:S.createIfMissing)===!0});if(j!=null&&j.success){i("done"),l(S!=null&&S.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((j==null?void 0:j.error)||"Could not save workspace")}catch(j){i("error"),l(j instanceof Error?j.message:"Could not save workspace")}},[e]),C=o.useCallback(async h=>{var k,S,j,A,M,w;try{i("loading"),l("Starting daemon upgrade…");const v=await e(h,"daemon_upgrade",{});if((k=v==null?void 0:v.result)!=null&&k.alreadyLatest){i("done"),l(`Already on v${((S=v==null?void 0:v.result)==null?void 0:S.version)||"latest"}.`);return}if((j=v==null?void 0:v.result)!=null&&j.upgraded||(A=v==null?void 0:v.result)!=null&&A.success){i("done"),l(`Upgrade to v${((M=v==null?void 0:v.result)==null?void 0:M.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((w=v==null?void 0:v.result)==null?void 0:w.error)||"Upgrade failed")}catch(v){i("error"),l(v instanceof Error?v.message:"Upgrade failed")}},[e]),y=o.useCallback(async(h,k,S,j)=>{var w,v,B;const A=Date.now(),M={machineId:h,kind:k,providerType:S,workspaceId:(j==null?void 0:j.workspaceId)||null,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:A};try{i("loading"),l(`Launching ${S}…`),m(M);const _={cliType:S};(w=j==null?void 0:j.workspacePath)!=null&&w.trim()?_.dir=j.workspacePath.trim():j!=null&&j.workspaceId&&(_.workspaceId=j.workspaceId),j!=null&&j.resumeSessionId&&(_.resumeSessionId=j.resumeSessionId),(v=j==null?void 0:j.args)!=null&&v.trim()&&(_.cliArgs=j.args.trim().split(/\s+/).filter(Boolean)),(B=j==null?void 0:j.model)!=null&&B.trim()&&(_.initialModel=j.model.trim());const T=await e(h,"launch_cli",_),D=(T==null?void 0:T.result)||T,K=(D==null?void 0:D.sessionId)||(D==null?void 0:D.id);if(T!=null&&T.success&&K){m(null),i("done"),l(`${S} launched`),t(Jt(K));return}if(T!=null&&T.success){i("loading"),l(`${S} launch requested — waiting for session…`);return}m(null),i("error"),l((T==null?void 0:T.error)||(D==null?void 0:D.error)||`Could not launch ${k.toUpperCase()} workspace`)}catch(_){if(Yx(_)){i("loading"),l(`${S} launch requested — waiting for session…`);return}m(null),i("error"),l(_ instanceof Error?_.message:`Could not launch ${k.toUpperCase()} workspace`)}},[t,e]),p=o.useCallback(async(h,k)=>{try{const S=await e(h,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),j=(S==null?void 0:S.result)??S;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(S){return console.error("Failed to list saved sessions on mobile:",S),[]}},[e]),g=o.useCallback(async(h,k)=>vn(e,h,k),[e]);o.useEffect(()=>{if(!d)return;const h=ki(d.workspacePath),k=r.find(j=>{var _,T,D,K;if(!j||j.type==="adhdev-daemon"||qx(j.daemonId||j.id)!==d.machineId||(j.transport==="acp"?"acp":j.transport==="pty"?"cli":null)!==d.kind||String(j.agentType||j.type||"")!==d.providerType)return!1;const v=String(j.providerSessionId||"");if(d.resumeSessionId&&v)return v===d.resumeSessionId;if(h){const L=ki(j.workspace||j.runtimeWorkspaceLabel);return L?L===h:!1}return Number(j.lastUpdated||j._lastUpdate||j.timestamp||((K=(D=(T=(_=j.activeChat)==null?void 0:_.messages)==null?void 0:T.at)==null?void 0:D.call(T,-1))==null?void 0:K.timestamp)||0)>=d.startedAt-5e3});if(!k)return;const S=Tl({entrySessionId:k.sessionId,entryInstanceId:k.instanceId,entryRouteId:k.id,conversations:n});S&&(m(null),i("done"),l(`${d.providerType} launched`),t(Jt(S)))},[n,r,t,d]),o.useEffect(()=>{if(!d)return;const h=window.setTimeout(()=>{m(k=>!k||k.startedAt!==d.startedAt?k:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[d]);const b=o.useCallback(async(h,k)=>{if(k.kind==="ide"&&k.providerType){await f(h,k.providerType,{workspacePath:k.workspace||null});return}(k.kind==="cli"||k.kind==="acp")&&k.providerType&&await y(h,k.kind,k.providerType,{workspacePath:k.workspace||null,resumeSessionId:k.providerSessionId||null})},[f,y]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:f,handleAddWorkspace:x,handleMachineUpgrade:C,handleLaunchWorkspaceProvider:y,handleListSavedSessions:p,handleBrowseDirectory:g,handleOpenRecent:b}}function Jx({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:d,setMachineBackTarget:m}){const u=o.useCallback(b=>{i(b.tabKey),c("chat"),n(b)},[n,c,i]),f=o.useCallback(b=>{const h=e.find(k=>k.routeId===b.routeId&&k.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),x=o.useCallback(()=>{n(t),c("inbox")},[n,t,c]),C=o.useCallback((b,h="inbox")=>{l(b),a(),d("machines"),m(h),c("machine")},[a,m,c,d,l]),y=o.useCallback(b=>{const h=bs(b);h&&C(h,"chat")},[C]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),g=o.useCallback(b=>{d(b),c("inbox")},[c,d]);return{openConversation:u,openNativeConversation:f,backFromConversation:x,openMachine:C,openConversationMachine:y,backFromMachine:p,changeMachineSection:g}}function hs(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function Qx(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Zx({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:C,onOpenHistory:y,onOpenRemote:p,onStopCli:g,wsStatus:b,isConnected:h,onShowAllHiddenConversations:k,onHideConversation:S,onOpenNewSession:j,liveSessionInboxState:A,setCliViewModeOverrides:M}){const[w,v]=o.useState(()=>{var Z;return((Z=e[0])==null?void 0:Z.tabKey)||null}),[B,_]=o.useState(()=>e[0]?"chat":"inbox"),[T,D]=o.useState("chats"),[K,L]=o.useState(null),[N,I]=o.useState("inbox"),F=o.useRef([]),P=$s(),$="0.9.75",H=o.useMemo(()=>e.find(Z=>Z.tabKey===w)||e[0]||null,[e,w]),J=o.useMemo(()=>H?r.find(Z=>Z.id===H.routeId):void 0,[r,H]),he=o.useMemo(()=>!H||Ze(H)||!tt(H)?null:Ks(H),[H]),ie=o.useMemo(()=>r.filter(Z=>Z.type==="adhdev-daemon").sort(Ga),[r]),te=o.useMemo(()=>ie.find(Z=>Z.id===K)||null,[ie,K]),be=bn({sendDaemonCommand:a,activeConv:H||void 0,setActionLogs:i,isStandalone:c}),we=Xx({sendDaemonCommand:a,navigate:P,ides:r,conversations:e}),ge=o.useMemo(()=>e.map(Z=>{const De=B==="chat"&&(H==null?void 0:H.tabKey)===Z.tabKey,$e=pn(Z,A,{hideOpenTaskCompleteUnread:!0,isOpenConversation:De}),Fe=ls(Z),Ue=Hc(Z);return{conversation:Z,timestamp:Fe,preview:Ue,unread:$e.unread,requiresAction:$e.requiresAction,isWorking:$e.isWorking,inboxBucket:$e.inboxBucket}}),[e,A,B,H]),{markConversationRead:X}=Gx({conversations:e,machineEntries:ie,items:ge,selectedConversation:H,selectedTabKey:w,screen:B,liveSessionInboxState:A,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:C,setSelectedTabKey:v,setScreen:_,setSelectedMachineId:L,setSection:D,setMachineBackTarget:I,resetMachineAction:we.resetMachineAction}),ce=Jx({conversations:e,selectedConversation:H,machineBackTarget:N,markConversationRead:X,resetMachineAction:we.resetMachineAction,setSelectedTabKey:v,setScreen:_,setSelectedMachineId:L,setSection:D,setMachineBackTarget:I}),ye=o.useMemo(()=>Ur(ge.filter(Z=>Z.requiresAction)),[ge]),ne=o.useMemo(()=>Ur(ge.filter(Z=>Z.unread&&!Z.requiresAction)),[ge]),de=o.useMemo(()=>Fx(ge.filter(Z=>!Z.unread&&!Z.requiresAction&&Z.isWorking),F.current),[ge]);o.useEffect(()=>{F.current=de.map(Z=>Z.conversation.tabKey)},[de]);const je=o.useMemo(()=>Ur(ge.filter(Z=>!Z.unread&&!Z.requiresAction&&!Z.isWorking)),[ge]),me=o.useMemo(()=>te?ge.filter(Z=>bs(Z.conversation)===te.id):[],[ge,te]),pe=o.useMemo(()=>Ux(te,r),[r,te]),ee=(te==null?void 0:te.version)||null,ue=!!te&&!!ee&&!0&&ee!==$,oe=o.useMemo(()=>(te==null?void 0:te.availableProviders)||[],[te]),q=o.useMemo(()=>oe.filter(Z=>hs(Z,"cli")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[oe]),V=o.useMemo(()=>oe.filter(Z=>hs(Z,"acp")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[oe]),le=o.useMemo(()=>zx(ie,ge),[ge,ie]),ke=o.useCallback(async Z=>{te&&await we.handleOpenRecent(te.id,Z)},[we,te]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:B==="chat"&&H?s.jsx(Lx,{selectedConversation:H,isAcp:Ze(H),isStandalone:c,selectedIdeEntry:J,actionLogs:n,userName:l,isSendingChat:be.isSendingChat,sendFeedbackMessage:be.sendFeedbackMessage,isFocusingAgent:be.isFocusingAgent,handleModalButton:be.handleModalButton,handleRelaunch:be.handleRelaunch,onBack:ce.backFromConversation,onOpenNativeConversation:ce.openNativeConversation,onOpenMachine:ce.openConversationMachine,onOpenHistory:y,onOpenRemote:p,onStopCli:g,cliViewMode:he,onSetCliViewMode:async Z=>{await hl({conversation:H,mode:Z,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:M})},handleSendChat:be.handleSendChat,handleFocusAgent:be.handleFocusAgent}):B==="machine"&&te?s.jsx(Ox,{selectedMachineEntry:te,selectedMachineConversations:me,selectedMachineRecentLaunches:pe,cliProviders:q,acpProviders:V,selectedMachineNeedsUpgrade:ue,appVersion:$,machineAction:we.machineAction,isStandalone:c,section:T,showBottomNav:N==="inbox",onBack:ce.backFromMachine,onSectionChange:ce.changeMachineSection,onOpenConversation:ce.openConversation,onOpenRecent:ke,onOpenMachineDetails:()=>P(`/machines/${te.id}`),onMachineUpgrade:()=>we.handleMachineUpgrade(te.id),onLaunchDetectedIde:(Z,De)=>we.handleLaunchDetectedIde(te.id,Z,De),onAddWorkspace:(Z,De)=>we.handleAddWorkspace(te.id,Z,De),onBrowseDirectory:Z=>we.handleBrowseDirectory(te.id,Z),onLaunchWorkspaceProvider:(Z,De,$e)=>we.handleLaunchWorkspaceProvider(te.id,Z,De,$e),onListSavedSessions:Z=>we.handleListSavedSessions(te.id,Z)}):s.jsx(Dx,{section:T,attentionItems:ye,unreadItems:ne,workingItems:de,completedItems:je,hiddenConversations:t,machineCards:le,getAvatarText:Qx,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ce.openConversation,onShowAllHidden:k,onHideConversation:S,onOpenNewSession:j,onOpenMachine:ce.openMachine,onOpenSettings:()=>P("/settings"),onSectionChange:D,wsStatus:b,isConnected:h,isStandalone:c})})}function Yn(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function eb({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,d]=o.useState(!1),[m,u]=o.useState(null),f=o.useCallback(()=>{c.current=0,d(!1),u(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const x=o.useCallback(g=>{g.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,d(!0))},[]),C=o.useCallback(g=>{if(!g.dataTransfer.types.includes("text/tab-key"))return;if(g.preventDefault(),!Yn(t,r)){u("merge");return}const b=g.currentTarget.getBoundingClientRect(),h=g.clientX-b.left,k=b.width/3;h<k?u("split-left"):h>k*2?u("split-right"):u("merge")},[t,r]),y=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,d(!1),u(null))},[]),p=o.useCallback(g=>{c.current=0,d(!1);const b=g.dataTransfer.getData("text/tab-key"),h=b?e.some(S=>S.tabKey===b):!1,k=m;if(u(null),i(),!!b){if(g.preventDefault(),k==="split-left"&&Yn(t,r)){r==null||r(b,"split-left");return}if(k==="split-right"&&Yn(t,r)){r==null||r(b,"split-right");return}if(h){a(b);return}n==null||n(b)}},[e,m,t,r,n,a,i]);return{dragOver:l,dropAction:m,resetDragState:f,handleDragEnter:x,handleDragOver:C,handleDragLeave:y,handleDrop:p}}function tb(e,t){const r=new Set(t.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=t.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function sb({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(t??null),[l,d]=o.useState(r??[]),[m,u]=o.useState(null),f=o.useRef(null),x=o.useRef(null),C=o.useRef(n),y=o.useRef(a);o.useEffect(()=>{C.current=n},[n]),o.useEffect(()=>{y.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{d(M=>{const w=tb(M,e);return w.length===M.length&&w.every((v,B)=>v===M[B])?M:w})},[e]);const p=o.useMemo(()=>{const M=m??l;if(M.length===0)return e;const w=new Map(M.map((v,B)=>[v,B]));return[...e].sort((v,B)=>{const _=w.get(v.tabKey)??999,T=w.get(B.tabKey)??999;return _-T})},[e,m,l]);o.useEffect(()=>{var w,v;if(p.length===0){i!==null&&(c(null),(w=C.current)==null||w.call(C,null));return}if(i&&p.some(B=>B.tabKey===i))return;const M=p[0].tabKey;M!==i&&(c(M),(v=C.current)==null||v.call(C,M))},[p,i]);const g=o.useMemo(()=>p.find(M=>M.tabKey===i),[p,i]),b=o.useCallback(M=>{var w;c(M),(w=C.current)==null||w.call(C,M)},[]),h=o.useCallback((M,w,v)=>{d(B=>{var K;const _=B.filter(L=>L!==M),T=_.indexOf(w);if(T<0)return B;const D=v==="left"?T:T+1;return _.splice(D,0,M),(K=y.current)==null||K.call(y,_),_}),u(null)},[]),k=o.useCallback((M,w,v)=>{const _=(l.length>0?l:e.map(K=>K.tabKey)).filter(K=>K!==M),T=_.indexOf(w);if(T<0)return;const D=v==="left"?T:T+1;_.splice(D,0,M),f.current=_,u(_)},[l,e]),S=o.useCallback(()=>{var w;const M=f.current;M&&(d(M),(w=y.current)==null||w.call(y,M))},[]),j=o.useCallback(()=>{f.current=null,u(null)},[]),A=o.useCallback(M=>{d(w=>{var B;const v=w.filter(_=>_!==M);return v.push(M),(B=y.current)==null||B.call(y,v),v})},[]);return{activeTabId:i,activeConv:g,sortedConversations:p,previewOrderRef:f,draggingTabRef:x,selectTab:b,handleTabReorder:h,updatePreviewOrder:k,commitPreviewOrder:S,clearPreviewOrder:j,moveTabToEnd:A,setDraggingTabKey:M=>{x.current=M}}}function rb({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 vo({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:i}){if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!r&&!n,l=n&&!!i,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?Gc: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:i,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:$t,"aria-label":$t,children:[s.jsx(ic,{size:14}),s.jsx("span",{children:$t})]})}),c&&s.jsx(Al,{}),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 _l="adhdev-tab-shortcuts";function Pl(){try{return JSON.parse(localStorage.getItem(_l)||"{}")}catch{return{}}}function Dl({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>Pl()),[l,d]=o.useState(null),m=o.useCallback(f=>{const x=[];return f.metaKey&&x.push(a?"⌘":"Meta"),f.ctrlKey&&x.push("Ctrl"),f.altKey&&x.push(a?"⌥":"Alt"),f.shiftKey&&x.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(x.push(f.key.length===1?f.key.toUpperCase():f.key),x.join("+"))},[a]),u=o.useCallback(f=>{c(f);try{localStorage.setItem(_l,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){d(null);return}const C=m(x);if(!C)return;const y={...i};for(const[p,g]of Object.entries(y))g===C&&delete y[p];y[l]=C,u(y),d(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,i,u,m]),o.useEffect(()=>{if(!e)return;const f=x=>{if(!(!x.ctrlKey&&!x.metaKey&&!x.altKey)){for(const[C,y]of Object.entries(i))if(t.includes(C)&&m(x)===y){x.preventDefault(),r(),n(C);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,i,t,r,n,m]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const Xn=e=>{e.preventDefault()},nb=o.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:f,onReorderTab:x,onCommitPreviewOrder:C,onClearPreviewOrder:y,onDragStateReset:p,onDragTabKeyChange:g,onReceiveTab:b,onOpenContextMenu:h,longPressTimer:k,isGroupActive:S}){const j=Bs(t),A=j.isGenerating?"agent-tab-generating":j.isWaiting?"agent-tab-waiting":"",M=j.isReconnecting,w=o.useCallback(I=>{l.current=t.tabKey,g(t.tabKey),I.dataTransfer.setData("text/tab-key",t.tabKey),I.dataTransfer.effectAllowed="move"},[t.tabKey,l,g]),v=o.useCallback(()=>{l.current=null,g(null),C(),y(),p()},[l,g,C,y,p]),B=o.useCallback(I=>{const F=l.current;if(!(!F||F===t.tabKey)&&I.dataTransfer.types.includes("text/tab-key")){I.preventDefault(),I.stopPropagation();const P=I.currentTarget.getBoundingClientRect(),$=I.clientX<P.left+P.width/2?"left":"right";f(F,t.tabKey,$)}},[t.tabKey,l,f]),_=o.useCallback(I=>{I.preventDefault(),I.stopPropagation();const F=I.dataTransfer.getData("text/tab-key");if(F&&F!==t.tabKey){const P=I.currentTarget.getBoundingClientRect(),$=I.clientX<P.left+P.width/2?"left":"right";c.includes(F)?x(F,t.tabKey,$):b&&b(F)}y()},[t.tabKey,c,x,b,y]),T=o.useCallback(I=>{I.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),D=o.useCallback(I=>{I.preventDefault(),h(I.clientX,I.clientY,t.tabKey)},[t.tabKey,h]),K=o.useCallback(I=>{const F=I.touches[0];k.current=setTimeout(()=>{h(F.clientX,F.clientY,t.tabKey)},600)},[t.tabKey,k,h]),L=o.useCallback(()=>{k.current&&clearTimeout(k.current)},[k]),N=["adhdev-dockview-tab",A,r&&"is-active",S&&"is-group-active",M&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:N,draggable:!0,onDragStart:w,onDragEnd:v,onDragOver:B,onDrop:_,onClick:T,onContextMenu:D,onTouchStart:K,onTouchEnd:L,onTouchMove:L,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:j.isGenerating?s.jsx("div",{className:"tab-spinner"}):j.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):M?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):j.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:lt(t),children:lt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[M?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:ns(t)}):j.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[ns(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:ns(t)}),s.jsx(_s,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),i&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function ab({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:C,onReceiveTab:y,onHideTab:p,isGroupActive:g,allowTabShortcuts:b=!0}){const[h,k]=o.useState(null),S=o.useRef(null),j=o.useRef(null),A=o.useMemo(()=>e.map(D=>D.tabKey),[e]);ur("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:M,tabShortcuts:w,shortcutListening:v,setShortcutListening:B,saveShortcuts:_}=Dl({enabled:b,sortedTabKeys:e.map(D=>D.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const D=K=>{const L=document.querySelector("[data-pane-context-menu]");L&&L.contains(K.target)||k(null)};return window.addEventListener("mousedown",D,!0),()=>window.removeEventListener("mousedown",D,!0)},[h]),o.useEffect(()=>{const D=j.current;if(!D)return;const K=L=>{Math.abs(L.deltaY)<=Math.abs(L.deltaX)||(L.preventDefault(),D.scrollLeft+=L.deltaY)};return D.addEventListener("wheel",K,{passive:!1}),()=>D.removeEventListener("wheel",K)},[]);const T=o.useCallback((D,K,L)=>{k({x:D,y:K,tabKey:L})},[]);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:j,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(D=>s.jsx(nb,{conv:D,isActive:t===D.tabKey,isDraggedTab:a.current===D.tabKey,isTaskCompleteUnread:n.has(D.tabKey),shortcut:b?w[D.tabKey]:void 0,conversationKeys:A,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:C,onReceiveTab:y,onOpenContextMenu:T,longPressTimer:S,isGroupActive:g},D.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),h&&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:h.x,top:h.y},children:[b&&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:Xn,onClick:D=>{D.stopPropagation(),B(h.tabKey),k(null)},children:["⌨ ",w[h.tabKey]?`Change shortcut (${w[h.tabKey]})`:"Set shortcut"]}),w[h.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:Xn,onClick:()=>{const D={...w};delete D[h.tabKey],_(D),k(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[b&&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:Xn,onClick:()=>{p(h.tabKey),k(null)},children:"🚫 Hide from Dashboard"})]})]}),b&&v&&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:D=>D.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. ",M?"⌘+1":"Ctrl+1",", ",M?"⌥+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 ob({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:d,groupIndex:m,onFocus:u,isSplitMode:f,numGroups:x,onMoveTab:C,onReceiveTab:y,style:p,onActiveTabChange:g,initialActiveTabId:b,initialTabOrder:h,onTabOrderChange:k,onHideTab:S,isFocused:j,allowTabShortcuts:A=!0,onOpenNewSession:M,liveSessionInboxState:w}){const{sendCommand:v}=gt(),B=o.useRef(null),{activeTabId:_,activeConv:T,sortedConversations:D,draggingTabRef:K,selectTab:L,handleTabReorder:N,updatePreviewOrder:I,commitPreviewOrder:F,clearPreviewOrder:P,moveTabToEnd:$,setDraggingTabKey:H}=sb({conversations:e,initialActiveTabId:b,initialTabOrder:h,onActiveTabChange:g,onTabOrderChange:k}),J=bn({sendDaemonCommand:a,activeConv:T,setActionLogs:i,isStandalone:c}),{dragOver:he,dropAction:ie,resetDragState:te,handleDragEnter:be,handleDragOver:we,handleDragLeave:ge,handleDrop:X}=eb({conversations:e,numGroups:x,onMoveTab:C,onReceiveTab:y,onOwnTabDrop:$,onClearPreviewOrder:P}),ce=T&&!Ze(T)&&Ks(T)==="terminal",ye=o.useMemo(()=>T?t.find(me=>me.id===T.routeId):void 0,[t,T]),ne=o.useMemo(()=>T?n.filter(me=>me.routeId===T.tabKey):[],[n,T]),de=o.useMemo(()=>new Set(D.filter(me=>Zu(me,w,{isOpenConversation:me.tabKey===_})).map(me=>me.tabKey)),[_,w,D]);ur("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:_,dragOver:he});const je=o.useCallback(me=>{me.streamSource==="agent-stream"&&me.agentType&&v(me.routeId,Ac(),{agentType:me.agentType,...me.sessionId&&{targetSessionId:me.sessionId}}).catch(()=>{})},[v]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...p,outline:he?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(ab,{conversations:D,activeTabId:_,groupIndex:m,numGroups:x,unreadTabKeys:de,draggingTabRef:K,onFocus:u,onSelectTab:L,onConversationActivated:je,onPreviewReorder:I,onReorderTab:N,onCommitPreviewOrder:F,onClearPreviewOrder:P,onDragStateReset:te,onDragTabKeyChange:H,onMoveTab:C,onReceiveTab:y,onHideTab:S,isGroupActive:j??!1,allowTabShortcuts:A}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:be,onDragOver:we,onDragLeave:ge,onDrop:X,children:[he&&s.jsx(rb,{dropAction:ie,canSplit:!!(x<4&&C)}),T?s.jsx(go,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!ce,ideEntry:ye,terminalRef:B,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:ne,userName:d,isInputActive:!f||!!j}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(vo,{conversationsCount:e.length,isSplitMode:f,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:M})})]})]})}function ib({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:f,userName:x,focusedGroup:C,focusGroup:y,moveTabToGroup:p,splitTabRelative:g,closeGroup:b,handleResizeStart:h,groupActiveTabIds:k,setGroupActiveTab:S,groupTabOrders:j,setGroupTabOrder:A,toggleHiddenTab:M,onOpenNewSession:w,allowTabShortcuts:v=!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 D=t&&n.length===r?`${n[T]}%`:void 0;return s.jsxs(Ct.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:K=>h(T-1,K),onDoubleClick:()=>b(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(ob,{style:t?{flexBasis:D??`${100/r}%`,flexGrow:D?0:1,flexShrink:D?0:1}:void 0,conversations:_,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:f,userName:x,groupIndex:T,isFocused:t&&C===T,onFocus:()=>y(T),isSplitMode:t,numGroups:r,onMoveTab:(K,L)=>{L==="left"&&T>0?p(K,T-1):L==="right"&&T<r-1?p(K,T+1):L==="split-left"&&r<4?g(K,T,"left"):L==="split-right"&&r<4&&g(K,T,"right")},onReceiveTab:K=>p(K,T),onActiveTabChange:K=>S(T,K),initialActiveTabId:k[T],initialTabOrder:j[T],onTabOrderChange:K=>A(T,K),onHideTab:M,onOpenNewSession:w,allowTabShortcuts:v,liveSessionInboxState:B})]},T)})})}function El({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?ut.onScreenshot("ide-page",(u,f)=>{if(u!==e)return;const x=new FileReader;x.onload=()=>i(x.result),x.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var u;return e?((u=ut.onStatus)==null?void 0:u.call(ut,(f,x)=>{f===e&&x!=null&&x.screenshotUsage&&l(x.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,t]),o.useEffect(()=>{const m=e?ut.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=o.useCallback(async(m,u)=>{const f=e?ut.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 $l="adhdev-dashboard-action-shortcuts",cb=1200,lb=[["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 db(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function nt(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 Bl(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:nt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:nt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:nt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:nt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:nt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:nt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:nt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:nt("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:nt("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:nt("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:nt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:nt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:nt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:nt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:nt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:nt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:nt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:nt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:nt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:nt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:nt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:nt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:nt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:nt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:nt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:nt("toggleCliView",e)}]}function Ra(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function ln(e){const t=Object.fromEntries(Bl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem($l)||"{}"),n={...t,...r};for(const[a,i]of lb)n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function Kl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function ub({enabled:e=!0,onTrigger:t}){const r=db(),[n,a]=o.useState(()=>ln(r)),[i,c]=o.useState(null),[l,d]=o.useState([]),m=o.useRef({parts:[],timer:null}),u=o.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(Kl(p.key)),g.join("+"))},[r]),f=o.useCallback(p=>{a(p);try{localStorage.setItem($l,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=ln(r),g=Object.entries(n),b=Object.entries(p);g.length===b.length&&g.every(([h,k])=>p[h]===k)||f(p)},[n,r,f]);const x=o.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),C=o.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},cb))},[]);o.useEffect(()=>{if(!i)return;const p=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){c(null),d([]);return}const b=u(g);if(!b)return;const k=!(g.metaKey||g.ctrlKey||g.altKey)&&/^[A-Z0-9]$/.test(b);if(l.length===0&&k){d([b]);return}const j=[...l,b].slice(0,2).join(" "),A={...n};for(const[M,w]of Object.entries(A))w===j&&delete A[M];A[i]=j,f(A),c(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,u,f,i,l]),o.useEffect(()=>{if(!e||i)return;const p=g=>{if(g.defaultPrevented)return;const b=u(g);if(!b)return;const h=g.metaKey||g.ctrlKey||g.altKey;if(Ra(g.target))return;const k=m.current.parts,S=h?[b]:[...k.slice(-1),b].slice(-2),j=S.join(" "),A=S[S.length-1],M=Object.entries(n).filter(([,T])=>!!T),w=M.find(([,T])=>T===j);if(w){g.preventDefault(),x(),t(w[0]);return}if(M.some(([,T])=>T.startsWith(`${j} `))){g.preventDefault(),m.current.parts=S,C();return}const B=M.find(([,T])=>T===A);if(B){g.preventDefault(),x(),t(B[0]);return}if(M.some(([,T])=>T.startsWith(`${A} `))){g.preventDefault(),m.current.parts=[A],C();return}x()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,C,e,u,t,x,i]),o.useEffect(()=>()=>x(),[x]);const y=o.useMemo(()=>Bl(r),[r]);return{isMac:r,actionDefinitions:y,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:f}}function mb({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 Wl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Si({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!Wl(n):!0}function fb({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:Wl(r)}const Ol=1e3,pb=4;function Ni(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Ci(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function hb({detachDelayMs:e=Ol,stillnessThresholdPx:t=pb,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let i=null,c=null,l=null,d=null,m=null,u=!1;const f=()=>{m!=null&&(a(m),m=null)},x=()=>{f(),l=null},C=()=>{f(),i=null,c=null,l=null,d=null,u=!1},y=()=>{!i||!l||!d||u||m!=null||(m=n(()=>{m=null,!(!i||!l||!d||u)&&Ni(d,c)&&(Ci(l,d,t)||(u=!0,r({panelId:i,clientX:d.clientX,clientY:d.clientY})))},e))},p=b=>{if(!(!i||u)){if(!Ni(b,c)){d={clientX:b.clientX,clientY:b.clientY},x();return}(!l||Ci(l,b,t))&&(f(),l={clientX:b.clientX,clientY:b.clientY}),d={clientX:b.clientX,clientY:b.clientY},y()}},g=b=>{!i||u||(b&&(d={clientX:b.clientX,clientY:b.clientY}),x())};return{startDrag:b=>{f(),i=b.panelId,c=b.selfPanelBounds??null,l=null,d={clientX:b.clientX,clientY:b.clientY},u=!1},markSelfPanel:p,markNonSelfPanel:g,markNoDropTarget:g,markDockTarget:g,endDrag:C,isDragging:()=>i!=null,hasDetached:()=>u,dispose:C}}function xb(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Dr(e){return e.isActive}function Ti(e){return e.isVisible}const Fl=o.createContext(null);function jn(){const e=o.useContext(Fl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function zr(e){return lt(e)||e.tabKey}function bb(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function Mi(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function gb(e){e.preventDefault()}function Jn(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 Qn(e,t){e.classList.remove(ma.className,fa.className),e.classList.add(t==="light"?ma.className:fa.className)}function Ai(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 yb(e){const[,t]=o.useState(0);o.useEffect(()=>{const r=()=>t(a=>a+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const a of n)a.dispose()}},[e.api,e.containerApi])}function vb(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:zr(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 Ii(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])Lt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==zr(n)&&a.api.setTitle(zr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:zr(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function Ri(e,t,r){var d,m;const n=r?bb(r):null;for(const u of[...e.panels])Lt(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 i=e.getPanel(n),c=Vc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((m=e.panels.find(u=>!Lt(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 wb({params:e,api:t}){var C;const r=jn(),n=o.useRef(null),[a,i]=o.useState(()=>Dr(t)),[c,l]=o.useState(()=>Ti(t)),d=r.conversationsByTabKey.get(e.tabKey),m=bn({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(Dr(t)),l(Ti(t));const y=[t.onDidActiveChange(p=>i(p.isActive)),t.onDidActiveGroupChange(p=>{if(!Dr(t)&&!p.isActive){i(!1);return}i(Dr(t))}),t.onDidVisibilityChange(p=>l(p.isVisible))];return()=>{for(const p of y)p.dispose()}},[t]);const u=o.useMemo(()=>d?r.ides.find(y=>y.id===d.routeId):void 0,[r.ides,d]),f=o.useMemo(()=>d?r.actionLogs.filter(y=>y.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(vo,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const x=!Ze(d)&&Ks(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(go,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:x,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:((C=r.scrollToBottomRequest)==null?void 0:C.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:c})})}function jb({params:e}){var d;const t=jn(),r=o.useMemo(()=>Dt([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=El({doId:a,targetSessionId:r?Mc(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(fc,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:l})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function kb(){const e=jn();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(vo,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Sb(e){var C,y;yb(e);const t=jn(),r=o.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=((C=e.api.group.activePanel)==null?void 0:C.id)===e.api.id,b=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${g?" is-active":""}${b?" 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=((y=e.api.group.activePanel)==null?void 0:y.id)===e.api.id,i=e.api.isGroupActive,c=pn(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,d=c.isConnecting,m=c.isGenerating,u=c.isWaiting,f=c.unread,x=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:lt(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:lt(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ns(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ns(n)}):s.jsx("span",{children:ns(n)})})]}),x&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:x,children:x})]})}function Nb({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:f,registerActionHandlers:x,onActiveTabChange:C,onOpenNewSession:y,onRequestScrollToBottom:p,requestedActiveTabKey:g,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:h,scrollToBottomRequest:k,liveSessionInboxState:S,layoutProfile:j}){var Je,Ge,rt;const{theme:A}=lo(),{sendCommand:M}=gt(),w=o.useRef(null),v=o.useRef(null),B=o.useRef(null),_=o.useRef(!1),T=o.useRef(!1),D=o.useRef(!1),K=o.useRef(null),L=o.useRef([]),[N,I]=o.useState(null),[F,P]=o.useState(0),$=o.useRef(typeof window>"u"?{}:zh(j)),H=o.useMemo(()=>new Map(e.map(O=>[O.tabKey,O])),[e]),J=o.useMemo(()=>{const O=w.current;return O?O.groups.some(U=>{try{const G=U.model.location.type;return G!=="floating"&&G!=="popout"?!1:U.panels.some(se=>H.has(se.id))}catch{return!1}}):!1},[H,F,e]),he=o.useCallback(()=>{var O;(O=w.current)==null||O.focus()},[]),ie=o.useCallback((O,U)=>{p==null||p(O,U)},[p]),te=o.useCallback(O=>{const U=document,G=O.document;for(const re of U.querySelectorAll('link[rel="stylesheet"]')){const ve=G.createElement("link");ve.rel="stylesheet",ve.href=re.href,re.crossOrigin&&(ve.crossOrigin=re.crossOrigin),G.head.appendChild(ve)}for(const re of U.querySelectorAll("style")){const ve=G.createElement("style");ve.textContent=re.textContent,G.head.appendChild(ve)}const se=[];for(const re of U.styleSheets)try{for(const ve of re.cssRules)ve instanceof CSSStyleRule&&(ve.selectorText===":root"||ve.selectorText==="html")&&se.push(ve.cssText)}catch{}if(se.length>0){const re=G.createElement("style");re.textContent=se.join(`
52
+ `),G.head.appendChild(re)}const E=U.documentElement.getAttribute("data-theme");E&&G.documentElement.setAttribute("data-theme",E),G.documentElement.style.colorScheme=E==="light"?"light":"dark",G.body.className=U.body.className;const Y=U.documentElement.getAttribute("style");Y&&G.documentElement.setAttribute("style",Y);const Q=G.getElementById("dv-popout-window");Q instanceof HTMLElement&&(Q.classList.add("adhdev-dockview"),Qn(Q,A))},[A]),be=o.useCallback(()=>{var U;const O=w.current;if(O)for(const G of O.groups)try{const se=(U=G.element)==null?void 0:U.ownerDocument;if(!se||se===document)continue;const E=se.getElementById("dv-popout-window");E instanceof HTMLElement&&(E.classList.add("adhdev-dockview"),Qn(E,A));const Y=document.documentElement.getAttribute("data-theme");Y&&se.documentElement.setAttribute("data-theme",Y),se.documentElement.style.colorScheme=Y==="light"?"light":"dark",se.body.className=document.body.className;const Q=document.documentElement.getAttribute("style");Q?se.documentElement.setAttribute("style",Q):se.documentElement.removeAttribute("style")}catch{}},[A]),we=o.useCallback(O=>{const U=w.current;if(!U)return;const G=U.getPanel(O);G&&U.addPopoutGroup(G,{popoutUrl:"/popout.html",onDidOpen:({window:se})=>{te(se),pe();const E=H.get(O);se.document.title=E?`${lt(E)} — ADHDev`:"ADHDev — Popout"}})},[H,te]),ge=o.useCallback(O=>{const U=w.current,G=U==null?void 0:U.getPanel(O);if(!U||!G)return;const se=U.groups.filter(E=>{var Y;try{return((Y=E.element)==null?void 0:Y.ownerDocument)===document}catch{return!0}});se.length>0?G.api.moveTo({group:se[0],position:"center"}):G.api.moveTo({position:"center"}),G.api.setActive()},[]),X=o.useCallback(O=>{var se;const U=w.current;if(!U)return!1;const G=U.getPanel(O);if(!G)return!1;try{return((se=G.group.element)==null?void 0:se.ownerDocument)!==document}catch{return!1}},[]),ce=o.useCallback(O=>{X(O)&&ge(O),u(O)},[X,ge,u]),ye=o.useCallback(O=>{const U=w.current,G=U==null?void 0:U.getPanel(O);!U||!G||U.addFloatingGroup(G,{width:600,height:500})},[]),ne=o.useCallback(O=>{var G;const U=(G=w.current)==null?void 0:G.getPanel(O);if(!U)return!1;try{return U.group.model.location.type==="floating"}catch{return!1}},[]),de=o.useCallback(()=>{var U,G;const O=(G=(U=w.current)==null?void 0:U.activePanel)==null?void 0:G.id;return!O||Lt(O)?null:H.has(O)?O:null},[H]),je=o.useCallback(O=>{const U=w.current,G=U==null?void 0:U.getPanel(O);if(!U||!G)return;const se=U.groups.filter(E=>{try{return E.model.location.type==="grid"}catch{return!0}});se.length>0?G.api.moveTo({group:se[0],position:"center"}):G.api.moveTo({position:"center"}),G.api.setActive()},[]),me=o.useCallback(()=>{var Y;const O=w.current;if(!O)return;const G=O.groups.filter(Q=>{var re;try{return((re=Q.element)==null?void 0:re.ownerDocument)===document&&Q.model.location.type==="grid"}catch{return!1}})[0]||null,se=[...O.panels];for(const Q of se){const re=(Y=Q.group.element)==null?void 0:Y.ownerDocument,ve=Q.group.model.location.type;re===document&&ve==="grid"||(G&&G.id!==Q.group.id?Q.api.moveTo({group:G,position:"center"}):Q.api.moveTo({position:"center"}))}const E=O.activePanel;E&&(E.group.model.openPanel(E),E.api.setActive()),Jn(document)},[]),pe=o.useCallback(()=>{var U,G;const O=w.current;if(O)for(const se of O.groups){const E=(U=se.element)==null?void 0:U.ownerDocument;if(!E||E===document)continue;const Y=E.getElementById("dv-popout-window");if(!(Y instanceof HTMLElement))continue;let Q=null,re=E.title||"ADHDev",ve="Popout workspace";const Ie=se.activePanel;if(Ie)if(Q=Ie.id,Lt(Ie.id)){const Ae=((G=Ie.params)==null?void 0:G.routeId)||Ie.id.slice(7),qe=Dt([...H.values()],Ae);re=Vc(qe),ve=qe!=null&&qe.machineName?`Remote view · ${qe.machineName}`:"Remote view"}else{const Ae=H.get(Ie.id);re=Ae?lt(Ae):Ie.title||Ie.id,ve=Ae?ns(Ae):"Dockview panel"}E.title=`${re} — ADHDev`;const Le=Array.from(E.querySelectorAll("#adhdev-popout-header"));for(const Ae of Le)Ae.remove();const Se=E.createElement("div");Se.id="adhdev-popout-header",E.body.appendChild(Se),Se.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(";")),Se.innerHTML=`
53
53
  <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
54
54
  <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
55
- <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Ci(re)}</div>
56
- <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Ci(ve)}</div>
55
+ <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Mi(re)}</div>
56
+ <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Mi(ve)}</div>
57
57
  </div>
58
58
  <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
59
59
  <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>
60
60
  <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>
61
61
  </div>
62
- `,Y.style.top="52px",Y.style.height="calc(100% - 52px)";const Pe=Se.querySelector("[data-adhdev-popout-focus]");Pe&&(Pe.onclick=()=>{window.focus()});const Ee=Se.querySelector("[data-adhdev-popout-dock]");Ee&&(Ee.disabled=!Q,Ee.style.opacity=Q?"1":"0.5",Ee.style.cursor=Q?"pointer":"default",Ee.onclick=()=>{var Ae;Q&&ge(Q),(Ae=E.defaultView)==null||Ae.focus()})}},[H,ge]),ee=o.useCallback(F=>{var se;const U=w.current,G=U==null?void 0:U.getPanel(F);if(!(!U||!G)){G.group.model.openPanel(G),G.api.setActive(),ie(F,"dockview-shortcut");try{const E=G.group.model.location;E.type==="popout"?E.getWindow().focus():Xn((se=G.group.element)==null?void 0:se.ownerDocument)}catch{}}},[ie]),ue=o.useCallback(F=>{const U=w.current,G=U==null?void 0:U.activePanel,se=(U==null?void 0:U.activeGroup)||(G==null?void 0:G.group);if(!U||!G||!se)return;const E=se.panels||[];if(E.length<=1)return;const Y=E.findIndex(ve=>ve.id===G.id);if(Y<0)return;const Q=(Y+F+E.length)%E.length,re=E[Q];re&&(re.group.model.openPanel(re),re.api.setActive(),Lt(re.id)||ie(re.id,"dockview-shortcut"))},[ie]),oe=o.useCallback(F=>{var Pe;const U=w.current,G=(U==null?void 0:U.activeGroup)||((Pe=U==null?void 0:U.activePanel)==null?void 0:Pe.group);if(!U||!G)return;const se=U.groups||[],E=se.find(Ee=>Ee.id===G.id);if(!E)return;const Y=E.element.getBoundingClientRect(),Q=Y.left+Y.width/2,re=Y.top+Y.height/2,ve=(Ee,Ae,qe,et)=>Math.max(0,Math.min(Ae,et)-Math.max(Ee,qe)),Ie=Ee=>{const Ae=Ee.element.getBoundingClientRect(),qe=Ae.left+Ae.width/2,et=Ae.top+Ae.height/2;let ct=0,ft=0,dt=0,gt=!1;if(F==="left"?(gt=qe<Q,ct=Math.max(0,Y.left-Ae.right),ft=Math.abs(et-re),dt=ve(Y.top,Y.bottom,Ae.top,Ae.bottom)):F==="right"?(gt=qe>Q,ct=Math.max(0,Ae.left-Y.right),ft=Math.abs(et-re),dt=ve(Y.top,Y.bottom,Ae.top,Ae.bottom)):F==="above"?(gt=et<re,ct=Math.max(0,Y.top-Ae.bottom),ft=Math.abs(qe-Q),dt=ve(Y.left,Y.right,Ae.left,Ae.right)):(gt=et>re,ct=Math.max(0,Ae.top-Y.bottom),ft=Math.abs(qe-Q),dt=ve(Y.left,Y.right,Ae.left,Ae.right)),!gt)return Number.POSITIVE_INFINITY;const Ve=dt>0?0:120;return ct*3+ft+Ve};let Le=null,Se=Number.POSITIVE_INFINITY;for(const Ee of se){if(Ee.id===E.id)continue;const Ae=Ie(Ee);Number.isFinite(Ae)&&(Ae>=Se||(Se=Ae,Le=Ee))}return Le||void 0},[]),q=o.useCallback(F=>{var se;const U=oe(F);if(!U)return;const G=U.activePanel||U.panels[0];G&&(U.model.openPanel(G),G.api.setActive(),Lt(G.id)||ie(G.id,"dockview-focus"),Xn((se=U.element)==null?void 0:se.ownerDocument))},[oe,ie]),V=o.useCallback((F,U)=>{const G=w.current,se=G==null?void 0:G.activePanel,E=(G==null?void 0:G.activeGroup)||(se==null?void 0:se.group);if(!G||!se||!E)return;let Y=oe(F);!Y&&(U!=null&&U.createGroupIfMissing)&&(Y=G.addGroup({referenceGroup:E,direction:F})),Y&&(se.api.moveTo({group:Y,position:"center"}),se.group.model.openPanel(se),se.api.setActive(),Lt(se.id)||ie(se.id,U!=null&&U.createGroupIfMissing?"dockview-split":"dockview-move"))},[oe,ie]),{isMac:le,tabShortcuts:ke,shortcutListening:Z,setShortcutListening:De,saveShortcuts:$e}=Pl({sortedTabKeys:e.map(F=>F.tabKey),onFocus:he,onSelectTab:ee}),Fe=o.useCallback(()=>{var G;const F=w.current;if(!F)return;const U=F.activePanel;if(U){if(Lt(U.id)){const se=((G=U.params)==null?void 0:G.routeId)||U.id.slice(7),E=Dt(e,se);E!=null&&E.tabKey&&De(E.tabKey);return}H.has(U.id)&&De(U.id)}},[H,ee,De,e]),Ue=o.useCallback(F=>{const U=[];return F.metaKey&&U.push(le?"⌘":"Meta"),F.ctrlKey&&U.push("Ctrl"),F.altKey&&U.push(le?"⌥":"Alt"),F.shiftKey&&F.key.length!==1&&U.push(le?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(F.key)?null:(U.push(Bl(F.key)),U.join("+"))},[le]),O=o.useCallback(F=>{var U,G;switch(F){case"splitActiveTabRight":V("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":V("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const se=de();se&&ye(se);return}case"popoutActiveTab":{const se=de();se&&we(se);return}case"dockActiveTab":{const se=de();if(!se)return;X(se)?ge(se):ne(se)&&je(se);return}case"focusLeftPane":q("left");return;case"focusRightPane":q("right");return;case"focusUpPane":q("above");return;case"focusDownPane":q("below");return;case"moveActiveTabToLeftPane":V("left");return;case"moveActiveTabToRightPane":V("right");return;case"moveActiveTabToUpPane":V("above");return;case"moveActiveTabToDownPane":V("below");return;case"selectPreviousGroupTab":ue(-1);return;case"selectNextGroupTab":ue(1);return;case"setActiveTabShortcut":Fe();return;case"hideCurrentTab":{const se=(G=(U=w.current)==null?void 0:U.activePanel)==null?void 0:G.id;se&&!Lt(se)&&ce(se);return}default:return}},[ue,je,q,ye,de,ce,ne,X,ge,V,we,Fe]);o.useEffect(()=>{if(!N)return;const F=N.sourceDocument,U=F.defaultView??window,G=se=>{const E=F.querySelector("[data-dockview-tab-context-menu]");E&&E.contains(se.target)||I(null)};return U.addEventListener("mousedown",G,!0),U!==window&&window.addEventListener("mousedown",()=>I(null),!0),()=>{U.removeEventListener("mousedown",G,!0),U!==window&&window.removeEventListener("mousedown",()=>I(null),!0)}},[N]);const Ce=o.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:H,hasDetachedConversationPanels:J,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:g,liveSessionInboxState:S,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:ce,userName:m,scrollToBottomRequest:y,tabShortcuts:ke,openTabContextMenu:({x:F,y:U,tabKey:G,sourceDocument:se})=>I({x:F,y:U,tabKey:G,sourceDocument:se??document}),popoutTab:we,moveTabBackToMain:ge,isTabInPopout:X,floatTab:ye,isTabFloating:ne}),[n,t,H,J,r,c,l,g,S,a,i,ce,m,y,ke,we,ge,X,ye,ne]),Te=N?db({isTabInPopout:X(N.tabKey),isTabFloating:ne(N.tabKey),tabShortcut:ke[N.tabKey],actionShortcuts:f}):[],_e=o.useCallback(F=>{var se;const U=w.current;if((((se=U==null?void 0:U.activePanel)==null?void 0:se.id)??null)===F.id){F.group.model.openPanel(F);return}F.group.model.openPanel(F),F.api.setActive()},[]),Be=o.useCallback((F,U="requested-tab")=>{if(!F)return!1;const G=w.current;if(!G)return!1;const se=G.getPanel(F);return se?(_e(se),ie(F,U),h==null||h(),!0):!1},[_e,h,ie]),He=o.useCallback(()=>{if(D.current)return!1;const F=Be(K.current,"stored-layout-restore");return F&&(D.current=!0),F},[Be]),Xe=o.useCallback(()=>{var U;const F=w.current;F&&Fh(k,{activeTabId:((U=F.activePanel)==null?void 0:U.id)??null,layout:F.toJSON()})},[k]),st=o.useCallback(()=>{Uh(k,$.current)},[k]),mt=o.useCallback(F=>{var se,E,Y,Q;const U=w.current;if(!U)return{kind:"grid"};const G=U.toJSON();for(const re of G.floatingGroups||[])if((E=(se=re.data)==null?void 0:se.views)!=null&&E.includes(F)&&re.position)return{kind:"floating",position:re.position};for(const re of G.popoutGroups||[])if((Q=(Y=re.data)==null?void 0:Y.views)!=null&&Q.includes(F))return{kind:"popout",position:re.position,popoutUrl:re.url};return{kind:"grid"}},[]),ht=o.useCallback(F=>{const U=w.current;if(!U)return;const G=U.getPanel(F),se=$.current[F];if(!G||!se||se.kind==="grid")return;if(G.group.model.location.type===se.kind){delete $.current[F],st();return}if(se.kind==="floating"){U.addFloatingGroup(G,{x:se.position.left??24,y:se.position.top??24,width:se.position.width,height:se.position.height}),delete $.current[F],st();return}delete $.current[F],st()},[st]);o.useEffect(()=>(x==null||x({setShortcutForActiveTab:Fe,restoreHiddenTabToSavedLocation:ht,activateConversationTab:ee,resetAllPanelsToMain:me,activatePreviousTabInGroup:()=>ue(-1),activateNextTabInGroup:()=>ue(1),floatActiveTab:()=>{const F=de();F&&ye(F)},popoutActiveTab:()=>{const F=de();F&&we(F)},dockActiveTab:()=>{const F=de();F&&(X(F)?ge(F):ne(F)&&je(F))},splitActiveTabRight:()=>V("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>V("below",{createGroupIfMissing:!0}),focusLeftPane:()=>q("left"),focusRightPane:()=>q("right"),focusUpPane:()=>q("above"),focusDownPane:()=>q("below"),moveActiveTabToLeftPane:()=>V("left"),moveActiveTabToRightPane:()=>V("right"),moveActiveTabToUpPane:()=>V("above"),moveActiveTabToDownPane:()=>V("below")}),()=>x==null?void 0:x(null)),[ue,je,ye,q,de,ne,X,V,ge,we,x,me,ht,ee,Fe]),o.useEffect(()=>()=>{var F;(F=B.current)==null||F.call(B),B.current=null},[]);const xt=o.useCallback(F=>{var G,se;w.current=F.api,(G=B.current)==null||G.call(B),B.current=null;const U=Oh(k);if(K.current=(U==null?void 0:U.activeTabId)??null,U!=null&&U.layout&&F.api.fromJSON(U.layout,{reuseExistingPanels:!1}),T.current=ji({hasStoredLayout:!!(U!=null&&U.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),T.current||(Mi(F.api,e),Ai(F.api,e,b)),F.api.totalPanels===0&&e.length>0){const E=gb(F.api,e,j);if(E){const Y=F.api.getPanel(E);Y&&_e(Y)}}else!T.current&&!Be(j)&&He();if(_.current=!0,F.api.onDidActivePanelChange(E=>{var Q;if(K.current=(E==null?void 0:E.id)??null,D.current=!0,pe(),E&&Lt(E.id)){const re=((Q=E.params)==null?void 0:Q.routeId)||E.id.slice(7),ve=Dt(e,re);C((ve==null?void 0:ve.tabKey)??null),Xe();return}if(C((E==null?void 0:E.id)??null),Xe(),!E)return;const Y=H.get(E.id);(Y==null?void 0:Y.streamSource)==="agent-stream"&&Y.agentType&&M(Y.routeId,Mc(),{agentType:Y.agentType,...Y.sessionId&&{targetSessionId:Y.sessionId}}).catch(()=>{})}),F.api.onDidLayoutChange(()=>{Xe(),pe(),P(E=>E+1)}),pb()){const E=Se=>({clientX:Se.clientX,clientY:Se.clientY}),Y=Se=>{const Pe=Se==null?void 0:Se.getBoundingClientRect();return Pe?{left:Pe.left,right:Pe.right,top:Pe.top,bottom:Pe.bottom}:null},Q=Se=>{var Ee;const Pe=(Ee=v.current)==null?void 0:Ee.getBoundingClientRect();return Pe?Se.clientX<Pe.left||Se.clientX>Pe.right||Se.clientY<Pe.top||Se.clientY>Pe.bottom:!1},re=fb({detachDelayMs:Wl,onDetach:({panelId:Se,clientX:Pe,clientY:Ee})=>{var dt,gt;const Ae=F.api.getPanel(Se);if(!Ae)return;try{if(Ae.group.model.location.type!=="grid")return}catch{return}const qe=(dt=v.current)==null?void 0:dt.getBoundingClientRect(),et=(gt=Ae.group.element)==null?void 0:gt.getBoundingClientRect(),ct=Math.round(Math.min(Math.max((et==null?void 0:et.width)??600,360),720)),ft=Math.round(Math.min(Math.max((et==null?void 0:et.height)??500,260),640));F.api.addFloatingGroup(Ae,{x:qe?Math.max(0,Pe-qe.left-32):void 0,y:qe?Math.max(0,Ee-qe.top-18):void 0,width:ct,height:ft}),Ae.api.setActive(),Xe(),pe(),P(Ve=>Ve+1)}}),ve=[F.api.onWillDragPanel(Se=>{if(!(Se.nativeEvent.defaultPrevented||Se.nativeEvent.shiftKey)){try{if(Se.panel.group.model.location.type!=="grid")return}catch{return}re.startDrag({panelId:Se.panel.id,selfPanelBounds:Y(Se.panel.group.element),...E(Se.nativeEvent)})}}),F.api.onWillShowOverlay(Se=>{if(re.hasDetached()){Se.preventDefault();return}re.markDockTarget(E(Se.nativeEvent))}),F.api.onWillDrop(Se=>{if(re.hasDetached()){Se.preventDefault(),re.endDrag();return}re.markDockTarget(E(Se.nativeEvent))}),F.api.onDidDrop(()=>re.endDrag()),F.api.onUnhandledDragOverEvent(Se=>{re.isDragging()&&re.markSelfPanel(E(Se.nativeEvent))})],Ie=Se=>{if(!re.isDragging())return;const Pe=E(Se);Q(Pe)&&re.markNonSelfPanel(Pe)},Le=()=>re.endDrag();window.addEventListener("dragover",Ie,!0),window.addEventListener("drop",Le,!0),window.addEventListener("dragend",Le,!0),B.current=()=>{re.dispose();for(const Se of ve)Se.dispose();window.removeEventListener("dragover",Ie,!0),window.removeEventListener("drop",Le,!0),window.removeEventListener("dragend",Le,!0)}}F.api.onDidAddGroup(E=>{requestAnimationFrame(()=>{var Y,Q;try{const re=(Y=E.element)==null?void 0:Y.ownerDocument;if(!re||re===document)return;(Q=re.getElementById("dv-popout-window"))==null||Q.classList.add("adhdev-dockview");const ve=document.documentElement.getAttribute("data-theme");ve&&re.documentElement.setAttribute("data-theme",ve),re.body.className=document.body.className;const Ie=document.documentElement.getAttribute("style");Ie&&re.documentElement.setAttribute("style",Ie)}catch{}pe(),P(re=>re+1)})}),C(((se=F.api.activePanel)==null?void 0:se.id)??null)},[_e,Be,H,r,d,k,C,Xe,j,b,M,pe,e]);o.useLayoutEffect(()=>{const F=w.current;if(!F||!_.current||T.current&&ji({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const U=L.current,G=new Set(U),se=e.map(Le=>Le.tabKey),E=new Set(se),Y=ub({previousVisibleConversationCount:U.length,visibleConversationCount:e.length,ides:r});let Q=!1;for(const Le of U)E.has(Le)||Y||($.current[Le]=mt(Le),Q=!0);Q&&st(),Y||(Mi(F,e),Ai(F,e,b));const re=se.filter(Le=>!G.has(Le));let ve=!1;for(const Le of re){const Se=F.getPanel(Le),Pe=$.current[Le];if(!Se||!Pe||Pe.kind==="grid")continue;if(Se.group.model.location.type===Pe.kind){delete $.current[Le],ve=!0;continue}if(Pe.kind==="floating"){F.addFloatingGroup(Se,{x:Pe.position.left??24,y:Pe.position.top??24,width:Pe.position.width,height:Pe.position.height}),delete $.current[Le],ve=!0;continue}}if(ve&&st(),L.current=se,j&&Be(j))return;!F.activePanel&&F.panels[0]&&_e(F.panels[0]),!!(F.activePanel&&F.getPanel(F.activePanel.id))||He()},[_e,Be,He,r,d,st,mt,j,b,e]),o.useEffect(()=>{_.current&&Be(j)},[Be,j]),o.useEffect(()=>{const F=G=>{const se=G.target;if(!se)return;const E=se.querySelector("[data-tab-key]")||se.closest("[data-tab-key]");if(E){const Y=E.getAttribute("data-tab-key");if(Y&&G.dataTransfer){const Q=se.closest(".dv-tab")||E.closest(".dv-tab")||E;G.dataTransfer.effectAllowed="move",G.dataTransfer.setData("text/tab-key",Y),Q instanceof HTMLElement&&G.dataTransfer.setDragImage(Q,Math.max(12,Math.round(Q.clientWidth/2)),Math.max(10,Math.round(Q.clientHeight/2)))}}};window.addEventListener("dragstart",F);const U=Ti(w.current);for(const G of U)G.addEventListener("dragstart",F);return()=>{window.removeEventListener("dragstart",F);for(const G of U)G.removeEventListener("dragstart",F)}},[W]),o.useEffect(()=>{var U;const F=(U=v.current)==null?void 0:U.querySelector(".adhdev-dockview");F instanceof HTMLElement&&Jn(F,A),be(),pe()},[pe,be,A]),o.useEffect(()=>{pe()},[pe]),o.useEffect(()=>{const F=U=>{if(U.defaultPrevented||Z)return;const G=Ue(U);if(!G)return;const se=U.metaKey||U.ctrlKey||U.altKey;Ia(U.target)&&!se||cn(le).setActiveTabShortcut!==G||(U.preventDefault(),U.stopPropagation(),Fe())};return window.addEventListener("keydown",F,!0),()=>window.removeEventListener("keydown",F,!0)},[Ue,le,Z,Fe]),o.useEffect(()=>{const F=v.current;if(!F)return;const U=G=>{var re,ve;if(!G.isTrusted)return;const se=(ve=(re=G.target)==null?void 0:re.closest)==null?void 0:ve.call(re,".dv-scrollable");if(!se)return;G.preventDefault(),G.stopPropagation();const E=Math.abs(G.deltaX),Y=Math.abs(G.deltaY),Q=E>Y?G.deltaX:G.deltaY;se.dispatchEvent(new WheelEvent("wheel",{deltaY:Q,deltaMode:G.deltaMode,bubbles:!1,cancelable:!0}))};return F.addEventListener("wheel",U,{passive:!1,capture:!0}),()=>F.removeEventListener("wheel",U,{capture:!0})},[]),o.useEffect(()=>{const F=Ti(w.current);if(F.length===0)return;const U=F.map(G=>{let se=[],E=null;const Y=()=>{E!=null&&G.clearTimeout(E),E=null,se=[]},Q=()=>{E!=null&&G.clearTimeout(E),E=G.setTimeout(()=>{E=null,se=[]},1200)},re=Ie=>{if(!Ie.ctrlKey&&!Ie.metaKey&&!Ie.altKey)return;const Le=Ue(Ie);if(!Le)return;const Se=_l();for(const[Pe,Ee]of Object.entries(Se))if(e.some(Ae=>Ae.tabKey===Pe)&&Ee===Le){Ie.preventDefault(),ee(Pe);return}},ve=Ie=>{if(Ie.defaultPrevented||Z)return;const Le=Ue(Ie);if(!Le)return;const Se=Ie.metaKey||Ie.ctrlKey||Ie.altKey;if(Ia(Ie.target))return;const Pe=cn(le),Ee=Object.entries(Pe).filter(([Ve,xe])=>!!xe&&(Ve==="splitActiveTabRight"||Ve==="splitActiveTabDown"||Ve==="floatActiveTab"||Ve==="popoutActiveTab"||Ve==="dockActiveTab"||Ve==="focusLeftPane"||Ve==="focusRightPane"||Ve==="focusUpPane"||Ve==="focusDownPane"||Ve==="moveActiveTabToLeftPane"||Ve==="moveActiveTabToRightPane"||Ve==="moveActiveTabToUpPane"||Ve==="moveActiveTabToDownPane"||Ve==="selectPreviousGroupTab"||Ve==="selectNextGroupTab"||Ve==="setActiveTabShortcut"||Ve==="hideCurrentTab")),Ae=Se?[Le]:[...se.slice(-1),Le].slice(-2),qe=Ae.join(" "),et=Ae[Ae.length-1],ct=Ee.find(([,Ve])=>Ve===qe);if(ct){Ie.preventDefault(),Y(),O(ct[0]);return}if(Ee.some(([,Ve])=>Ve.startsWith(`${qe} `))){Ie.preventDefault(),se=Ae,Q();return}const dt=Ee.find(([,Ve])=>Ve===et);if(dt){Ie.preventDefault(),Y(),O(dt[0]);return}if(Ee.some(([,Ve])=>Ve.startsWith(`${et} `))){Ie.preventDefault(),se=[et],Q();return}Y()};return G.addEventListener("keydown",re),G.addEventListener("keydown",ve),()=>{Y(),G.removeEventListener("keydown",re),G.removeEventListener("keydown",ve)}});return()=>{for(const G of U)G()}},[Ue,le,W,ee,Z,O,e]);const Ne=A==="light"?ua:ma,ze=((rt=(Ge=(Je=w.current)==null?void 0:Je.activePanel)==null?void 0:Ge.group.element)==null?void 0:rt.ownerDocument)??document;return s.jsxs(Ol.Provider,{value:Ce,children:[s.jsx("div",{ref:v,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Ad,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:yb,remote:vb},defaultTabComponent:jb,watermarkComponent:wb,onReady:xt,singleTabMode:"default",tabAnimation:"smooth",theme:Ne,popoutUrl:"/popout.html"})}),N&&ar.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:N.x,top:N.y},children:Te.map(F=>{if(F.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},F.id);let U=s.jsx(Su,{size:13,className:"shrink-0 opacity-70"}),G=()=>{};switch(F.id){case"dockInWindow":case"dockBackToGrid":U=s.jsx(Cu,{size:13,className:"shrink-0 opacity-70"}),G=()=>{je(N.tabKey),I(null)};break;case"moveBackToMain":U=s.jsx(ku,{size:13,className:"shrink-0 opacity-70"}),G=()=>{ge(N.tabKey),I(null)};break;case"floatAsPanel":U=s.jsx(Nu,{size:13,className:"shrink-0 opacity-70"}),G=()=>{ye(N.tabKey),I(null)};break;case"openInNewWindow":U=s.jsx(ju,{size:13,className:"shrink-0 opacity-70"}),G=()=>{we(N.tabKey),I(null)};break;case"setShortcut":G=se=>{se.stopPropagation(),De(N.tabKey),I(null)};break;case"removeShortcut":U=s.jsx(yt,{size:13,className:"shrink-0 opacity-70"}),G=()=>{const se={...ke};delete se[N.tabKey],$e(se),I(null)};break;case"hideTab":U=s.jsx(Wa,{size:13,className:"shrink-0 opacity-70"}),G=()=>{ce(N.tabKey),I(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 ${F.tone==="muted"?"text-text-muted":""}`,onMouseDown:xb,onClick:G,children:[U,s.jsx("span",{className:"flex-1 min-w-0",children:F.label}),F.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:F.shortcut}):null]},F.id)})}),N.sourceDocument.body),Z&&ar.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:()=>De(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. ",le?"⌘+1":"Ctrl+1",", ",le?"⌥+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"})]})}),ze.body)]})}const Fl="adhdev-recent-launch-args-v1",Sb=8;function Hl(e){return String(e||"").trim().replace(/\s+/g," ")}function vo(e,t){return`${e.trim()}::${t.trim()}`}function wo(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Fl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Ul(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Fl,JSON.stringify(e))}catch{}}function Ra(e,t){var i;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((i=wo().byKey[vo(r,n)])==null?void 0:i.items)||[]}function zl(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),i=Hl(r);if(!n||!a||!i)return;const c=wo(),l=vo(n,a),d=((u=c.byKey[l])==null?void 0:u.items)||[],m=[i,...d.filter(f=>f!==i)].slice(0,Sb);c.byKey[l]={items:m},Ul(c)}function Nb(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),i=Hl(r);if(!n||!a||!i)return;const c=wo(),l=vo(n,a),m=(((u=c.byKey[l])==null?void 0:u.items)||[]).filter(f=>f!==i);m.length>0?c.byKey[l]={items:m}:delete c.byKey[l],Ul(c)}function Vl(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Vr({title:e,description:t,action:r,children:n,className:a="",contentClassName:i=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),r?s.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?s.jsx("div",{className:t||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function Cb({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 Gl({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:i,onRefresh:c,onOpenHistory:l,onClearSelection:d}){const m=i?Il(i):null,u=Cb({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Vr,{title:"Saved history",description:ro(),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:kp()})]}),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 ql({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 Tb({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:i,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||i,children:l.label},l.id))})]})}function Qn(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>hs(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>hs(a,"acp"))?"acp":null}function Er(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Mb({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:c,onListMeshes:l,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Ve,xe;const u=fr(),f=o.useMemo(()=>[...e].sort(Va),[e]),[x,C]=o.useState(((Ve=f[0])==null?void 0:Ve.id)||""),g=o.useMemo(()=>f.find(z=>z.id===x)||f[0],[x,f]),p=o.useMemo(()=>((g==null?void 0:g.workspaces)||[]).map(z=>({id:z.id,path:z.path,label:z.label})),[g]),j=(g==null?void 0:g.defaultWorkspaceId)||null,[b,h]=o.useState("workspace"),[y,S]=o.useState(""),[k,A]=o.useState(""),[M,w]=o.useState([]),[v,B]=o.useState(""),[_,T]=o.useState(!1),[D,K]=o.useState(null),[L,N]=o.useState(""),[I,W]=o.useState(Qn(f[0])),[P,$]=o.useState(""),[H,J]=o.useState(""),[he,ie]=o.useState([]),[te,be]=o.useState(""),[we,ge]=o.useState([]),[X,ce]=o.useState(!1),[ye,ne]=o.useState(!1),[de,je]=o.useState(""),[me,pe]=o.useState(!1),[ee,ue]=o.useState(()=>vt()),[oe,q]=o.useState(null),[V,le]=o.useState(!1),[ke,Z]=o.useState(""),[De,$e]=o.useState(null),[Fe,Ue]=o.useState(!1),[O,Ce]=o.useState(""),[Te,_e]=o.useState([]),[Be,He]=o.useState(!1),[Xe,st]=o.useState(""),[mt,ht]=o.useState(!1),xt=o.useRef(null),Ne=o.useRef(0);o.useEffect(()=>{var z;!x&&((z=f[0])!=null&&z.id)&&C(f[0].id)},[x,f]),o.useEffect(()=>{!g||!(!g.workspaces||!g.availableProviders||!g.detectedIdes||!g.recentLaunches)||u(g.id,{minFreshMs:3e4}).catch(()=>{})},[u,g]);const ze=o.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(z=>hs(z,"cli")),[g]),Je=o.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(z=>hs(z,"acp")),[g]),Ge=o.useMemo(()=>((g==null?void 0:g.detectedIdes)||[]).map(z=>({id:z.type,label:z.name||z.type,meta:z.running?"Detected locally":"Available to open"})),[g]),rt=o.useMemo(()=>I==="cli"?ze.map(z=>({id:z.type,label:z.displayName||z.type,meta:"CLI provider"})):I==="acp"?Je.map(z=>({id:z.type,label:z.displayName||z.type,meta:"ACP provider"})):Ge,[Je,I,ze,Ge]),F=o.useMemo(()=>M.find(z=>z.id===v)||null,[M,v]),U=o.useMemo(()=>ze.find(z=>z.type===P)||null,[ze,P]),G=o.useMemo(()=>Nl(U==null?void 0:U.meshCoordinator,{meshId:(F==null?void 0:F.id)||"",workspace:(F==null?void 0:F.workspace)||""}),[U,F]),se=De||G,E=o.useCallback(async z=>{T(!0),N("");try{const Me=await l(z);w(Me),B(R=>{var ae;return Me.some(fe=>fe.id===R)?R:((ae=Me[0])==null?void 0:ae.id)||""}),K(z)}catch(Me){w([]),B(""),K(z),N(Me instanceof Error?Me.message:"Could not load meshes")}finally{T(!1)}},[l]);o.useEffect(()=>{var Me;if(!g)return;if(xt.current!==g.id){xt.current=g.id,h("workspace"),S(j||((Me=p[0])==null?void 0:Me.id)||"__home__"),A(""),w([]),B(""),K(null),N(""),W(Qn(g)),$(""),J(""),be(""),ge([]),ne(!1),je(""),ue(vt()),Z(""),$e(null);return}S(R=>{var ae;return R==="__custom__"||R==="__home__"||p.some(fe=>fe.id===R)?R:j||((ae=p[0])==null?void 0:ae.id)||"__home__"}),W(R=>R==="ide"&&Ge.length>0||R==="cli"&&ze.length>0||R==="acp"&&Je.length>0?R:Qn(g))},[Je.length,ze.length,j,Ge.length,g,p]),o.useEffect(()=>{!g||b!=="mesh"||D===g.id||_||E(g.id)},[E,D,_,g,b]),o.useEffect(()=>{b==="mesh"&&I!=="cli"&&ze.length>0&&W("cli")},[I,ze.length,b]),o.useEffect(()=>{var z;I&&(rt.some(Me=>Me.id===P)||$(((z=rt[0])==null?void 0:z.id)||""))},[I,rt,P]),o.useEffect(()=>{$e(null)},[g==null?void 0:g.id,v,P,b]);const Y=o.useCallback(async(z,Me)=>{const R=Ne.current+1;return Ne.current=R,ce(!0),je(""),m(z,Me).then(ae=>{Ne.current===R&&ge(ae)}).catch(ae=>{Ne.current===R&&(ge([]),je(ae instanceof Error?ae.message:"Could not load saved sessions"))}).finally(()=>{Ne.current===R&&(ce(!1),ne(!0))})},[m]),Q=o.useCallback((z,Me)=>{ie(Ra(z,Me))},[]);o.useEffect(()=>{Ne.current+=1,be(""),ue(vt()),!g||!P||I==="ide"?ie([]):Q(g.id,P),ne(!1),ge([]),je(""),ce(!1)},[I,Q,Y,g,P]),o.useEffect(()=>{if(!te)return;const z=we.find(Me=>Me.providerSessionId===te);z!=null&&z.canResume||be("")},[we,te]);const re=y==="__custom__"?k.trim():y==="__home__"?"":((xe=p.find(z=>z.id===y))==null?void 0:xe.path)||"",ve=o.useMemo(()=>g?t.filter(z=>z.id!==g.id&&z.daemonId===g.id).map(z=>z.workspace):[],[t,g]),Ie=o.useMemo(()=>((g==null?void 0:g.recentLaunches)||[]).map(z=>z.workspace),[g]),Le=o.useCallback(z=>{const Me=String(z.workspace||"").trim();if(!Me)return;const R=p.find(ae=>Er(ae.path)===Er(Me));if(R){S(R.id),A("");return}S("__custom__"),A(Me)},[p]),Se=o.useCallback(z=>{const Me=String(z.workspace||"").trim();if(!Me)return{workspaceId:null,workspacePath:null};const R=p.find(ae=>Er(ae.path)===Er(Me));return R?{workspaceId:R.id,workspacePath:null}:{workspaceId:null,workspacePath:Me}},[p]),Pe=o.useMemo(()=>we.find(z=>z.providerSessionId===te)||null,[we,te]),Ee=o.useMemo(()=>{var Me;if(I!=="cli"||!g||!P)return null;const z=((Me=ze.find(R=>R.type===P))==null?void 0:Me.displayName)||P;return{routeId:g.id,daemonId:g.id,providerSessionId:te||void 0,transport:"pty",mode:"chat",agentName:z,agentType:P,status:"idle",title:z,messages:[],ideType:P,workspaceName:re,workspacePath:re,displayPrimary:z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${g.id}:${P}`,machineName:Tt(g,{fallbackId:g.id})}},[I,ze,re,g,te,P]),Ae=o.useCallback(()=>{var Me;if(!g)return;S("__custom__"),Ue(!0),st("");const z=gn(g.platform,bn(k.trim(),re,ve,Ie,g.defaultWorkspacePath,(Me=p.find(R=>R.id===j))==null?void 0:Me.path,p.map(R=>R.path)));He(!0),n(g.id,z).then(R=>{Ce(R.path),A(R.path),_e(R.directories)}).catch(R=>{st(R instanceof Error?R.message:"Could not load folder")}).finally(()=>He(!1))},[k,j,Ie,ve,n,re,g,p]),qe=o.useCallback(z=>{g&&(He(!0),st(""),n(g.id,z).then(Me=>{Ce(Me.path),A(Me.path),_e(Me.directories)}).catch(Me=>{st(Me instanceof Error?Me.message:"Could not load folder")}).finally(()=>He(!1)))},[n,g]),et=o.useCallback(async()=>{if(!g||!re)return;ht(!0),Z("");const z=await a(g.id,re);if(ht(!1),!z.ok){Z(z.error||"Could not save workspace");return}Z("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,re,g]),ct=o.useCallback(async()=>{if(!g)return;if(b==="mesh"){if(!v||!P)return;le(!0),Z(""),$e(null);const R=await d(g.id,v,P);if(le(!1),!R.ok){if(R.code==="mesh_coordinator_manual_mcp_setup_required"&&R.manualSetup){$e(R.manualSetup),Z("Manual MCP setup required before this provider can act as mesh coordinator.");return}Z(R.error||"Could not start mesh coordinator");return}r();return}if(!I||!P)return;le(!0),Z("");const z=H.trim()?H.trim().split(/\s+/).filter(Boolean):[],Me=I==="ide"?await i(g.id,P,{workspacePath:re||null}):await c(g.id,I,P,{workspaceId:y!=="__home__"&&y!=="__custom__"?y:null,workspacePath:y==="__custom__"&&re||null,resumeSessionId:I==="cli"&&te?te:null,cliArgs:z});if(le(!1),!Me.ok){Z(Me.error||"Could not start session");return}I!=="ide"&&H.trim()&&(zl(g.id,P,H),Q(g.id,P)),r()},[I,H,Q,r,i,d,c,re,g,v,te,P,y,b]),ft=b==="mesh"?"Start mesh coordinator":I?qc(I,I==="cli"&&!!te):"Start",dt=b==="mesh"?"Starting coordinator…":I?Yc(I,I==="cli"&&!!te):"Starting…",gt=f.length>5;return g?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(yt,{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(Vr,{title:"Machine",children:gt?s.jsx("select",{"aria-label":"Machine",value:g.id,onChange:z=>C(z.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:V,children:f.map(z=>s.jsx("option",{value:z.id,children:Tt(z,{fallbackId:z.id})},z.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:f.map(z=>{const Me=Tt(z,{fallbackId:z.id}),R=g.id===z.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${Me}`,"aria-pressed":R,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${R?"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:()=>C(z.id),disabled:V,title:Me,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${z.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Me})]},z.id)})})}),s.jsxs(Vr,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:b==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ae,disabled:V,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(z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":b===z.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${b===z.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:()=>{h(z.id),Z(""),z.id==="mesh"&&g&&D!==g.id&&!_&&E(g.id)},disabled:V,children:[s.jsx("div",{className:"text-sm font-semibold",children:z.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:z.desc})]},z.id))}),b==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:y,onChange:z=>{const Me=z.target.value;S(Me),Me==="__custom__"?Ae():Z("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:V,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),p.map(z=>s.jsxs("option",{value:z.id,children:[z.id===j?"⭐ ":"",pn(z.path,z.label)||z.path]},z.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y==="__home__"?"Launch without a workspace.":re||"Select a workspace folder."}),y==="__custom__"&&re&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ae,disabled:V,children:[s.jsx(ms,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:V||mt,children:mt?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[_&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!_&&L&&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:L}),!_&&!L&&M.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."}),M.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:M.map(z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":v===z.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>B(z.id),disabled:V,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:z.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[z.repoIdentity||"Repo mesh",typeof z.nodesCount=="number"?` · ${z.nodesCount} node${z.nodesCount===1?"":"s"}`:""]}),z.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",z.workspace]})]},z.id))}),F&&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(Tb,{workspaceMode:b,activeKind:I,cliEnabled:ze.length>0,ideEnabled:Ge.length>0,acpEnabled:Je.length>0,busy:V,onSelect:W}),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:I==="ide"?"Choose IDE":I==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[rt.map(z=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${P===z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(z.id),disabled:V,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:z.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:z.meta})]},z.id)),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."})]})]}),b==="mesh"&&se&&s.jsx(ql,{setup:se,providerName:(U==null?void 0:U.displayName)||(U==null?void 0:U.name)||P}),b!=="mesh"&&I!=="ide"&&s.jsxs(Vr,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:H,onChange:z=>J(z.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:V}),he.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:he.map(z=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>J(z),disabled:V,title:z,children:z},z))})]}),b!=="mesh"&&I==="cli"&&s.jsx(Gl,{busy:V,savedSessionsLoading:X,savedSessionsError:de,selectedSession:Pe,onRefresh:()=>{!g||!P||Y(g.id,P)},onOpenHistory:()=>{!g||!P||(pe(!0),Vl({hasLoadedInitialResults:ye,isLoading:X})&&Y(g.id,P))},onClearSelection:()=>be("")}),ke&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ke.includes("saved")||ke.includes("requested")||ke.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:ke})]}),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:V,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:ct,disabled:V||(b==="mesh"?!v||!P||I!=="cli"||_:!I||!P||y==="__custom__"&&!re),children:[s.jsx(Fa,{size:14}),V?dt:ft]})]})]})}),Fe&&s.jsx(vn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:O,directories:Te,busy:Be,error:Xe,onClose:()=>Ue(!1),onNavigate:qe,onConfirm:z=>{A(z),Ce(z),S("__custom__"),Ue(!1)}}),me&&Ee&&s.jsx(oo,{activeConv:Ee,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:we,isSavedSessionsLoading:X,isResumingSavedSessionId:oe,savedHistoryFilters:ee,missingWorkspaceResumePath:re||null,onSavedHistoryFiltersChange:ue,onClose:()=>pe(!1),onNewChat:()=>{be(""),pe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!g||!P||Y(g.id,P)},onResumeSavedSession:z=>{if(!g||!P||oe||!z.canResume)return;const Me=Se(z);be(z.providerSessionId),Le(z),q(z.providerSessionId),pe(!1),le(!0),Z(""),c(g.id,"cli",P,{workspaceId:Me.workspaceId,workspacePath:Me.workspacePath,resumeSessionId:z.providerSessionId}).then(R=>{if(!R.ok){Z(R.error||"Could not resume session");return}r()}).finally(()=>{le(!1),q(R=>R===z.providerSessionId?null:R)})}})]}):null}function Ab(e,t){const{sendCommand:r}=bt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);o.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=Ib(n);return{remoteUrl:n,githubUrl:l,loading:i}}function Ib(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 Yl=5e3;function Rb(e){return`git:${e}`}function Lb({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Yl}){return{type:"subscribe",topic:"workspace.git",key:Rb(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function jo(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function xs(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 _b(e){const t=jo(e);return(t==null?void 0:t.success)===!1?{status:null,error:xs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:xs(t,"Git status response did not include status")}}function Pb(e){const t=jo(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:xs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:xs(t,"Git diff summary response did not include diffSummary")}}function Zn(e){return e===void 0||typeof e=="boolean"}function Db(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Zn(t.binary)&&Zn(t.truncated)&&Zn(t.staged)}function Eb(e){const t=jo(e);return(t==null?void 0:t.success)===!1?{diff:null,error:xs(t,"Git file diff request failed")}:Db(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:xs(t,"Git file diff response did not include a valid diff object")}}function $b({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Yl}){const{sendCommand:i,sendData:c}=bt(),l=typeof t=="string"?t.trim():"",d=!!(r&&e&&l),[m,u]=o.useState(null),[f,x]=o.useState(null),[C,g]=o.useState(!1),[p,j]=o.useState(null),b=o.useCallback(async()=>{if(!(!d||!e||!l)){g(!0),j(null);try{const y=_b(await i(e,"git_status",{workspace:l}));if(y.error){u(null),x(null),j(y.error);return}if(u(y.status),!n){x(null);return}const S=Pb(await i(e,"git_diff_summary",{workspace:l}));if(S.error){x(null),j(S.error);return}x(S.diffSummary)}catch(y){j(xs(y,"Git status request failed"))}finally{g(!1)}}},[d,e,n,i,l]),h=o.useMemo(()=>l?Lb({workspace:l,includeDiffSummary:n,intervalMs:a}):null,[n,a,l]);return o.useEffect(()=>{if(!d||!e||!l||!h){u(null),x(null),g(!1),j(null);return}const y=c?Ht.subscribe({sendData:c},e,h,S=>{var k,A;S.workspace===l&&(u(S.status),x(S.diffSummary??null),j(((k=S.status)==null?void 0:k.error)||((A=S.diffSummary)==null?void 0:A.error)||null),g(!1))},{retryIntervalMs:1e3}):null;return b(),()=>{y==null||y()}},[d,e,b,h,c,l]),{status:m,diffSummary:f,loading:C,error:p,refresh:b}}const Bb={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},Kb={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 Ii(e){return e.split("/").pop()??e}function Wb(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Ob({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(i=>{const c=n===i.path,l=Bb[i.status]??"?",d=Kb[i.status]??"text-zinc-400",m=Wb(i.path),u=Ii(i.path),f=i.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(i),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:i.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}),i.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Ii(i.oldPath)]}),f]}),!i.binary&&(i.insertions>0||i.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[i.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",i.insertions]}),i.insertions>0&&i.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),i.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",i.deletions]})]}),i.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${i.path}-${i.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 Fb(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 Hb({diff:e,binary:t,truncated:r,loading:n,error:a,className:i=""}){const c=o.useRef(null);if(o.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 ${i}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${i}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${i}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${i}`,children:"No diff available."});const l=e.split(`
63
- `);return s.jsxs("div",{ref:c,className:`overflow-auto ${i}`,children:[s.jsx("div",{className:"py-1",children:l.map((d,m)=>Fb(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 Ub(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,i]of Object.entries(n))r.push(`${a}: ${i.slice(0,5).join(", ")}${i.length>5?` (+${i.length-5} more)`:""}`);return r.join(`
64
- `)}function Xl({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=bt(),{status:a,diffSummary:i,loading:c,error:l,refresh:d}=$b({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=o.useState(null),[f,x]=o.useState(null),[C,g]=o.useState(""),[p,j]=o.useState(!1),[b,h]=o.useState(!1),[y,S]=o.useState(null),[k,A]=o.useState(null),{githubUrl:M}=Ab(e,t),w=o.useCallback(async K=>{if(!((m==null?void 0:m.path)===K.path&&!m.loading)){u({path:K.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const L=await n(e,"git_diff_file",{workspace:t,path:K.path,staged:K.staged}),N=Eb(L);if(N.error||!N.diff){u({path:K.path,diff:"",binary:!1,truncated:!1,loading:!1,error:N.error??"Failed to load diff"});return}u({path:K.path,diff:N.diff.diff,binary:N.diff.binary??!1,truncated:N.diff.truncated??!1,loading:!1,error:null})}catch(L){const N=L instanceof Error?L.message:"Failed to load diff";u({path:K.path,diff:"",binary:!1,truncated:!1,loading:!1,error:N})}}},[e,n,m,t]),v=o.useCallback(K=>{g(""),j(!1),S(null),A(null),x(K)},[]),B=o.useCallback(()=>{x(null),S(null),h(!1)},[]),_=o.useCallback(async()=>{var K,L,N;if(f){h(!0),S(null);try{let I;f==="checkpoint"?I=await n(e,"git_checkpoint",{workspace:t,message:C,includeUntracked:p}):f==="stash"?I=await n(e,"git_stash_push",{workspace:t,message:C,includeUntracked:p}):f==="stash_pop"?I=await n(e,"git_stash_pop",{workspace:t}):f==="checkout_files"&&m&&(I=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const W=(I==null?void 0:I.result)??I;if((W==null?void 0:W.success)===!1||W!=null&&W.error){S((W==null?void 0:W.error)??"Action failed"),h(!1);return}f==="checkpoint"?A(`Checkpoint created: ${((L=(K=W==null?void 0:W.checkpoint)==null?void 0:K.commit)==null?void 0:L.slice(0,7))??"done"}`):f==="stash"?A(`Stashed as ${((N=W==null?void 0:W.stash)==null?void 0:N.stashRef)??"stash@{0}"}`):f==="stash_pop"?A("Stash restored"):(A("File reverted"),u(null)),x(null),await d()}catch(I){S(I instanceof Error?I.message:"Action failed")}finally{h(!1)}}},[f,n,e,t,C,p,m,d]),T=!!(a!=null&&a.hasConflicts),D=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:K=>{K.target===K.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}),M&&s.jsx("a",{href:`${M}/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(yt,{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"}),D===0&&!a.error&&s.jsx("span",{className:"text-emerald-500",children:"clean"}),i&&i.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[i.files.length," file",i.files.length!==1?"s":"",i.totalInsertions>0&&s.jsxs("span",{className:"text-emerald-500",children:[" +",i.totalInsertions]}),i.totalDeletions>0&&s.jsxs("span",{className:"text-red-400",children:[" -",i.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&&!i&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),i&&s.jsx(Ob,{files:i.files,truncated:i.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:w}),!c&&!i&&!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(Hb,{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"})})]}),k&&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:k}),s.jsx("button",{onClick:()=>A(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:()=>v("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:()=>v("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:()=>v("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:()=>v("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"}),i&&i.files.length>0&&s.jsx("button",{onClick:()=>{const K=Ub((a==null?void 0:a.branch)??null,i);navigator.clipboard.writeText(K),A("Copied to clipboard"),setTimeout(()=>A(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:C,onChange:K=>g(K.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:K=>j(K.target.checked)}),"Include untracked files"]})]}),y&&s.jsx("p",{className:"text-xs text-red-400",children:y}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:B,disabled:b,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:b||(f==="checkpoint"||f==="stash")&&!C.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:b?"Working…":"Confirm"})]})]})})]})})}function zb({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=o.useState(!1),[i,c]=o.useState(!1),[l,d]=o.useState(!1),[m,u]=o.useState(!1),[f,x]=o.useState(!1),[C,g]=o.useState("quickstart"),[p,j]=o.useState("workspace"),b=o.useMemo(()=>!t&&!e,[t,e]),h=o.useCallback(w=>{a(w),w&&c(!1)},[]),y=o.useCallback(w=>{c(w),w&&a(!1)},[]),S=o.useCallback(()=>{g(r===0?"quickstart":"shortcuts"),j("workspace"),d(!0),a(!1),c(!1)},[r]),k=o.useCallback(()=>{d(!1)},[]),A=o.useCallback(()=>{u(!0)},[]),M=o.useCallback(()=>{u(!1)},[]);return o.useEffect(()=>{if(!b){x(!1);return}x(!0);const w=window.setTimeout(()=>{x(!1)},1e4);return()=>window.clearTimeout(w)},[b]),{inboxOpen:n,hiddenOpen:i,shortcutHelpOpen:l,newSessionOpen:m,guideNudgeVisible:f,guideTab:C,shortcutSection:p,isDesktopDashboard:b,setGuideTab:g,setShortcutSection:j,handleInboxOpenChange:h,handleHiddenOpenChange:y,handleOpenShortcutHelp:S,closeShortcutHelp:k,openNewSession:A,closeNewSession:M}}function Vb(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 Gb(e){return e instanceof Error?e.message:String(e||"")}function qb(e){const t=Gb(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Yb({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:f,ides:x,actionLogs:C,sendDaemonCommand:g,setActionLogs:p,setCliViewModeOverrides:j,isStandalone:b,initialDataLoaded:h,userName:y,requestedMobileTabKey:S,onRequestedMobileTabConsumed:k,requestedMachineId:A,onRequestedMachineConsumed:M,requestedMobileSection:w,onRequestedMobileSectionConsumed:v,containerRef:B,isSplitMode:_,numGroups:T,groupSizes:D,groupedConvs:K,clearedTabs:L,focusedGroup:N,focusGroup:I,moveTabToGroup:W,splitTabRelative:P,closeGroup:$,handleResizeStart:H,groupActiveTabIds:J,setGroupActiveTab:he,groupTabOrders:ie,setGroupTabOrder:te,toggleHiddenTab:be,visibleConversations:we,requestedDesktopTabKey:ge,onRequestedDesktopTabConsumed:X,onDesktopActiveTabChange:ce,onRequestScrollToBottom:ye,onHideConversation:ne,onShowHiddenConversation:de,onShowAllHiddenConversations:je,scrollToBottomRequest:me,machineEntries:pe,layoutProfile:ee,onBrowseMachineDirectory:ue,onSaveMachineWorkspace:oe,onLaunchMachineIde:q,onLaunchMachineProvider:V,onListMachineMeshes:le,onLaunchMeshCoordinator:ke,onListMachineSavedSessions:Z,notifications:De,notificationUnreadCount:$e,liveSessionInboxState:Fe,onMarkNotificationRead:Ue,onMarkNotificationUnread:O,onDeleteNotification:Ce}){const Te=Ct.useRef(null),{inboxOpen:_e,hiddenOpen:Be,shortcutHelpOpen:He,newSessionOpen:Xe,guideNudgeVisible:st,guideTab:mt,shortcutSection:ht,isDesktopDashboard:xt,setGuideTab:Ne,setShortcutSection:ze,handleInboxOpenChange:Je,handleHiddenOpenChange:Ge,handleOpenShortcutHelp:rt,closeShortcutHelp:F,openNewSession:U,closeNewSession:G}=zb({isMobile:t,showMobileChatMode:e,visibleConversationCount:we.length}),[se,E]=Ct.useState(null),Y=Ct.useCallback((xe,z)=>{E({daemonId:xe,workspace:z})},[]),Q=Ct.useCallback(xe=>{var z;ar.flushSync(()=>{de(xe)}),(z=Te.current)==null||z.restoreHiddenTabToSavedLocation(xe.tabKey)},[de]),re=Ct.useCallback(xe=>{var Me;const z=u.find(R=>wa(R,xe))||f.find(R=>wa(R,xe));z&&(f.some(R=>R.tabKey===z.tabKey)&&Q(z),ce(z.tabKey),(Me=Te.current)==null||Me.activateConversationTab(z.tabKey),ye(z.tabKey,"notification-open")),Ue(xe.id),Je(!1)},[Q,f,u,ce,Ue,ye]),ve=Ct.useCallback(()=>{var z;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((z=Te.current)==null||z.resetAllPanelsToMain(),Ge(!1))},[Ge]),Ie=Ct.useCallback(async xe=>{var fe;if(!r)return;const z=(fe=r.modalButtons)==null?void 0:fe[xe];if(!z)return;const Me=Ls(r);if(!Me)return;const R=z.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),ae=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(R);try{await g(Me,"resolve_action",{button:z,action:ae?"approve":"reject",buttonIndex:xe,...rs(r)})}catch(Ke){qb(Ke)||console.error("[Shortcut approval] Failed:",Ke)}},[r,g]),{isMac:Le,actionDefinitions:Se,actionShortcuts:Pe,shortcutListening:Ee,shortcutListeningDraft:Ae,setShortcutListening:qe,setShortcutListeningDraft:et,saveShortcuts:ct}=lb({enabled:xt&&!He,onTrigger:xe=>{var z,Me,R,ae,fe,Ke,Re,We,ot,Nt,pt,Vt,xr,br,gr,yr;if(xe==="openShortcutHelp"){rt();return}if(xe==="openNewSession"){U();return}if(xe==="hideCurrentTab"){r&&ne(r);return}if(xe==="toggleHiddenTabs"){Ge(!Be);return}if(xe==="openHistoryForActiveTab"){r&&!Ze(r)&&i(r);return}if(xe==="openRemoteForActiveTab"){r&&!tt(r)&&!Ze(r)&&c(r);return}if(xe==="splitActiveTabRight"){(z=Te.current)==null||z.splitActiveTabRight();return}if(xe==="splitActiveTabDown"){(Me=Te.current)==null||Me.splitActiveTabDown();return}if(xe==="floatActiveTab"){(R=Te.current)==null||R.floatActiveTab();return}if(xe==="popoutActiveTab"){(ae=Te.current)==null||ae.popoutActiveTab();return}if(xe==="dockActiveTab"){(fe=Te.current)==null||fe.dockActiveTab();return}if(xe==="focusLeftPane"){(Ke=Te.current)==null||Ke.focusLeftPane();return}if(xe==="focusRightPane"){(Re=Te.current)==null||Re.focusRightPane();return}if(xe==="focusUpPane"){(We=Te.current)==null||We.focusUpPane();return}if(xe==="focusDownPane"){(ot=Te.current)==null||ot.focusDownPane();return}if(xe==="moveActiveTabToLeftPane"){(Nt=Te.current)==null||Nt.moveActiveTabToLeftPane();return}if(xe==="moveActiveTabToRightPane"){(pt=Te.current)==null||pt.moveActiveTabToRightPane();return}if(xe==="moveActiveTabToUpPane"){(Vt=Te.current)==null||Vt.moveActiveTabToUpPane();return}if(xe==="moveActiveTabToDownPane"){(xr=Te.current)==null||xr.moveActiveTabToDownPane();return}if(xe==="triggerPrimaryApprovalAction"){Ie(0);return}if(xe==="triggerSecondaryApprovalAction"){Ie(1);return}if(xe==="triggerTertiaryApprovalAction"){Ie(2);return}if(xe==="setActiveTabShortcut"){(br=Te.current)==null||br.setShortcutForActiveTab();return}if(xe==="selectPreviousGroupTab"){(gr=Te.current)==null||gr.activatePreviousTabInGroup();return}if(xe==="selectNextGroupTab"){(yr=Te.current)==null||yr.activateNextTabInGroup();return}!r||!tt(r)||Ze(r)||xe==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),ft=Ct.useCallback(()=>{F(),qe(null),et([])},[F,qe,et]),dt=Ct.useMemo(()=>ht==="all"?Se:Se.filter(xe=>Vb(xe)===ht),[Se,ht]),gt=Ct.useCallback(()=>{const xe=Object.fromEntries(Se.map(z=>[z.id,""]));ct(xe)},[Se,ct]),Ve=Ct.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const xe=Object.fromEntries(Se.map(z=>[z.id,z.defaultShortcut]));ct(xe)},[Se,ct]);return Ct.useEffect(()=>{const xe=z=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?z.metaKey&&z.key.toLowerCase()==="w":z.ctrlKey&&z.key.toLowerCase()==="w")&&(z.preventDefault(),r&&ne&&ne(r))};return window.addEventListener("keydown",xe),()=>window.removeEventListener("keydown",xe)},[r,ne]),Ct.useEffect(()=>{if(!He||Ee)return;const xe=z=>{z.key==="Escape"&&(z.preventDefault(),ft())};return window.addEventListener("keydown",xe,!0),()=>window.removeEventListener("keydown",xe,!0)},[ft,He,Ee]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(bp,{activeConv:r,wsStatus:n,isConnected:a,conversations:we,hiddenConversations:f,onOpenHistory:i,onHideConversation:ne,onShowConversation:Q,onShowAllHidden:je,onResetPanelsToMain:ve,notifications:De,notificationUnreadCount:$e,onOpenNotification:re,onMarkNotificationRead:Ue,onMarkNotificationUnread:O,onDeleteNotification:Ce,inboxOpen:_e,onInboxOpenChange:Je,hiddenOpen:Be,onHiddenOpenChange:Ge,onOpenNewSession:t?void 0:U,onOpenDashboardGuide:rt,guideNudgeVisible:st,actionShortcuts:Pe,onOpenRemote:()=>{!r||tt(r)||Ze(r)||c(r)},onStopCli:l,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:Y}),e?s.jsx(Jx,{conversations:u,hiddenConversations:f,ides:x,actionLogs:C,sendDaemonCommand:g,setActionLogs:p,setCliViewModeOverrides:j,isStandalone:b,userName:y,requestedActiveTabKey:S,onRequestedActiveTabConsumed:k,requestedMachineId:A,onRequestedMachineConsumed:M,requestedMobileSection:w,onRequestedMobileSectionConsumed:v,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowAllHiddenConversations:je,onHideConversation:ne,onOpenNewSession:U,liveSessionInboxState:Fe}):t?s.jsx(ab,{containerRef:B,isSplitMode:_,numGroups:T,groupSizes:D,groupedConvs:K,clearedTabs:L,ides:x,actionLogs:C,sendDaemonCommand:g,setActionLogs:p,isStandalone:b,hasRegisteredMachines:pe.length>0,userName:y,focusedGroup:N,focusGroup:I,moveTabToGroup:W,splitTabRelative:P,closeGroup:$,handleResizeStart:H,groupActiveTabIds:J,setGroupActiveTab:he,groupTabOrders:ie,setGroupTabOrder:te,toggleHiddenTab:be,onOpenNewSession:U,allowTabShortcuts:!1,liveSessionInboxState:Fe}):s.jsx(kb,{visibleConversations:we,clearedTabs:L,ides:x,actionLogs:C,sendDaemonCommand:g,setActionLogs:p,isStandalone:b,hasRegisteredMachines:pe.length>0,initialDataLoaded:h,userName:y,toggleHiddenTab:be,actionShortcuts:Pe,registerActionHandlers:xe=>{Te.current=xe},onActiveTabChange:ce,requestedActiveTabKey:ge,onRequestedActiveTabConsumed:X,onRequestScrollToBottom:ye,scrollToBottomRequest:me,onOpenNewSession:U,liveSessionInboxState:Fe,layoutProfile:ee}),Xe&&s.jsx(Mb,{machines:pe,ides:x,onClose:G,onBrowseDirectory:ue,onSaveWorkspace:oe,onLaunchIde:q,onLaunchProvider:V,onListMeshes:le,onLaunchMeshCoordinator:ke,onListSavedSessions:Z}),se&&s.jsx(Xl,{daemonId:se.daemonId,workspace:se.workspace,onClose:()=>E(null)}),He&&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:ft,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:xe=>xe.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:ft,"aria-label":"Close dashboard guide",children:s.jsx(yt,{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(xe=>s.jsx("button",{type:"button",className:`btn btn-sm ${mt===xe.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ne(xe.id),children:xe.label},xe.id))}),mt==="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 ",Le?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),mt==="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."]})]})]})]}),mt==="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(xe=>s.jsx("button",{type:"button",className:`btn btn-sm ${ht===xe.id?"btn-primary":"btn-secondary"}`,onClick:()=>ze(xe.id),children:xe.label},xe.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:gt,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:Ve,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:dt.map(xe=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ee===xe.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:xe.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:xe.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:xe.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:Ee===xe.id?Ae.length>0?`${Ae.join(" ")} ...`:"Listening...":Pe[xe.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{qe(xe.id),et([])},children:Ee===xe.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const z={...Pe};z[xe.id]="",ct(z)},children:"Disable"})]})]})},xe.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Le?"⌘⇧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 ea=[{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 Xb({onClose:e}){const[t,r]=o.useState(0),n=ea[t],a=t===ea.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:i=>{i.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(yt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:ea.map((i,c)=>s.jsx("div",{style:{width:c===t?24:8,height:8,borderRadius:4,background:c===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:n.icon})," ",n.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
62
+ `,Y.style.top="52px",Y.style.height="calc(100% - 52px)";const Pe=Se.querySelector("[data-adhdev-popout-focus]");Pe&&(Pe.onclick=()=>{window.focus()});const Ee=Se.querySelector("[data-adhdev-popout-dock]");Ee&&(Ee.disabled=!Q,Ee.style.opacity=Q?"1":"0.5",Ee.style.cursor=Q?"pointer":"default",Ee.onclick=()=>{var Ae;Q&&ge(Q),(Ae=E.defaultView)==null||Ae.focus()})}},[H,ge]),ee=o.useCallback(O=>{var se;const U=w.current,G=U==null?void 0:U.getPanel(O);if(!(!U||!G)){G.group.model.openPanel(G),G.api.setActive(),ie(O,"dockview-shortcut");try{const E=G.group.model.location;E.type==="popout"?E.getWindow().focus():Jn((se=G.group.element)==null?void 0:se.ownerDocument)}catch{}}},[ie]),ue=o.useCallback(O=>{const U=w.current,G=U==null?void 0:U.activePanel,se=(U==null?void 0:U.activeGroup)||(G==null?void 0:G.group);if(!U||!G||!se)return;const E=se.panels||[];if(E.length<=1)return;const Y=E.findIndex(ve=>ve.id===G.id);if(Y<0)return;const Q=(Y+O+E.length)%E.length,re=E[Q];re&&(re.group.model.openPanel(re),re.api.setActive(),Lt(re.id)||ie(re.id,"dockview-shortcut"))},[ie]),oe=o.useCallback(O=>{var Pe;const U=w.current,G=(U==null?void 0:U.activeGroup)||((Pe=U==null?void 0:U.activePanel)==null?void 0:Pe.group);if(!U||!G)return;const se=U.groups||[],E=se.find(Ee=>Ee.id===G.id);if(!E)return;const Y=E.element.getBoundingClientRect(),Q=Y.left+Y.width/2,re=Y.top+Y.height/2,ve=(Ee,Ae,qe,et)=>Math.max(0,Math.min(Ae,et)-Math.max(Ee,qe)),Ie=Ee=>{const Ae=Ee.element.getBoundingClientRect(),qe=Ae.left+Ae.width/2,et=Ae.top+Ae.height/2;let ct=0,ft=0,dt=0,yt=!1;if(O==="left"?(yt=qe<Q,ct=Math.max(0,Y.left-Ae.right),ft=Math.abs(et-re),dt=ve(Y.top,Y.bottom,Ae.top,Ae.bottom)):O==="right"?(yt=qe>Q,ct=Math.max(0,Ae.left-Y.right),ft=Math.abs(et-re),dt=ve(Y.top,Y.bottom,Ae.top,Ae.bottom)):O==="above"?(yt=et<re,ct=Math.max(0,Y.top-Ae.bottom),ft=Math.abs(qe-Q),dt=ve(Y.left,Y.right,Ae.left,Ae.right)):(yt=et>re,ct=Math.max(0,Ae.top-Y.bottom),ft=Math.abs(qe-Q),dt=ve(Y.left,Y.right,Ae.left,Ae.right)),!yt)return Number.POSITIVE_INFINITY;const Ve=dt>0?0:120;return ct*3+ft+Ve};let Le=null,Se=Number.POSITIVE_INFINITY;for(const Ee of se){if(Ee.id===E.id)continue;const Ae=Ie(Ee);Number.isFinite(Ae)&&(Ae>=Se||(Se=Ae,Le=Ee))}return Le||void 0},[]),q=o.useCallback(O=>{var se;const U=oe(O);if(!U)return;const G=U.activePanel||U.panels[0];G&&(U.model.openPanel(G),G.api.setActive(),Lt(G.id)||ie(G.id,"dockview-focus"),Jn((se=U.element)==null?void 0:se.ownerDocument))},[oe,ie]),V=o.useCallback((O,U)=>{const G=w.current,se=G==null?void 0:G.activePanel,E=(G==null?void 0:G.activeGroup)||(se==null?void 0:se.group);if(!G||!se||!E)return;let Y=oe(O);!Y&&(U!=null&&U.createGroupIfMissing)&&(Y=G.addGroup({referenceGroup:E,direction:O})),Y&&(se.api.moveTo({group:Y,position:"center"}),se.group.model.openPanel(se),se.api.setActive(),Lt(se.id)||ie(se.id,U!=null&&U.createGroupIfMissing?"dockview-split":"dockview-move"))},[oe,ie]),{isMac:le,tabShortcuts:ke,shortcutListening:Z,setShortcutListening:De,saveShortcuts:$e}=Dl({sortedTabKeys:e.map(O=>O.tabKey),onFocus:he,onSelectTab:ee}),Fe=o.useCallback(()=>{var G;const O=w.current;if(!O)return;const U=O.activePanel;if(U){if(Lt(U.id)){const se=((G=U.params)==null?void 0:G.routeId)||U.id.slice(7),E=Dt(e,se);E!=null&&E.tabKey&&De(E.tabKey);return}H.has(U.id)&&De(U.id)}},[H,ee,De,e]),Ue=o.useCallback(O=>{const U=[];return O.metaKey&&U.push(le?"⌘":"Meta"),O.ctrlKey&&U.push("Ctrl"),O.altKey&&U.push(le?"⌥":"Alt"),O.shiftKey&&O.key.length!==1&&U.push(le?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(O.key)?null:(U.push(Kl(O.key)),U.join("+"))},[le]),W=o.useCallback(O=>{var U,G;switch(O){case"splitActiveTabRight":V("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":V("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const se=de();se&&ye(se);return}case"popoutActiveTab":{const se=de();se&&we(se);return}case"dockActiveTab":{const se=de();if(!se)return;X(se)?ge(se):ne(se)&&je(se);return}case"focusLeftPane":q("left");return;case"focusRightPane":q("right");return;case"focusUpPane":q("above");return;case"focusDownPane":q("below");return;case"moveActiveTabToLeftPane":V("left");return;case"moveActiveTabToRightPane":V("right");return;case"moveActiveTabToUpPane":V("above");return;case"moveActiveTabToDownPane":V("below");return;case"selectPreviousGroupTab":ue(-1);return;case"selectNextGroupTab":ue(1);return;case"setActiveTabShortcut":Fe();return;case"hideCurrentTab":{const se=(G=(U=w.current)==null?void 0:U.activePanel)==null?void 0:G.id;se&&!Lt(se)&&ce(se);return}default:return}},[ue,je,q,ye,de,ce,ne,X,ge,V,we,Fe]);o.useEffect(()=>{if(!N)return;const O=N.sourceDocument,U=O.defaultView??window,G=se=>{const E=O.querySelector("[data-dockview-tab-context-menu]");E&&E.contains(se.target)||I(null)};return U.addEventListener("mousedown",G,!0),U!==window&&window.addEventListener("mousedown",()=>I(null),!0),()=>{U.removeEventListener("mousedown",G,!0),U!==window&&window.removeEventListener("mousedown",()=>I(null),!0)}},[N]);const Ce=o.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:H,hasDetachedConversationPanels:J,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:y,liveSessionInboxState:S,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:ce,userName:m,scrollToBottomRequest:k,tabShortcuts:ke,openTabContextMenu:({x:O,y:U,tabKey:G,sourceDocument:se})=>I({x:O,y:U,tabKey:G,sourceDocument:se??document}),popoutTab:we,moveTabBackToMain:ge,isTabInPopout:X,floatTab:ye,isTabFloating:ne}),[n,t,H,J,r,c,l,y,S,a,i,ce,m,k,ke,we,ge,X,ye,ne]),Te=N?mb({isTabInPopout:X(N.tabKey),isTabFloating:ne(N.tabKey),tabShortcut:ke[N.tabKey],actionShortcuts:f}):[],_e=o.useCallback(O=>{var se;const U=w.current;if((((se=U==null?void 0:U.activePanel)==null?void 0:se.id)??null)===O.id){O.group.model.openPanel(O);return}O.group.model.openPanel(O),O.api.setActive()},[]),Be=o.useCallback((O,U="requested-tab")=>{if(!O)return!1;const G=w.current;if(!G)return!1;const se=G.getPanel(O);return se?(_e(se),ie(O,U),h==null||h(),!0):!1},[_e,h,ie]),He=o.useCallback(()=>{if(D.current)return!1;const O=Be(K.current,"stored-layout-restore");return O&&(D.current=!0),O},[Be]),Xe=o.useCallback(()=>{var U;const O=w.current;O&&Uh(j,{activeTabId:((U=O.activePanel)==null?void 0:U.id)??null,layout:O.toJSON()})},[j]),st=o.useCallback(()=>{Vh(j,$.current)},[j]),mt=o.useCallback(O=>{var se,E,Y,Q;const U=w.current;if(!U)return{kind:"grid"};const G=U.toJSON();for(const re of G.floatingGroups||[])if((E=(se=re.data)==null?void 0:se.views)!=null&&E.includes(O)&&re.position)return{kind:"floating",position:re.position};for(const re of G.popoutGroups||[])if((Q=(Y=re.data)==null?void 0:Y.views)!=null&&Q.includes(O))return{kind:"popout",position:re.position,popoutUrl:re.url};return{kind:"grid"}},[]),ht=o.useCallback(O=>{const U=w.current;if(!U)return;const G=U.getPanel(O),se=$.current[O];if(!G||!se||se.kind==="grid")return;if(G.group.model.location.type===se.kind){delete $.current[O],st();return}if(se.kind==="floating"){U.addFloatingGroup(G,{x:se.position.left??24,y:se.position.top??24,width:se.position.width,height:se.position.height}),delete $.current[O],st();return}delete $.current[O],st()},[st]);o.useEffect(()=>(x==null||x({setShortcutForActiveTab:Fe,restoreHiddenTabToSavedLocation:ht,activateConversationTab:ee,resetAllPanelsToMain:me,activatePreviousTabInGroup:()=>ue(-1),activateNextTabInGroup:()=>ue(1),floatActiveTab:()=>{const O=de();O&&ye(O)},popoutActiveTab:()=>{const O=de();O&&we(O)},dockActiveTab:()=>{const O=de();O&&(X(O)?ge(O):ne(O)&&je(O))},splitActiveTabRight:()=>V("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>V("below",{createGroupIfMissing:!0}),focusLeftPane:()=>q("left"),focusRightPane:()=>q("right"),focusUpPane:()=>q("above"),focusDownPane:()=>q("below"),moveActiveTabToLeftPane:()=>V("left"),moveActiveTabToRightPane:()=>V("right"),moveActiveTabToUpPane:()=>V("above"),moveActiveTabToDownPane:()=>V("below")}),()=>x==null?void 0:x(null)),[ue,je,ye,q,de,ne,X,V,ge,we,x,me,ht,ee,Fe]),o.useEffect(()=>()=>{var O;(O=B.current)==null||O.call(B),B.current=null},[]);const xt=o.useCallback(O=>{var G,se;w.current=O.api,(G=B.current)==null||G.call(B),B.current=null;const U=Hh(j);if(K.current=(U==null?void 0:U.activeTabId)??null,U!=null&&U.layout&&O.api.fromJSON(U.layout,{reuseExistingPanels:!1}),T.current=Si({hasStoredLayout:!!(U!=null&&U.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),T.current||(Ii(O.api,e),Ri(O.api,e,b)),O.api.totalPanels===0&&e.length>0){const E=vb(O.api,e,g);if(E){const Y=O.api.getPanel(E);Y&&_e(Y)}}else!T.current&&!Be(g)&&He();if(_.current=!0,O.api.onDidActivePanelChange(E=>{var Q;if(K.current=(E==null?void 0:E.id)??null,D.current=!0,pe(),E&&Lt(E.id)){const re=((Q=E.params)==null?void 0:Q.routeId)||E.id.slice(7),ve=Dt(e,re);C((ve==null?void 0:ve.tabKey)??null),Xe();return}if(C((E==null?void 0:E.id)??null),Xe(),!E)return;const Y=H.get(E.id);(Y==null?void 0:Y.streamSource)==="agent-stream"&&Y.agentType&&M(Y.routeId,Ac(),{agentType:Y.agentType,...Y.sessionId&&{targetSessionId:Y.sessionId}}).catch(()=>{})}),O.api.onDidLayoutChange(()=>{Xe(),pe(),P(E=>E+1)}),xb()){const E=Se=>({clientX:Se.clientX,clientY:Se.clientY}),Y=Se=>{const Pe=Se==null?void 0:Se.getBoundingClientRect();return Pe?{left:Pe.left,right:Pe.right,top:Pe.top,bottom:Pe.bottom}:null},Q=Se=>{var Ee;const Pe=(Ee=v.current)==null?void 0:Ee.getBoundingClientRect();return Pe?Se.clientX<Pe.left||Se.clientX>Pe.right||Se.clientY<Pe.top||Se.clientY>Pe.bottom:!1},re=hb({detachDelayMs:Ol,onDetach:({panelId:Se,clientX:Pe,clientY:Ee})=>{var dt,yt;const Ae=O.api.getPanel(Se);if(!Ae)return;try{if(Ae.group.model.location.type!=="grid")return}catch{return}const qe=(dt=v.current)==null?void 0:dt.getBoundingClientRect(),et=(yt=Ae.group.element)==null?void 0:yt.getBoundingClientRect(),ct=Math.round(Math.min(Math.max((et==null?void 0:et.width)??600,360),720)),ft=Math.round(Math.min(Math.max((et==null?void 0:et.height)??500,260),640));O.api.addFloatingGroup(Ae,{x:qe?Math.max(0,Pe-qe.left-32):void 0,y:qe?Math.max(0,Ee-qe.top-18):void 0,width:ct,height:ft}),Ae.api.setActive(),Xe(),pe(),P(Ve=>Ve+1)}}),ve=[O.api.onWillDragPanel(Se=>{if(!(Se.nativeEvent.defaultPrevented||Se.nativeEvent.shiftKey)){try{if(Se.panel.group.model.location.type!=="grid")return}catch{return}re.startDrag({panelId:Se.panel.id,selfPanelBounds:Y(Se.panel.group.element),...E(Se.nativeEvent)})}}),O.api.onWillShowOverlay(Se=>{if(re.hasDetached()){Se.preventDefault();return}re.markDockTarget(E(Se.nativeEvent))}),O.api.onWillDrop(Se=>{if(re.hasDetached()){Se.preventDefault(),re.endDrag();return}re.markDockTarget(E(Se.nativeEvent))}),O.api.onDidDrop(()=>re.endDrag()),O.api.onUnhandledDragOverEvent(Se=>{re.isDragging()&&re.markSelfPanel(E(Se.nativeEvent))})],Ie=Se=>{if(!re.isDragging())return;const Pe=E(Se);Q(Pe)&&re.markNonSelfPanel(Pe)},Le=()=>re.endDrag();window.addEventListener("dragover",Ie,!0),window.addEventListener("drop",Le,!0),window.addEventListener("dragend",Le,!0),B.current=()=>{re.dispose();for(const Se of ve)Se.dispose();window.removeEventListener("dragover",Ie,!0),window.removeEventListener("drop",Le,!0),window.removeEventListener("dragend",Le,!0)}}O.api.onDidAddGroup(E=>{requestAnimationFrame(()=>{var Y,Q;try{const re=(Y=E.element)==null?void 0:Y.ownerDocument;if(!re||re===document)return;(Q=re.getElementById("dv-popout-window"))==null||Q.classList.add("adhdev-dockview");const ve=document.documentElement.getAttribute("data-theme");ve&&re.documentElement.setAttribute("data-theme",ve),re.body.className=document.body.className;const Ie=document.documentElement.getAttribute("style");Ie&&re.documentElement.setAttribute("style",Ie)}catch{}pe(),P(re=>re+1)})}),C(((se=O.api.activePanel)==null?void 0:se.id)??null)},[_e,Be,H,r,d,j,C,Xe,g,b,M,pe,e]);o.useLayoutEffect(()=>{const O=w.current;if(!O||!_.current||T.current&&Si({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const U=L.current,G=new Set(U),se=e.map(Le=>Le.tabKey),E=new Set(se),Y=fb({previousVisibleConversationCount:U.length,visibleConversationCount:e.length,ides:r});let Q=!1;for(const Le of U)E.has(Le)||Y||($.current[Le]=mt(Le),Q=!0);Q&&st(),Y||(Ii(O,e),Ri(O,e,b));const re=se.filter(Le=>!G.has(Le));let ve=!1;for(const Le of re){const Se=O.getPanel(Le),Pe=$.current[Le];if(!Se||!Pe||Pe.kind==="grid")continue;if(Se.group.model.location.type===Pe.kind){delete $.current[Le],ve=!0;continue}if(Pe.kind==="floating"){O.addFloatingGroup(Se,{x:Pe.position.left??24,y:Pe.position.top??24,width:Pe.position.width,height:Pe.position.height}),delete $.current[Le],ve=!0;continue}}if(ve&&st(),L.current=se,g&&Be(g))return;!O.activePanel&&O.panels[0]&&_e(O.panels[0]),!!(O.activePanel&&O.getPanel(O.activePanel.id))||He()},[_e,Be,He,r,d,st,mt,g,b,e]),o.useEffect(()=>{_.current&&Be(g)},[Be,g]),o.useEffect(()=>{const O=G=>{const se=G.target;if(!se)return;const E=se.querySelector("[data-tab-key]")||se.closest("[data-tab-key]");if(E){const Y=E.getAttribute("data-tab-key");if(Y&&G.dataTransfer){const Q=se.closest(".dv-tab")||E.closest(".dv-tab")||E;G.dataTransfer.effectAllowed="move",G.dataTransfer.setData("text/tab-key",Y),Q instanceof HTMLElement&&G.dataTransfer.setDragImage(Q,Math.max(12,Math.round(Q.clientWidth/2)),Math.max(10,Math.round(Q.clientHeight/2)))}}};window.addEventListener("dragstart",O);const U=Ai(w.current);for(const G of U)G.addEventListener("dragstart",O);return()=>{window.removeEventListener("dragstart",O);for(const G of U)G.removeEventListener("dragstart",O)}},[F]),o.useEffect(()=>{var U;const O=(U=v.current)==null?void 0:U.querySelector(".adhdev-dockview");O instanceof HTMLElement&&Qn(O,A),be(),pe()},[pe,be,A]),o.useEffect(()=>{pe()},[pe]),o.useEffect(()=>{const O=U=>{if(U.defaultPrevented||Z)return;const G=Ue(U);if(!G)return;const se=U.metaKey||U.ctrlKey||U.altKey;Ra(U.target)&&!se||ln(le).setActiveTabShortcut!==G||(U.preventDefault(),U.stopPropagation(),Fe())};return window.addEventListener("keydown",O,!0),()=>window.removeEventListener("keydown",O,!0)},[Ue,le,Z,Fe]),o.useEffect(()=>{const O=v.current;if(!O)return;const U=G=>{var re,ve;if(!G.isTrusted)return;const se=(ve=(re=G.target)==null?void 0:re.closest)==null?void 0:ve.call(re,".dv-scrollable");if(!se)return;G.preventDefault(),G.stopPropagation();const E=Math.abs(G.deltaX),Y=Math.abs(G.deltaY),Q=E>Y?G.deltaX:G.deltaY;se.dispatchEvent(new WheelEvent("wheel",{deltaY:Q,deltaMode:G.deltaMode,bubbles:!1,cancelable:!0}))};return O.addEventListener("wheel",U,{passive:!1,capture:!0}),()=>O.removeEventListener("wheel",U,{capture:!0})},[]),o.useEffect(()=>{const O=Ai(w.current);if(O.length===0)return;const U=O.map(G=>{let se=[],E=null;const Y=()=>{E!=null&&G.clearTimeout(E),E=null,se=[]},Q=()=>{E!=null&&G.clearTimeout(E),E=G.setTimeout(()=>{E=null,se=[]},1200)},re=Ie=>{if(!Ie.ctrlKey&&!Ie.metaKey&&!Ie.altKey)return;const Le=Ue(Ie);if(!Le)return;const Se=Pl();for(const[Pe,Ee]of Object.entries(Se))if(e.some(Ae=>Ae.tabKey===Pe)&&Ee===Le){Ie.preventDefault(),ee(Pe);return}},ve=Ie=>{if(Ie.defaultPrevented||Z)return;const Le=Ue(Ie);if(!Le)return;const Se=Ie.metaKey||Ie.ctrlKey||Ie.altKey;if(Ra(Ie.target))return;const Pe=ln(le),Ee=Object.entries(Pe).filter(([Ve,xe])=>!!xe&&(Ve==="splitActiveTabRight"||Ve==="splitActiveTabDown"||Ve==="floatActiveTab"||Ve==="popoutActiveTab"||Ve==="dockActiveTab"||Ve==="focusLeftPane"||Ve==="focusRightPane"||Ve==="focusUpPane"||Ve==="focusDownPane"||Ve==="moveActiveTabToLeftPane"||Ve==="moveActiveTabToRightPane"||Ve==="moveActiveTabToUpPane"||Ve==="moveActiveTabToDownPane"||Ve==="selectPreviousGroupTab"||Ve==="selectNextGroupTab"||Ve==="setActiveTabShortcut"||Ve==="hideCurrentTab")),Ae=Se?[Le]:[...se.slice(-1),Le].slice(-2),qe=Ae.join(" "),et=Ae[Ae.length-1],ct=Ee.find(([,Ve])=>Ve===qe);if(ct){Ie.preventDefault(),Y(),W(ct[0]);return}if(Ee.some(([,Ve])=>Ve.startsWith(`${qe} `))){Ie.preventDefault(),se=Ae,Q();return}const dt=Ee.find(([,Ve])=>Ve===et);if(dt){Ie.preventDefault(),Y(),W(dt[0]);return}if(Ee.some(([,Ve])=>Ve.startsWith(`${et} `))){Ie.preventDefault(),se=[et],Q();return}Y()};return G.addEventListener("keydown",re),G.addEventListener("keydown",ve),()=>{Y(),G.removeEventListener("keydown",re),G.removeEventListener("keydown",ve)}});return()=>{for(const G of U)G()}},[Ue,le,F,ee,Z,W,e]);const Ne=A==="light"?ma:fa,ze=((rt=(Ge=(Je=w.current)==null?void 0:Je.activePanel)==null?void 0:Ge.group.element)==null?void 0:rt.ownerDocument)??document;return s.jsxs(Fl.Provider,{value:Ce,children:[s.jsx("div",{ref:v,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Id,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:wb,remote:jb},defaultTabComponent:Sb,watermarkComponent:kb,onReady:xt,singleTabMode:"default",tabAnimation:"smooth",theme:Ne,popoutUrl:"/popout.html"})}),N&&ar.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:N.x,top:N.y},children:Te.map(O=>{if(O.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},O.id);let U=s.jsx(Nu,{size:13,className:"shrink-0 opacity-70"}),G=()=>{};switch(O.id){case"dockInWindow":case"dockBackToGrid":U=s.jsx(Tu,{size:13,className:"shrink-0 opacity-70"}),G=()=>{je(N.tabKey),I(null)};break;case"moveBackToMain":U=s.jsx(Su,{size:13,className:"shrink-0 opacity-70"}),G=()=>{ge(N.tabKey),I(null)};break;case"floatAsPanel":U=s.jsx(Cu,{size:13,className:"shrink-0 opacity-70"}),G=()=>{ye(N.tabKey),I(null)};break;case"openInNewWindow":U=s.jsx(ku,{size:13,className:"shrink-0 opacity-70"}),G=()=>{we(N.tabKey),I(null)};break;case"setShortcut":G=se=>{se.stopPropagation(),De(N.tabKey),I(null)};break;case"removeShortcut":U=s.jsx(vt,{size:13,className:"shrink-0 opacity-70"}),G=()=>{const se={...ke};delete se[N.tabKey],$e(se),I(null)};break;case"hideTab":U=s.jsx(Oa,{size:13,className:"shrink-0 opacity-70"}),G=()=>{ce(N.tabKey),I(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 ${O.tone==="muted"?"text-text-muted":""}`,onMouseDown:gb,onClick:G,children:[U,s.jsx("span",{className:"flex-1 min-w-0",children:O.label}),O.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:O.shortcut}):null]},O.id)})}),N.sourceDocument.body),Z&&ar.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:()=>De(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:O=>O.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. ",le?"⌘+1":"Ctrl+1",", ",le?"⌥+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"})]})}),ze.body)]})}const Hl="adhdev-recent-launch-args-v1",Cb=8;function Ul(e){return String(e||"").trim().replace(/\s+/g," ")}function wo(e,t){return`${e.trim()}::${t.trim()}`}function jo(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Hl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function zl(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Hl,JSON.stringify(e))}catch{}}function La(e,t){var i;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((i=jo().byKey[wo(r,n)])==null?void 0:i.items)||[]}function Vl(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),i=Ul(r);if(!n||!a||!i)return;const c=jo(),l=wo(n,a),d=((u=c.byKey[l])==null?void 0:u.items)||[],m=[i,...d.filter(f=>f!==i)].slice(0,Cb);c.byKey[l]={items:m},zl(c)}function Tb(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),i=Ul(r);if(!n||!a||!i)return;const c=jo(),l=wo(n,a),m=(((u=c.byKey[l])==null?void 0:u.items)||[]).filter(f=>f!==i);m.length>0?c.byKey[l]={items:m}:delete c.byKey[l],zl(c)}function Gl(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Vr({title:e,description:t,action:r,children:n,className:a="",contentClassName:i=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),r?s.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?s.jsx("div",{className:t||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function Mb({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 ql({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:i,onRefresh:c,onOpenHistory:l,onClearSelection:d}){const m=i?Rl(i):null,u=Mb({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Vr,{title:"Saved history",description:no(),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:Np()})]}),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 Yl({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 Ab({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:i,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||i,children:l.label},l.id))})]})}function Zn(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>hs(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>hs(a,"acp"))?"acp":null}function Er(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ib({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:c,onListMeshes:l,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Ve,xe;const u=fr(),f=o.useMemo(()=>[...e].sort(Ga),[e]),[x,C]=o.useState(((Ve=f[0])==null?void 0:Ve.id)||""),y=o.useMemo(()=>f.find(z=>z.id===x)||f[0],[x,f]),p=o.useMemo(()=>((y==null?void 0:y.workspaces)||[]).map(z=>({id:z.id,path:z.path,label:z.label})),[y]),g=(y==null?void 0:y.defaultWorkspaceId)||null,[b,h]=o.useState("workspace"),[k,S]=o.useState(""),[j,A]=o.useState(""),[M,w]=o.useState([]),[v,B]=o.useState(""),[_,T]=o.useState(!1),[D,K]=o.useState(null),[L,N]=o.useState(""),[I,F]=o.useState(Zn(f[0])),[P,$]=o.useState(""),[H,J]=o.useState(""),[he,ie]=o.useState([]),[te,be]=o.useState(""),[we,ge]=o.useState([]),[X,ce]=o.useState(!1),[ye,ne]=o.useState(!1),[de,je]=o.useState(""),[me,pe]=o.useState(!1),[ee,ue]=o.useState(()=>wt()),[oe,q]=o.useState(null),[V,le]=o.useState(!1),[ke,Z]=o.useState(""),[De,$e]=o.useState(null),[Fe,Ue]=o.useState(!1),[W,Ce]=o.useState(""),[Te,_e]=o.useState([]),[Be,He]=o.useState(!1),[Xe,st]=o.useState(""),[mt,ht]=o.useState(!1),xt=o.useRef(null),Ne=o.useRef(0);o.useEffect(()=>{var z;!x&&((z=f[0])!=null&&z.id)&&C(f[0].id)},[x,f]),o.useEffect(()=>{!y||!(!y.workspaces||!y.availableProviders||!y.detectedIdes||!y.recentLaunches)||u(y.id,{minFreshMs:3e4}).catch(()=>{})},[u,y]);const ze=o.useMemo(()=>((y==null?void 0:y.availableProviders)||[]).filter(z=>hs(z,"cli")),[y]),Je=o.useMemo(()=>((y==null?void 0:y.availableProviders)||[]).filter(z=>hs(z,"acp")),[y]),Ge=o.useMemo(()=>((y==null?void 0:y.detectedIdes)||[]).map(z=>({id:z.type,label:z.name||z.type,meta:z.running?"Detected locally":"Available to open"})),[y]),rt=o.useMemo(()=>I==="cli"?ze.map(z=>({id:z.type,label:z.displayName||z.type,meta:"CLI provider"})):I==="acp"?Je.map(z=>({id:z.type,label:z.displayName||z.type,meta:"ACP provider"})):Ge,[Je,I,ze,Ge]),O=o.useMemo(()=>M.find(z=>z.id===v)||null,[M,v]),U=o.useMemo(()=>ze.find(z=>z.type===P)||null,[ze,P]),G=o.useMemo(()=>Cl(U==null?void 0:U.meshCoordinator,{meshId:(O==null?void 0:O.id)||"",workspace:(O==null?void 0:O.workspace)||""}),[U,O]),se=De||G,E=o.useCallback(async z=>{T(!0),N("");try{const Me=await l(z);w(Me),B(R=>{var ae;return Me.some(fe=>fe.id===R)?R:((ae=Me[0])==null?void 0:ae.id)||""}),K(z)}catch(Me){w([]),B(""),K(z),N(Me instanceof Error?Me.message:"Could not load meshes")}finally{T(!1)}},[l]);o.useEffect(()=>{var Me;if(!y)return;if(xt.current!==y.id){xt.current=y.id,h("workspace"),S(g||((Me=p[0])==null?void 0:Me.id)||"__home__"),A(""),w([]),B(""),K(null),N(""),F(Zn(y)),$(""),J(""),be(""),ge([]),ne(!1),je(""),ue(wt()),Z(""),$e(null);return}S(R=>{var ae;return R==="__custom__"||R==="__home__"||p.some(fe=>fe.id===R)?R:g||((ae=p[0])==null?void 0:ae.id)||"__home__"}),F(R=>R==="ide"&&Ge.length>0||R==="cli"&&ze.length>0||R==="acp"&&Je.length>0?R:Zn(y))},[Je.length,ze.length,g,Ge.length,y,p]),o.useEffect(()=>{!y||b!=="mesh"||D===y.id||_||E(y.id)},[E,D,_,y,b]),o.useEffect(()=>{b==="mesh"&&I!=="cli"&&ze.length>0&&F("cli")},[I,ze.length,b]),o.useEffect(()=>{var z;I&&(rt.some(Me=>Me.id===P)||$(((z=rt[0])==null?void 0:z.id)||""))},[I,rt,P]),o.useEffect(()=>{$e(null)},[y==null?void 0:y.id,v,P,b]);const Y=o.useCallback(async(z,Me)=>{const R=Ne.current+1;return Ne.current=R,ce(!0),je(""),m(z,Me).then(ae=>{Ne.current===R&&ge(ae)}).catch(ae=>{Ne.current===R&&(ge([]),je(ae instanceof Error?ae.message:"Could not load saved sessions"))}).finally(()=>{Ne.current===R&&(ce(!1),ne(!0))})},[m]),Q=o.useCallback((z,Me)=>{ie(La(z,Me))},[]);o.useEffect(()=>{Ne.current+=1,be(""),ue(wt()),!y||!P||I==="ide"?ie([]):Q(y.id,P),ne(!1),ge([]),je(""),ce(!1)},[I,Q,Y,y,P]),o.useEffect(()=>{if(!te)return;const z=we.find(Me=>Me.providerSessionId===te);z!=null&&z.canResume||be("")},[we,te]);const re=k==="__custom__"?j.trim():k==="__home__"?"":((xe=p.find(z=>z.id===k))==null?void 0:xe.path)||"",ve=o.useMemo(()=>y?t.filter(z=>z.id!==y.id&&z.daemonId===y.id).map(z=>z.workspace):[],[t,y]),Ie=o.useMemo(()=>((y==null?void 0:y.recentLaunches)||[]).map(z=>z.workspace),[y]),Le=o.useCallback(z=>{const Me=String(z.workspace||"").trim();if(!Me)return;const R=p.find(ae=>Er(ae.path)===Er(Me));if(R){S(R.id),A("");return}S("__custom__"),A(Me)},[p]),Se=o.useCallback(z=>{const Me=String(z.workspace||"").trim();if(!Me)return{workspaceId:null,workspacePath:null};const R=p.find(ae=>Er(ae.path)===Er(Me));return R?{workspaceId:R.id,workspacePath:null}:{workspaceId:null,workspacePath:Me}},[p]),Pe=o.useMemo(()=>we.find(z=>z.providerSessionId===te)||null,[we,te]),Ee=o.useMemo(()=>{var Me;if(I!=="cli"||!y||!P)return null;const z=((Me=ze.find(R=>R.type===P))==null?void 0:Me.displayName)||P;return{routeId:y.id,daemonId:y.id,providerSessionId:te||void 0,transport:"pty",mode:"chat",agentName:z,agentType:P,status:"idle",title:z,messages:[],ideType:P,workspaceName:re,workspacePath:re,displayPrimary:z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${y.id}:${P}`,machineName:Tt(y,{fallbackId:y.id})}},[I,ze,re,y,te,P]),Ae=o.useCallback(()=>{var Me;if(!y)return;S("__custom__"),Ue(!0),st("");const z=yn(y.platform,gn(j.trim(),re,ve,Ie,y.defaultWorkspacePath,(Me=p.find(R=>R.id===g))==null?void 0:Me.path,p.map(R=>R.path)));He(!0),n(y.id,z).then(R=>{Ce(R.path),A(R.path),_e(R.directories)}).catch(R=>{st(R instanceof Error?R.message:"Could not load folder")}).finally(()=>He(!1))},[j,g,Ie,ve,n,re,y,p]),qe=o.useCallback(z=>{y&&(He(!0),st(""),n(y.id,z).then(Me=>{Ce(Me.path),A(Me.path),_e(Me.directories)}).catch(Me=>{st(Me instanceof Error?Me.message:"Could not load folder")}).finally(()=>He(!1)))},[n,y]),et=o.useCallback(async()=>{if(!y||!re)return;ht(!0),Z("");const z=await a(y.id,re);if(ht(!1),!z.ok){Z(z.error||"Could not save workspace");return}Z("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,re,y]),ct=o.useCallback(async()=>{if(!y)return;if(b==="mesh"){if(!v||!P)return;le(!0),Z(""),$e(null);const R=await d(y.id,v,P);if(le(!1),!R.ok){if(R.code==="mesh_coordinator_manual_mcp_setup_required"&&R.manualSetup){$e(R.manualSetup),Z("Manual MCP setup required before this provider can act as mesh coordinator.");return}Z(R.error||"Could not start mesh coordinator");return}r();return}if(!I||!P)return;le(!0),Z("");const z=H.trim()?H.trim().split(/\s+/).filter(Boolean):[],Me=I==="ide"?await i(y.id,P,{workspacePath:re||null}):await c(y.id,I,P,{workspaceId:k!=="__home__"&&k!=="__custom__"?k:null,workspacePath:k==="__custom__"&&re||null,resumeSessionId:I==="cli"&&te?te:null,cliArgs:z});if(le(!1),!Me.ok){Z(Me.error||"Could not start session");return}I!=="ide"&&H.trim()&&(Vl(y.id,P,H),Q(y.id,P)),r()},[I,H,Q,r,i,d,c,re,y,v,te,P,k,b]),ft=b==="mesh"?"Start mesh coordinator":I?Yc(I,I==="cli"&&!!te):"Start",dt=b==="mesh"?"Starting coordinator…":I?Xc(I,I==="cli"&&!!te):"Starting…",yt=f.length>5;return y?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[s.jsx(Vr,{title:"Machine",children:yt?s.jsx("select",{"aria-label":"Machine",value:y.id,onChange:z=>C(z.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:V,children:f.map(z=>s.jsx("option",{value:z.id,children:Tt(z,{fallbackId:z.id})},z.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:f.map(z=>{const Me=Tt(z,{fallbackId:z.id}),R=y.id===z.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${Me}`,"aria-pressed":R,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${R?"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:()=>C(z.id),disabled:V,title:Me,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${z.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Me})]},z.id)})})}),s.jsxs(Vr,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:b==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ae,disabled:V,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(z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":b===z.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${b===z.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:()=>{h(z.id),Z(""),z.id==="mesh"&&y&&D!==y.id&&!_&&E(y.id)},disabled:V,children:[s.jsx("div",{className:"text-sm font-semibold",children:z.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:z.desc})]},z.id))}),b==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:k,onChange:z=>{const Me=z.target.value;S(Me),Me==="__custom__"?Ae():Z("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:V,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),p.map(z=>s.jsxs("option",{value:z.id,children:[z.id===g?"⭐ ":"",hn(z.path,z.label)||z.path]},z.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:k==="__home__"?"Launch without a workspace.":re||"Select a workspace folder."}),k==="__custom__"&&re&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ae,disabled:V,children:[s.jsx(ms,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:V||mt,children:mt?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[_&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!_&&L&&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:L}),!_&&!L&&M.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."}),M.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:M.map(z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":v===z.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>B(z.id),disabled:V,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:z.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[z.repoIdentity||"Repo mesh",typeof z.nodesCount=="number"?` · ${z.nodesCount} node${z.nodesCount===1?"":"s"}`:""]}),z.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",z.workspace]})]},z.id))}),O&&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(Ab,{workspaceMode:b,activeKind:I,cliEnabled:ze.length>0,ideEnabled:Ge.length>0,acpEnabled:Je.length>0,busy:V,onSelect:F}),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:I==="ide"?"Choose IDE":I==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[rt.map(z=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${P===z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(z.id),disabled:V,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:z.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:z.meta})]},z.id)),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."})]})]}),b==="mesh"&&se&&s.jsx(Yl,{setup:se,providerName:(U==null?void 0:U.displayName)||(U==null?void 0:U.name)||P}),b!=="mesh"&&I!=="ide"&&s.jsxs(Vr,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:H,onChange:z=>J(z.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:V}),he.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:he.map(z=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>J(z),disabled:V,title:z,children:z},z))})]}),b!=="mesh"&&I==="cli"&&s.jsx(ql,{busy:V,savedSessionsLoading:X,savedSessionsError:de,selectedSession:Pe,onRefresh:()=>{!y||!P||Y(y.id,P)},onOpenHistory:()=>{!y||!P||(pe(!0),Gl({hasLoadedInitialResults:ye,isLoading:X})&&Y(y.id,P))},onClearSelection:()=>be("")}),ke&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ke.includes("saved")||ke.includes("requested")||ke.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:ke})]}),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:V,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:ct,disabled:V||(b==="mesh"?!v||!P||I!=="cli"||_:!I||!P||k==="__custom__"&&!re),children:[s.jsx(Ha,{size:14}),V?dt:ft]})]})]})}),Fe&&s.jsx(wn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:W,directories:Te,busy:Be,error:Xe,onClose:()=>Ue(!1),onNavigate:qe,onConfirm:z=>{A(z),Ce(z),S("__custom__"),Ue(!1)}}),me&&Ee&&s.jsx(io,{activeConv:Ee,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:we,isSavedSessionsLoading:X,isResumingSavedSessionId:oe,savedHistoryFilters:ee,missingWorkspaceResumePath:re||null,onSavedHistoryFiltersChange:ue,onClose:()=>pe(!1),onNewChat:()=>{be(""),pe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!y||!P||Y(y.id,P)},onResumeSavedSession:z=>{if(!y||!P||oe||!z.canResume)return;const Me=Se(z);be(z.providerSessionId),Le(z),q(z.providerSessionId),pe(!1),le(!0),Z(""),c(y.id,"cli",P,{workspaceId:Me.workspaceId,workspacePath:Me.workspacePath,resumeSessionId:z.providerSessionId}).then(R=>{if(!R.ok){Z(R.error||"Could not resume session");return}r()}).finally(()=>{le(!1),q(R=>R===z.providerSessionId?null:R)})}})]}):null}function Rb(e,t){const{sendCommand:r}=gt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);o.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=Lb(n);return{remoteUrl:n,githubUrl:l,loading:i}}function Lb(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 Xl=5e3;function _b(e){return`git:${e}`}function Pb({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Xl}){return{type:"subscribe",topic:"workspace.git",key:_b(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function ko(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function xs(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 Db(e){const t=ko(e);return(t==null?void 0:t.success)===!1?{status:null,error:xs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:xs(t,"Git status response did not include status")}}function Eb(e){const t=ko(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:xs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:xs(t,"Git diff summary response did not include diffSummary")}}function ea(e){return e===void 0||typeof e=="boolean"}function $b(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&ea(t.binary)&&ea(t.truncated)&&ea(t.staged)}function Bb(e){const t=ko(e);return(t==null?void 0:t.success)===!1?{diff:null,error:xs(t,"Git file diff request failed")}:$b(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:xs(t,"Git file diff response did not include a valid diff object")}}function Kb({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Xl}){const{sendCommand:i,sendData:c}=gt(),l=typeof t=="string"?t.trim():"",d=!!(r&&e&&l),[m,u]=o.useState(null),[f,x]=o.useState(null),[C,y]=o.useState(!1),[p,g]=o.useState(null),b=o.useCallback(async()=>{if(!(!d||!e||!l)){y(!0),g(null);try{const k=Db(await i(e,"git_status",{workspace:l}));if(k.error){u(null),x(null),g(k.error);return}if(u(k.status),!n){x(null);return}const S=Eb(await i(e,"git_diff_summary",{workspace:l}));if(S.error){x(null),g(S.error);return}x(S.diffSummary)}catch(k){g(xs(k,"Git status request failed"))}finally{y(!1)}}},[d,e,n,i,l]),h=o.useMemo(()=>l?Pb({workspace:l,includeDiffSummary:n,intervalMs:a}):null,[n,a,l]);return o.useEffect(()=>{if(!d||!e||!l||!h){u(null),x(null),y(!1),g(null);return}const k=c?Ht.subscribe({sendData:c},e,h,S=>{var j,A;S.workspace===l&&(u(S.status),x(S.diffSummary??null),g(((j=S.status)==null?void 0:j.error)||((A=S.diffSummary)==null?void 0:A.error)||null),y(!1))},{retryIntervalMs:1e3}):null;return b(),()=>{k==null||k()}},[d,e,b,h,c,l]),{status:m,diffSummary:f,loading:C,error:p,refresh:b}}const Wb={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},Ob={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 Li(e){return e.split("/").pop()??e}function Fb(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Hb({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(i=>{const c=n===i.path,l=Wb[i.status]??"?",d=Ob[i.status]??"text-zinc-400",m=Fb(i.path),u=Li(i.path),f=i.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(i),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:i.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}),i.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Li(i.oldPath)]}),f]}),!i.binary&&(i.insertions>0||i.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[i.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",i.insertions]}),i.insertions>0&&i.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),i.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",i.deletions]})]}),i.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${i.path}-${i.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 Ub(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 zb({diff:e,binary:t,truncated:r,loading:n,error:a,className:i=""}){const c=o.useRef(null);if(o.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 ${i}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${i}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${i}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${i}`,children:"No diff available."});const l=e.split(`
63
+ `);return s.jsxs("div",{ref:c,className:`overflow-auto ${i}`,children:[s.jsx("div",{className:"py-1",children:l.map((d,m)=>Ub(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 Vb(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,i]of Object.entries(n))r.push(`${a}: ${i.slice(0,5).join(", ")}${i.length>5?` (+${i.length-5} more)`:""}`);return r.join(`
64
+ `)}function Jl({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=gt(),{status:a,diffSummary:i,loading:c,error:l,refresh:d}=Kb({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=o.useState(null),[f,x]=o.useState(null),[C,y]=o.useState(""),[p,g]=o.useState(!1),[b,h]=o.useState(!1),[k,S]=o.useState(null),[j,A]=o.useState(null),{githubUrl:M}=Rb(e,t),w=o.useCallback(async K=>{if(!((m==null?void 0:m.path)===K.path&&!m.loading)){u({path:K.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const L=await n(e,"git_diff_file",{workspace:t,path:K.path,staged:K.staged}),N=Bb(L);if(N.error||!N.diff){u({path:K.path,diff:"",binary:!1,truncated:!1,loading:!1,error:N.error??"Failed to load diff"});return}u({path:K.path,diff:N.diff.diff,binary:N.diff.binary??!1,truncated:N.diff.truncated??!1,loading:!1,error:null})}catch(L){const N=L instanceof Error?L.message:"Failed to load diff";u({path:K.path,diff:"",binary:!1,truncated:!1,loading:!1,error:N})}}},[e,n,m,t]),v=o.useCallback(K=>{y(""),g(!1),S(null),A(null),x(K)},[]),B=o.useCallback(()=>{x(null),S(null),h(!1)},[]),_=o.useCallback(async()=>{var K,L,N;if(f){h(!0),S(null);try{let I;f==="checkpoint"?I=await n(e,"git_checkpoint",{workspace:t,message:C,includeUntracked:p}):f==="stash"?I=await n(e,"git_stash_push",{workspace:t,message:C,includeUntracked:p}):f==="stash_pop"?I=await n(e,"git_stash_pop",{workspace:t}):f==="checkout_files"&&m&&(I=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const F=(I==null?void 0:I.result)??I;if((F==null?void 0:F.success)===!1||F!=null&&F.error){S((F==null?void 0:F.error)??"Action failed"),h(!1);return}f==="checkpoint"?A(`Checkpoint created: ${((L=(K=F==null?void 0:F.checkpoint)==null?void 0:K.commit)==null?void 0:L.slice(0,7))??"done"}`):f==="stash"?A(`Stashed as ${((N=F==null?void 0:F.stash)==null?void 0:N.stashRef)??"stash@{0}"}`):f==="stash_pop"?A("Stash restored"):(A("File reverted"),u(null)),x(null),await d()}catch(I){S(I instanceof Error?I.message:"Action failed")}finally{h(!1)}}},[f,n,e,t,C,p,m,d]),T=!!(a!=null&&a.hasConflicts),D=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:K=>{K.target===K.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}),M&&s.jsx("a",{href:`${M}/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(vt,{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"}),D===0&&!a.error&&s.jsx("span",{className:"text-emerald-500",children:"clean"}),i&&i.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[i.files.length," file",i.files.length!==1?"s":"",i.totalInsertions>0&&s.jsxs("span",{className:"text-emerald-500",children:[" +",i.totalInsertions]}),i.totalDeletions>0&&s.jsxs("span",{className:"text-red-400",children:[" -",i.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&&!i&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),i&&s.jsx(Hb,{files:i.files,truncated:i.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:w}),!c&&!i&&!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(zb,{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"})})]}),j&&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:j}),s.jsx("button",{onClick:()=>A(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:()=>v("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:()=>v("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:()=>v("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:()=>v("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"}),i&&i.files.length>0&&s.jsx("button",{onClick:()=>{const K=Vb((a==null?void 0:a.branch)??null,i);navigator.clipboard.writeText(K),A("Copied to clipboard"),setTimeout(()=>A(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:C,onChange:K=>y(K.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:K=>g(K.target.checked)}),"Include untracked files"]})]}),k&&s.jsx("p",{className:"text-xs text-red-400",children:k}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:B,disabled:b,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:b||(f==="checkpoint"||f==="stash")&&!C.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:b?"Working…":"Confirm"})]})]})})]})})}function Gb({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=o.useState(!1),[i,c]=o.useState(!1),[l,d]=o.useState(!1),[m,u]=o.useState(!1),[f,x]=o.useState(!1),[C,y]=o.useState("quickstart"),[p,g]=o.useState("workspace"),b=o.useMemo(()=>!t&&!e,[t,e]),h=o.useCallback(w=>{a(w),w&&c(!1)},[]),k=o.useCallback(w=>{c(w),w&&a(!1)},[]),S=o.useCallback(()=>{y(r===0?"quickstart":"shortcuts"),g("workspace"),d(!0),a(!1),c(!1)},[r]),j=o.useCallback(()=>{d(!1)},[]),A=o.useCallback(()=>{u(!0)},[]),M=o.useCallback(()=>{u(!1)},[]);return o.useEffect(()=>{if(!b){x(!1);return}x(!0);const w=window.setTimeout(()=>{x(!1)},1e4);return()=>window.clearTimeout(w)},[b]),{inboxOpen:n,hiddenOpen:i,shortcutHelpOpen:l,newSessionOpen:m,guideNudgeVisible:f,guideTab:C,shortcutSection:p,isDesktopDashboard:b,setGuideTab:y,setShortcutSection:g,handleInboxOpenChange:h,handleHiddenOpenChange:k,handleOpenShortcutHelp:S,closeShortcutHelp:j,openNewSession:A,closeNewSession:M}}function qb(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 Yb(e){return e instanceof Error?e.message:String(e||"")}function Xb(e){const t=Yb(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Jb({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:f,ides:x,actionLogs:C,sendDaemonCommand:y,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:b,initialDataLoaded:h,userName:k,requestedMobileTabKey:S,onRequestedMobileTabConsumed:j,requestedMachineId:A,onRequestedMachineConsumed:M,requestedMobileSection:w,onRequestedMobileSectionConsumed:v,containerRef:B,isSplitMode:_,numGroups:T,groupSizes:D,groupedConvs:K,clearedTabs:L,focusedGroup:N,focusGroup:I,moveTabToGroup:F,splitTabRelative:P,closeGroup:$,handleResizeStart:H,groupActiveTabIds:J,setGroupActiveTab:he,groupTabOrders:ie,setGroupTabOrder:te,toggleHiddenTab:be,visibleConversations:we,requestedDesktopTabKey:ge,onRequestedDesktopTabConsumed:X,onDesktopActiveTabChange:ce,onRequestScrollToBottom:ye,onHideConversation:ne,onShowHiddenConversation:de,onShowAllHiddenConversations:je,scrollToBottomRequest:me,machineEntries:pe,layoutProfile:ee,onBrowseMachineDirectory:ue,onSaveMachineWorkspace:oe,onLaunchMachineIde:q,onLaunchMachineProvider:V,onListMachineMeshes:le,onLaunchMeshCoordinator:ke,onListMachineSavedSessions:Z,notifications:De,notificationUnreadCount:$e,liveSessionInboxState:Fe,onMarkNotificationRead:Ue,onMarkNotificationUnread:W,onDeleteNotification:Ce}){const Te=Ct.useRef(null),{inboxOpen:_e,hiddenOpen:Be,shortcutHelpOpen:He,newSessionOpen:Xe,guideNudgeVisible:st,guideTab:mt,shortcutSection:ht,isDesktopDashboard:xt,setGuideTab:Ne,setShortcutSection:ze,handleInboxOpenChange:Je,handleHiddenOpenChange:Ge,handleOpenShortcutHelp:rt,closeShortcutHelp:O,openNewSession:U,closeNewSession:G}=Gb({isMobile:t,showMobileChatMode:e,visibleConversationCount:we.length}),[se,E]=Ct.useState(null),Y=Ct.useCallback((xe,z)=>{E({daemonId:xe,workspace:z})},[]),Q=Ct.useCallback(xe=>{var z;ar.flushSync(()=>{de(xe)}),(z=Te.current)==null||z.restoreHiddenTabToSavedLocation(xe.tabKey)},[de]),re=Ct.useCallback(xe=>{var Me;const z=u.find(R=>ja(R,xe))||f.find(R=>ja(R,xe));z&&(f.some(R=>R.tabKey===z.tabKey)&&Q(z),ce(z.tabKey),(Me=Te.current)==null||Me.activateConversationTab(z.tabKey),ye(z.tabKey,"notification-open")),Ue(xe.id),Je(!1)},[Q,f,u,ce,Ue,ye]),ve=Ct.useCallback(()=>{var z;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((z=Te.current)==null||z.resetAllPanelsToMain(),Ge(!1))},[Ge]),Ie=Ct.useCallback(async xe=>{var fe;if(!r)return;const z=(fe=r.modalButtons)==null?void 0:fe[xe];if(!z)return;const Me=Ls(r);if(!Me)return;const R=z.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),ae=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(R);try{await y(Me,"resolve_action",{button:z,action:ae?"approve":"reject",buttonIndex:xe,...rs(r)})}catch(Ke){Xb(Ke)||console.error("[Shortcut approval] Failed:",Ke)}},[r,y]),{isMac:Le,actionDefinitions:Se,actionShortcuts:Pe,shortcutListening:Ee,shortcutListeningDraft:Ae,setShortcutListening:qe,setShortcutListeningDraft:et,saveShortcuts:ct}=ub({enabled:xt&&!He,onTrigger:xe=>{var z,Me,R,ae,fe,Ke,Re,We,ot,Nt,pt,Vt,xr,br,gr,yr;if(xe==="openShortcutHelp"){rt();return}if(xe==="openNewSession"){U();return}if(xe==="hideCurrentTab"){r&&ne(r);return}if(xe==="toggleHiddenTabs"){Ge(!Be);return}if(xe==="openHistoryForActiveTab"){r&&!Ze(r)&&i(r);return}if(xe==="openRemoteForActiveTab"){r&&!tt(r)&&!Ze(r)&&c(r);return}if(xe==="splitActiveTabRight"){(z=Te.current)==null||z.splitActiveTabRight();return}if(xe==="splitActiveTabDown"){(Me=Te.current)==null||Me.splitActiveTabDown();return}if(xe==="floatActiveTab"){(R=Te.current)==null||R.floatActiveTab();return}if(xe==="popoutActiveTab"){(ae=Te.current)==null||ae.popoutActiveTab();return}if(xe==="dockActiveTab"){(fe=Te.current)==null||fe.dockActiveTab();return}if(xe==="focusLeftPane"){(Ke=Te.current)==null||Ke.focusLeftPane();return}if(xe==="focusRightPane"){(Re=Te.current)==null||Re.focusRightPane();return}if(xe==="focusUpPane"){(We=Te.current)==null||We.focusUpPane();return}if(xe==="focusDownPane"){(ot=Te.current)==null||ot.focusDownPane();return}if(xe==="moveActiveTabToLeftPane"){(Nt=Te.current)==null||Nt.moveActiveTabToLeftPane();return}if(xe==="moveActiveTabToRightPane"){(pt=Te.current)==null||pt.moveActiveTabToRightPane();return}if(xe==="moveActiveTabToUpPane"){(Vt=Te.current)==null||Vt.moveActiveTabToUpPane();return}if(xe==="moveActiveTabToDownPane"){(xr=Te.current)==null||xr.moveActiveTabToDownPane();return}if(xe==="triggerPrimaryApprovalAction"){Ie(0);return}if(xe==="triggerSecondaryApprovalAction"){Ie(1);return}if(xe==="triggerTertiaryApprovalAction"){Ie(2);return}if(xe==="setActiveTabShortcut"){(br=Te.current)==null||br.setShortcutForActiveTab();return}if(xe==="selectPreviousGroupTab"){(gr=Te.current)==null||gr.activatePreviousTabInGroup();return}if(xe==="selectNextGroupTab"){(yr=Te.current)==null||yr.activateNextTabInGroup();return}!r||!tt(r)||Ze(r)||xe==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),ft=Ct.useCallback(()=>{O(),qe(null),et([])},[O,qe,et]),dt=Ct.useMemo(()=>ht==="all"?Se:Se.filter(xe=>qb(xe)===ht),[Se,ht]),yt=Ct.useCallback(()=>{const xe=Object.fromEntries(Se.map(z=>[z.id,""]));ct(xe)},[Se,ct]),Ve=Ct.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const xe=Object.fromEntries(Se.map(z=>[z.id,z.defaultShortcut]));ct(xe)},[Se,ct]);return Ct.useEffect(()=>{const xe=z=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?z.metaKey&&z.key.toLowerCase()==="w":z.ctrlKey&&z.key.toLowerCase()==="w")&&(z.preventDefault(),r&&ne&&ne(r))};return window.addEventListener("keydown",xe),()=>window.removeEventListener("keydown",xe)},[r,ne]),Ct.useEffect(()=>{if(!He||Ee)return;const xe=z=>{z.key==="Escape"&&(z.preventDefault(),ft())};return window.addEventListener("keydown",xe,!0),()=>window.removeEventListener("keydown",xe,!0)},[ft,He,Ee]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(yp,{activeConv:r,wsStatus:n,isConnected:a,conversations:we,hiddenConversations:f,onOpenHistory:i,onHideConversation:ne,onShowConversation:Q,onShowAllHidden:je,onResetPanelsToMain:ve,notifications:De,notificationUnreadCount:$e,onOpenNotification:re,onMarkNotificationRead:Ue,onMarkNotificationUnread:W,onDeleteNotification:Ce,inboxOpen:_e,onInboxOpenChange:Je,hiddenOpen:Be,onHiddenOpenChange:Ge,onOpenNewSession:t?void 0:U,onOpenDashboardGuide:rt,guideNudgeVisible:st,actionShortcuts:Pe,onOpenRemote:()=>{!r||tt(r)||Ze(r)||c(r)},onStopCli:l,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:Y}),e?s.jsx(Zx,{conversations:u,hiddenConversations:f,ides:x,actionLogs:C,sendDaemonCommand:y,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:b,userName:k,requestedActiveTabKey:S,onRequestedActiveTabConsumed:j,requestedMachineId:A,onRequestedMachineConsumed:M,requestedMobileSection:w,onRequestedMobileSectionConsumed:v,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowAllHiddenConversations:je,onHideConversation:ne,onOpenNewSession:U,liveSessionInboxState:Fe}):t?s.jsx(ib,{containerRef:B,isSplitMode:_,numGroups:T,groupSizes:D,groupedConvs:K,clearedTabs:L,ides:x,actionLogs:C,sendDaemonCommand:y,setActionLogs:p,isStandalone:b,hasRegisteredMachines:pe.length>0,userName:k,focusedGroup:N,focusGroup:I,moveTabToGroup:F,splitTabRelative:P,closeGroup:$,handleResizeStart:H,groupActiveTabIds:J,setGroupActiveTab:he,groupTabOrders:ie,setGroupTabOrder:te,toggleHiddenTab:be,onOpenNewSession:U,allowTabShortcuts:!1,liveSessionInboxState:Fe}):s.jsx(Nb,{visibleConversations:we,clearedTabs:L,ides:x,actionLogs:C,sendDaemonCommand:y,setActionLogs:p,isStandalone:b,hasRegisteredMachines:pe.length>0,initialDataLoaded:h,userName:k,toggleHiddenTab:be,actionShortcuts:Pe,registerActionHandlers:xe=>{Te.current=xe},onActiveTabChange:ce,requestedActiveTabKey:ge,onRequestedActiveTabConsumed:X,onRequestScrollToBottom:ye,scrollToBottomRequest:me,onOpenNewSession:U,liveSessionInboxState:Fe,layoutProfile:ee}),Xe&&s.jsx(Ib,{machines:pe,ides:x,onClose:G,onBrowseDirectory:ue,onSaveWorkspace:oe,onLaunchIde:q,onLaunchProvider:V,onListMeshes:le,onLaunchMeshCoordinator:ke,onListSavedSessions:Z}),se&&s.jsx(Jl,{daemonId:se.daemonId,workspace:se.workspace,onClose:()=>E(null)}),He&&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:ft,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:xe=>xe.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:ft,"aria-label":"Close dashboard guide",children:s.jsx(vt,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(xe=>s.jsx("button",{type:"button",className:`btn btn-sm ${mt===xe.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ne(xe.id),children:xe.label},xe.id))}),mt==="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 ",Le?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),mt==="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."]})]})]})]}),mt==="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(xe=>s.jsx("button",{type:"button",className:`btn btn-sm ${ht===xe.id?"btn-primary":"btn-secondary"}`,onClick:()=>ze(xe.id),children:xe.label},xe.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:yt,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:Ve,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:dt.map(xe=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ee===xe.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:xe.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:xe.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:xe.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:Ee===xe.id?Ae.length>0?`${Ae.join(" ")} ...`:"Listening...":Pe[xe.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{qe(xe.id),et([])},children:Ee===xe.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const z={...Pe};z[xe.id]="",ct(z)},children:"Disable"})]})]})},xe.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Le?"⌘⇧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 ta=[{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 Qb({onClose:e}){const[t,r]=o.useState(0),n=ta[t],a=t===ta.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:i=>{i.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(vt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:ta.map((i,c)=>s.jsx("div",{style:{width:c===t?24:8,height:8,borderRadius:4,background:c===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:n.icon})," ",n.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
65
65
  @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
66
66
  @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
67
- `})]})}function Jb({hasExtensions:e,ideName:t,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:t}),n.map(i=>{const c=r===i.tabKey,l=i.status==="waiting_approval",d=i.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${c?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(i.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),i.title,l&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},i.tabKey)})]}):null}function Qb({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,c]=o.useState(()=>a||"native"),l=o.useMemo(()=>Jc(t),[t]),d=o.useMemo(()=>e?io(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),m=o.useMemo(()=>d.find(p=>p.streamSource==="native"),[d]),u=o.useMemo(()=>d.filter(p=>p.streamSource==="agent-stream"),[d]),f=o.useMemo(()=>e?Dt(d,e.id):null,[d,e]);o.useEffect(()=>{a&&c(a)},[a]),o.useEffect(()=>{if(a||!f)return;const p=f.streamSource==="native"?"native":f.tabKey;!p||i===p||i==="native"&&c(p)},[i,f,a]),o.useEffect(()=>{var p;i!=="native"&&(u.some(j=>j.tabKey===i)||c(((p=u[0])==null?void 0:p.tabKey)||"native"))},[i,u]),o.useEffect(()=>{i==="native"&&(m||u[0]&&c(u[0].tabKey))},[i,m,u]);const x=o.useMemo(()=>i==="native"&&m?m:u.find(p=>p.tabKey===i)||f||m||u[0],[i,m,f,u]),C=o.useMemo(()=>u.map(p=>({tabKey:p.tabKey,title:Uc(p)||n,status:p.status})),[u,n]),g=o.useCallback(p=>{if(p)return d.find(j=>wa(j,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[d]);return{activeChatTab:i,setActiveChatTab:c,activeConv:x,conversations:d,extensionTabs:C,hasExtensions:C.length>0,resolveConversationByTarget:g}}function Zb({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:i,setActionLogs:c,isStandalone:l,userName:d,onOpenHistory:m,onConversationChange:u,onClose:f}){const[x,C]=o.useState("split"),[g,p]=o.useState(()=>Xt(e)?"native":e.tabKey),j=o.useRef(null),b=o.useMemo(()=>t||r.find(I=>I.id===e.routeId),[e.routeId,t,r]),h=o.useMemo(()=>it((b==null?void 0:b.type)||""),[b==null?void 0:b.type]),{conversations:y,extensionTabs:S,hasExtensions:k}=Qb({ideData:b,allIdes:r,connectionStates:n,ideName:h||"IDE",preferredTabKey:Xt(e)?void 0:e.tabKey}),A=o.useMemo(()=>b?Dt(y,b.id):null,[b,y]);o.useEffect(()=>{const I=j.current,W={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(j.current=W,!(I&&I.routeId===W.routeId&&I.tabKey===W.tabKey&&I.streamSource===W.streamSource)){if(Xt(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(g==="native"){if(y.some(I=>I.streamSource==="native"))return;(A==null?void 0:A.streamSource)==="agent-stream"&&p(A.tabKey);return}if(!y.some(I=>I.tabKey===g)){if((A==null?void 0:A.streamSource)==="agent-stream"){p(A.tabKey);return}p("native")}},[y,g,A]);const M=o.useMemo(()=>g==="native"?y.find(I=>I.streamSource==="native")||e:y.find(I=>I.tabKey===g)||e,[e,y,g]),w=ll(M),v=o.useMemo(()=>w.status||w.modalMessage||w.modalButtons?{...M,...w.status?{status:w.status}:{},...w.modalMessage!==void 0?{modalMessage:w.modalMessage}:{},...w.modalButtons!==void 0?{modalButtons:w.modalButtons}:{}}:M,[M,w]),B=mr(v),_=xn({sendDaemonCommand:i,activeConv:v,setActionLogs:c,isStandalone:l}),{connScreenshot:T,screenshotUsage:D,handleRemoteAction:K}=Dl({doId:B,targetSessionId:Tc(v),connState:v.connectionState||"new",viewMode:x}),L=o.useMemo(()=>a.filter(I=>I.routeId===v.tabKey),[a,v.tabKey]);o.useEffect(()=>{u==null||u(v)},[v,u]),o.useEffect(()=>{const I=W=>{W.key==="Escape"&&f()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[f]);const N=o.useCallback(I=>{I.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:N,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(Mt,{size:16})}),s.jsx("span",{className:"truncate",children:Ya(M)||"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(I=>{const W=x===I;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${W?"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:()=>C(I),title:I==="split"?"Split view":"Remote only",children:I==="split"?s.jsx(du,{size:15}):s.jsx(Mt,{size:15})},I)})}),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(M),title:"Chat History",children:[s.jsx(Ka,{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 ${x==="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:[x!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${x==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(Jb,{hasExtensions:k,ideName:h||"IDE",activeChatTab:g,extensionTabs:S,onSelectTab:p}),s.jsx(fc,{activeConv:v,onModalButton:_.handleModalButton}),s.jsx(ka,{activeConv:v,ideEntry:b,showMetaChips:!1,handleSendChat:_.handleSendChat,isSendingChat:_.isSendingChat,sendFeedbackMessage:_.sendFeedbackMessage,handleFocusAgent:_.handleFocusAgent,isFocusingAgent:_.isFocusingAgent,actionLogs:L,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${x==="split"?"order-1 md:order-2":""}`,children:s.jsx(uc,{addLog:()=>{},connState:v.connectionState||"new",connScreenshot:T,screenshotUsage:D,transportType:v.transport,onAction:K})})]})]})})}function eg({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=op(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[s.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",i,"?"]}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:t?"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.":"This provider does not support graceful stop. Force Stop will end the runtime immediately."})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),s.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Force Stop"}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function tg({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(up,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(oo,{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(Zb,{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&&(tt(r.targetConv)||Ze(r.targetConv))&&s.jsx(eg,{activeConv:r.targetConv,canSaveAndStop:tt(r.targetConv)&&!Ze(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(Xc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&s.jsx(Xb,{onClose:i.onClose})]})}function sg({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:i}){return e.length===0?null:s.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(dr,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[r?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(c=>{const l=Tt(c,{fallbackId:c.id}),d=n[c.id],m=c.version||c.daemonVersion||"unknown",u=c.versionUpdateRequired===!0,x=jl(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:x})]},c.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:s.jsx(yt,{size:16})})]})}function rg(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function ng(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 ag(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>ng(t)).map(t=>t.id)}}function og(){var Ao,Io,Ro,Lo;const{sendCommand:e}=bt(),t=fr(),r=cl(),n=Ea(),a=$s(),[i,c]=Id(),l=i.get("activeTab"),d=((Ao=n.state)==null?void 0:Ao.openRemoteForTabKey)||null,m=((Io=n.state)==null?void 0:Io.openMachineId)||null,u=((Ro=n.state)==null?void 0:Ro.mobileSection)||null,f=Wc(),x=f.ides||[],C=f.initialLoaded??!0,{updateRouteChats:g,setToasts:p}=f,[j,b]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),h=f.toasts||[],y=f.wsStatus||"connected",S=f.isConnected??!0,k=f.connectionStates||{},A=f.showReconnected||!1,{layoutProfile:M,groupAssignments:w,updateGroupAssignments:v,focusedGroup:B,updateFocusedGroup:_,focusGroup:T,groupActiveTabIds:D,updateGroupActiveTabIds:K,setGroupActiveTab:L,groupTabOrders:N,updateGroupTabOrders:I,setGroupTabOrder:W,groupSizes:P,updateGroupSizes:$,isMobile:H,hasHydratedStoredLayout:J,hydrateStoredLayout:he,focusConversationTab:ie}=Gh(),[te,be]=o.useState(()=>mo());o.useEffect(()=>lh(be),[]);const we=o.useMemo(()=>rg({isMobile:H,mobileViewMode:te}),[H,te]),[ge,X]=o.useState([]),[ce,ye]=o.useState({}),[ne,de]=o.useState({});ur("Dashboard",{ideCount:x.length,toastCount:h.length,focusedGroup:B,groupCount:Object.keys(w).length,actionLogCount:ge.length});const je=o.useMemo(()=>x.filter(Ye=>Ye.type==="adhdev-daemon").sort(Va),[x]),me=je[0],pe=!!me;o.useEffect(()=>{const{metadataDaemonIds:Ye,runtimeDaemonIds:Rt}=ag(je);for(const Ws of Ye)t(Ws,{minFreshMs:3e4}).catch(()=>{});for(const Ws of Rt)r(Ws,{minFreshMs:3e4}).catch(()=>{})},[t,r,je]);const ee=(me==null?void 0:me.terminalBackend)||null,ue=me?Tt(me,{fallbackId:me.id}):null,oe=(me==null?void 0:me.id)||null,q=o.useMemo(()=>vh(x,ce),[x,ce]),{hiddenTabs:V,hideTarget:le,toggleTarget:ke,showTarget:Z,showAllTabs:De}=yh(),{conversations:$e,visibleConversations:Fe,visibleTabKeys:Ue,resolveConversationBySessionId:O,resolveConversationByTarget:Ce}=Lh({ides:q,connectionStates:k,clearedTabs:ne,hiddenTabs:V}),Te=o.useMemo(()=>new Map($e.map(Ye=>[Ye.tabKey,Ye])),[$e]);$f(Fe,we),o.useEffect(()=>{Object.keys(ce).length!==0&&ye(Ye=>wh(Ye,x))},[x,ce]);const _e=o.useMemo(()=>Ju(x),[x]),{notifications:Be,unreadCount:He}=lx({conversations:$e,liveSessionInboxState:_e}),{handleMarkDashboardNotificationRead:Xe,handleMarkDashboardNotificationUnread:st,handleDeleteDashboardNotification:mt}=dx({notifications:Be,sendDaemonCommand:e}),{containerRef:ht,normalizedGroupAssignments:xt,numGroups:Ne,isSplitMode:ze,groupedConvs:Je,moveTabToGroup:Ge,closeGroup:rt,handleResizeStart:F,splitTabRelative:U}=ex({groupAssignments:w,updateGroupAssignments:v,updateFocusedGroup:_,updateGroupActiveTabIds:K,updateGroupTabOrders:I,groupSizes:P,updateGroupSizes:$,isMobile:H,visibleConversations:Fe,visibleTabKeys:Ue}),{activeConv:G,openDesktopConversation:se,requestScrollToBottom:E,scrollToBottomRequest:Y,setDesktopActiveTab:Q}=kx({isMobile:H,conversations:$e,visibleConversations:Fe,groupActiveTabIds:D,focusedGroup:B,groupedConvs:Je,setSearchParams:c});Cx({activeConv:G,isMobile:H,liveSessionInboxState:_e,sendDaemonCommand:e});const{requestedDesktopTabKey:re,requestedMobileTabKey:ve,consumeRequestedActiveTab:Ie}=_h({isMobile:H,urlActiveTab:l,resolveConversationBySessionId:O,setSearchParams:c}),{remoteDialogConv:Le,remoteDialogIdeEntry:Se,remoteDialogActiveConv:Pe,setRemoteDialogActiveConv:Ee,openRemoteDialog:Ae,closeRemoteDialog:qe,cliStopDialogOpen:et,cliStopTargetConv:ct,requestCliStop:ft,cancelCliStop:dt,confirmCliStop:gt}=Ax({isMobile:H,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:re,conversations:$e,ides:x,resolveConversationByTarget:Ce,activeConv:G,sendDaemonCommand:e}),{historyModalOpen:Ve,openHistoryModal:xe,closeHistoryModal:z,historyTargetConv:Me,isSavedSessionHistoryTarget:R,isHistoryCreatingChat:ae,isHistoryRefreshingHistory:fe,handleHistorySwitchSession:Ke,handleHistoryNewChat:Re,handleHistoryRefresh:We,savedHistorySessions:ot,savedHistoryFilters:Nt,setSavedHistoryFilters:pt,missingWorkspaceResumePath:Vt,isSavedHistoryLoading:xr,resumingSavedHistorySessionId:br,handleRefreshSavedHistory:gr,handleResumeSavedHistorySession:yr}=Tx({activeConv:G,remoteDialogConv:Le,remoteDialogActiveConv:Pe,ides:x,sendDaemonCommand:e,updateRouteChats:g,setToasts:p,setClearedTabs:de,setSearchParams:c}),td=o.useMemo(()=>Fe,[Fe]),vr=H&&te==="chat",sd=o.useMemo(()=>$e.filter(Ye=>fo(V,Ye)),[$e,V]),Co=o.useCallback(Ye=>{const Rt=new URLSearchParams(i);Rt.set("activeTab",Ye),c(Rt,{replace:!0})},[i,c]),{trackPendingLaunch:rd}=yx({ides:x,conversations:$e,onOpenSession:Co}),{handleBrowseMachineDirectory:nd,handleSaveMachineWorkspace:ad,handleLaunchMachineIde:od,handleLaunchMachineProvider:id,handleListMachineMeshes:cd,handleLaunchMeshCoordinator:ld,handleListMachineSavedSessions:dd,setActiveCliViewMode:ud}=vx({sendDaemonCommand:e,trackPendingLaunch:rd,onOpenSession:Co,activeConv:G,ides:x,setCliViewModeOverrides:ye});jh({visibleConversations:Fe,clearedTabs:ne,setClearedTabs:de,setActionLogs:X}),Ph({ides:x,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Ce});const{isRefreshingHistory:md,handleRefreshHistory:fd}=wl({sendDaemonCommand:e,activeConv:G,chats:(Lo=x.find(Ye=>Ye.id===(G==null?void 0:G.routeId)))==null?void 0:Lo.chats,updateRouteChats:g,setToasts:p,setClearedTabs:de});Yh({urlActiveTab:H&&!vr?l:null,conversations:$e,resolveConversationBySessionId:O,normalizedGroupAssignments:xt,hasHydratedStoredLayout:H&&!vr?J:!0,hydrateStoredLayout:H&&!vr?he:()=>{},focusConversationTab:ie,setSearchParams:c,historyModalOpen:Ve,activeConv:G,isRefreshingHistory:md,ides:x,handleRefreshHistory:fd});const pd=o.useMemo(()=>!G||!tt(G)||Ze(G)?null:Ks(G),[G]),{versionMismatchDaemons:hd,hasRequiredVersionDaemons:To,targetVersion:xd,versionBannerDismissed:bd,setVersionBannerDismissed:gd,upgradingDaemons:yd,handleBannerUpgrade:vd}=sx({ides:x,sendDaemonCommand:e}),Mo=o.useCallback(Ye=>{Z(Ye),se(Ye)},[se,Z]),wd=o.useCallback(Ye=>{le(Ye)},[le]);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(mp,{terminalBackend:ee,isStandalone:pe,machineLabel:ue,machineKey:oe}),(!bd||To)&&s.jsx(sg,{daemons:hd,targetVersion:xd,required:To,upgradingDaemons:yd,onUpgrade:vd,onDismiss:()=>gd(!0)}),s.jsx(Yb,{showMobileChatMode:vr,isMobile:H,activeConv:G,wsStatus:y,isConnected:S,onOpenHistory:Ye=>{Ye&&Ee(Ye),xe()},onOpenRemote:Ae,onStopCli:ft,activeCliViewMode:pd,onSetActiveCliViewMode:ud,mobileChatConversations:td,ides:x,actionLogs:ge,sendDaemonCommand:e,setActionLogs:X,setCliViewModeOverrides:ye,isStandalone:pe,initialDataLoaded:C,userName:f.userName,requestedMobileTabKey:ve,onRequestedMobileTabConsumed:Ie,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:ht,isSplitMode:ze,numGroups:Ne,groupSizes:P,groupedConvs:Je,clearedTabs:ne,focusedGroup:B,focusGroup:T,moveTabToGroup:Ge,splitTabRelative:U,closeGroup:rt,handleResizeStart:F,groupActiveTabIds:D,setGroupActiveTab:L,groupTabOrders:N,setGroupTabOrder:W,toggleHiddenTab:Ye=>ke(Te.get(Ye)||{tabKey:Ye}),visibleConversations:Fe,hiddenConversations:sd,requestedDesktopTabKey:re,onRequestedDesktopTabConsumed:Ie,onDesktopActiveTabChange:Q,onRequestScrollToBottom:E,onHideConversation:wd,onShowHiddenConversation:Mo,onShowAllHiddenConversations:De,scrollToBottomRequest:Y,machineEntries:je,layoutProfile:M,onBrowseMachineDirectory:nd,onSaveMachineWorkspace:ad,onLaunchMachineIde:od,onLaunchMachineProvider:id,onListMachineMeshes:cd,onLaunchMeshCoordinator:ld,onListMachineSavedSessions:dd,notifications:Be,notificationUnreadCount:He,liveSessionInboxState:_e,onMarkNotificationRead:Xe,onMarkNotificationUnread:st,onDeleteNotification:mt}),s.jsx("style",{children:`
67
+ `})]})}function Zb({hasExtensions:e,ideName:t,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:t}),n.map(i=>{const c=r===i.tabKey,l=i.status==="waiting_approval",d=i.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${c?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(i.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),i.title,l&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},i.tabKey)})]}):null}function eg({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,c]=o.useState(()=>a||"native"),l=o.useMemo(()=>Qc(t),[t]),d=o.useMemo(()=>e?co(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),m=o.useMemo(()=>d.find(p=>p.streamSource==="native"),[d]),u=o.useMemo(()=>d.filter(p=>p.streamSource==="agent-stream"),[d]),f=o.useMemo(()=>e?Dt(d,e.id):null,[d,e]);o.useEffect(()=>{a&&c(a)},[a]),o.useEffect(()=>{if(a||!f)return;const p=f.streamSource==="native"?"native":f.tabKey;!p||i===p||i==="native"&&c(p)},[i,f,a]),o.useEffect(()=>{var p;i!=="native"&&(u.some(g=>g.tabKey===i)||c(((p=u[0])==null?void 0:p.tabKey)||"native"))},[i,u]),o.useEffect(()=>{i==="native"&&(m||u[0]&&c(u[0].tabKey))},[i,m,u]);const x=o.useMemo(()=>i==="native"&&m?m:u.find(p=>p.tabKey===i)||f||m||u[0],[i,m,f,u]),C=o.useMemo(()=>u.map(p=>({tabKey:p.tabKey,title:zc(p)||n,status:p.status})),[u,n]),y=o.useCallback(p=>{if(p)return d.find(g=>ja(g,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[d]);return{activeChatTab:i,setActiveChatTab:c,activeConv:x,conversations:d,extensionTabs:C,hasExtensions:C.length>0,resolveConversationByTarget:y}}function tg({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:i,setActionLogs:c,isStandalone:l,userName:d,onOpenHistory:m,onConversationChange:u,onClose:f}){const[x,C]=o.useState("split"),[y,p]=o.useState(()=>Xt(e)?"native":e.tabKey),g=o.useRef(null),b=o.useMemo(()=>t||r.find(I=>I.id===e.routeId),[e.routeId,t,r]),h=o.useMemo(()=>it((b==null?void 0:b.type)||""),[b==null?void 0:b.type]),{conversations:k,extensionTabs:S,hasExtensions:j}=eg({ideData:b,allIdes:r,connectionStates:n,ideName:h||"IDE",preferredTabKey:Xt(e)?void 0:e.tabKey}),A=o.useMemo(()=>b?Dt(k,b.id):null,[b,k]);o.useEffect(()=>{const I=g.current,F={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(g.current=F,!(I&&I.routeId===F.routeId&&I.tabKey===F.tabKey&&I.streamSource===F.streamSource)){if(Xt(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(y==="native"){if(k.some(I=>I.streamSource==="native"))return;(A==null?void 0:A.streamSource)==="agent-stream"&&p(A.tabKey);return}if(!k.some(I=>I.tabKey===y)){if((A==null?void 0:A.streamSource)==="agent-stream"){p(A.tabKey);return}p("native")}},[k,y,A]);const M=o.useMemo(()=>y==="native"?k.find(I=>I.streamSource==="native")||e:k.find(I=>I.tabKey===y)||e,[e,k,y]),w=dl(M),v=o.useMemo(()=>w.status||w.modalMessage||w.modalButtons?{...M,...w.status?{status:w.status}:{},...w.modalMessage!==void 0?{modalMessage:w.modalMessage}:{},...w.modalButtons!==void 0?{modalButtons:w.modalButtons}:{}}:M,[M,w]),B=mr(v),_=bn({sendDaemonCommand:i,activeConv:v,setActionLogs:c,isStandalone:l}),{connScreenshot:T,screenshotUsage:D,handleRemoteAction:K}=El({doId:B,targetSessionId:Mc(v),connState:v.connectionState||"new",viewMode:x}),L=o.useMemo(()=>a.filter(I=>I.routeId===v.tabKey),[a,v.tabKey]);o.useEffect(()=>{u==null||u(v)},[v,u]),o.useEffect(()=>{const I=F=>{F.key==="Escape"&&f()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[f]);const N=o.useCallback(I=>{I.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:N,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(Mt,{size:16})}),s.jsx("span",{className:"truncate",children:Xa(M)||"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(I=>{const F=x===I;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${F?"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:()=>C(I),title:I==="split"?"Split view":"Remote only",children:I==="split"?s.jsx(uu,{size:15}):s.jsx(Mt,{size:15})},I)})}),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(M),title:"Chat History",children:[s.jsx(Wa,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:f,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${x==="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:[x!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${x==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(Zb,{hasExtensions:j,ideName:h||"IDE",activeChatTab:y,extensionTabs:S,onSelectTab:p}),s.jsx(hc,{activeConv:v,onModalButton:_.handleModalButton}),s.jsx(Sa,{activeConv:v,ideEntry:b,showMetaChips:!1,handleSendChat:_.handleSendChat,isSendingChat:_.isSendingChat,sendFeedbackMessage:_.sendFeedbackMessage,handleFocusAgent:_.handleFocusAgent,isFocusingAgent:_.isFocusingAgent,actionLogs:L,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${x==="split"?"order-1 md:order-2":""}`,children:s.jsx(fc,{addLog:()=>{},connState:v.connectionState||"new",connScreenshot:T,screenshotUsage:D,transportType:v.transport,onAction:K})})]})]})})}function sg({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=cp(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[s.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",i,"?"]}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:t?"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.":"This provider does not support graceful stop. Force Stop will end the runtime immediately."})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),s.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Force Stop"}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function rg({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(fp,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(io,{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(tg,{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&&(tt(r.targetConv)||Ze(r.targetConv))&&s.jsx(sg,{activeConv:r.targetConv,canSaveAndStop:tt(r.targetConv)&&!Ze(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(Jc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&s.jsx(Qb,{onClose:i.onClose})]})}function ng({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:i}){return e.length===0?null:s.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(dr,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[r?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(c=>{const l=Tt(c,{fallbackId:c.id}),d=n[c.id],m=c.version||c.daemonVersion||"unknown",u=c.versionUpdateRequired===!0,x=kl(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:x})]},c.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:s.jsx(vt,{size:16})})]})}function ag(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function og(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 ig(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>og(t)).map(t=>t.id)}}function cg(){var Io,Ro,Lo,_o;const{sendCommand:e}=gt(),t=fr(),r=ll(),n=$a(),a=$s(),[i,c]=Rd(),l=i.get("activeTab"),d=((Io=n.state)==null?void 0:Io.openRemoteForTabKey)||null,m=((Ro=n.state)==null?void 0:Ro.openMachineId)||null,u=((Lo=n.state)==null?void 0:Lo.mobileSection)||null,f=Oc(),x=f.ides||[],C=f.initialLoaded??!0,{updateRouteChats:y,setToasts:p}=f,[g,b]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),h=f.toasts||[],k=f.wsStatus||"connected",S=f.isConnected??!0,j=f.connectionStates||{},A=f.showReconnected||!1,{layoutProfile:M,groupAssignments:w,updateGroupAssignments:v,focusedGroup:B,updateFocusedGroup:_,focusGroup:T,groupActiveTabIds:D,updateGroupActiveTabIds:K,setGroupActiveTab:L,groupTabOrders:N,updateGroupTabOrders:I,setGroupTabOrder:F,groupSizes:P,updateGroupSizes:$,isMobile:H,hasHydratedStoredLayout:J,hydrateStoredLayout:he,focusConversationTab:ie}=Yh(),[te,be]=o.useState(()=>fo());o.useEffect(()=>uh(be),[]);const we=o.useMemo(()=>ag({isMobile:H,mobileViewMode:te}),[H,te]),[ge,X]=o.useState([]),[ce,ye]=o.useState({}),[ne,de]=o.useState({});ur("Dashboard",{ideCount:x.length,toastCount:h.length,focusedGroup:B,groupCount:Object.keys(w).length,actionLogCount:ge.length});const je=o.useMemo(()=>x.filter(Ye=>Ye.type==="adhdev-daemon").sort(Ga),[x]),me=je[0],pe=!!me;o.useEffect(()=>{const{metadataDaemonIds:Ye,runtimeDaemonIds:Rt}=ig(je);for(const Ws of Ye)t(Ws,{minFreshMs:3e4}).catch(()=>{});for(const Ws of Rt)r(Ws,{minFreshMs:3e4}).catch(()=>{})},[t,r,je]);const ee=(me==null?void 0:me.terminalBackend)||null,ue=me?Tt(me,{fallbackId:me.id}):null,oe=(me==null?void 0:me.id)||null,q=o.useMemo(()=>jh(x,ce),[x,ce]),{hiddenTabs:V,hideTarget:le,toggleTarget:ke,showTarget:Z,showAllTabs:De}=wh(),{conversations:$e,visibleConversations:Fe,visibleTabKeys:Ue,resolveConversationBySessionId:W,resolveConversationByTarget:Ce}=Ph({ides:q,connectionStates:j,clearedTabs:ne,hiddenTabs:V}),Te=o.useMemo(()=>new Map($e.map(Ye=>[Ye.tabKey,Ye])),[$e]);Kf(Fe,we),o.useEffect(()=>{Object.keys(ce).length!==0&&ye(Ye=>kh(Ye,x))},[x,ce]);const _e=o.useMemo(()=>Qu(x),[x]),{notifications:Be,unreadCount:He}=ux({conversations:$e,liveSessionInboxState:_e}),{handleMarkDashboardNotificationRead:Xe,handleMarkDashboardNotificationUnread:st,handleDeleteDashboardNotification:mt}=mx({notifications:Be,sendDaemonCommand:e}),{containerRef:ht,normalizedGroupAssignments:xt,numGroups:Ne,isSplitMode:ze,groupedConvs:Je,moveTabToGroup:Ge,closeGroup:rt,handleResizeStart:O,splitTabRelative:U}=sx({groupAssignments:w,updateGroupAssignments:v,updateFocusedGroup:_,updateGroupActiveTabIds:K,updateGroupTabOrders:I,groupSizes:P,updateGroupSizes:$,isMobile:H,visibleConversations:Fe,visibleTabKeys:Ue}),{activeConv:G,openDesktopConversation:se,requestScrollToBottom:E,scrollToBottomRequest:Y,setDesktopActiveTab:Q}=Nx({isMobile:H,conversations:$e,visibleConversations:Fe,groupActiveTabIds:D,focusedGroup:B,groupedConvs:Je,setSearchParams:c});Mx({activeConv:G,isMobile:H,liveSessionInboxState:_e,sendDaemonCommand:e});const{requestedDesktopTabKey:re,requestedMobileTabKey:ve,consumeRequestedActiveTab:Ie}=Dh({isMobile:H,urlActiveTab:l,resolveConversationBySessionId:W,setSearchParams:c}),{remoteDialogConv:Le,remoteDialogIdeEntry:Se,remoteDialogActiveConv:Pe,setRemoteDialogActiveConv:Ee,openRemoteDialog:Ae,closeRemoteDialog:qe,cliStopDialogOpen:et,cliStopTargetConv:ct,requestCliStop:ft,cancelCliStop:dt,confirmCliStop:yt}=Rx({isMobile:H,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:re,conversations:$e,ides:x,resolveConversationByTarget:Ce,activeConv:G,sendDaemonCommand:e}),{historyModalOpen:Ve,openHistoryModal:xe,closeHistoryModal:z,historyTargetConv:Me,isSavedSessionHistoryTarget:R,isHistoryCreatingChat:ae,isHistoryRefreshingHistory:fe,handleHistorySwitchSession:Ke,handleHistoryNewChat:Re,handleHistoryRefresh:We,savedHistorySessions:ot,savedHistoryFilters:Nt,setSavedHistoryFilters:pt,missingWorkspaceResumePath:Vt,isSavedHistoryLoading:xr,resumingSavedHistorySessionId:br,handleRefreshSavedHistory:gr,handleResumeSavedHistorySession:yr}=Ax({activeConv:G,remoteDialogConv:Le,remoteDialogActiveConv:Pe,ides:x,sendDaemonCommand:e,updateRouteChats:y,setToasts:p,setClearedTabs:de,setSearchParams:c}),sd=o.useMemo(()=>Fe,[Fe]),vr=H&&te==="chat",rd=o.useMemo(()=>$e.filter(Ye=>po(V,Ye)),[$e,V]),To=o.useCallback(Ye=>{const Rt=new URLSearchParams(i);Rt.set("activeTab",Ye),c(Rt,{replace:!0})},[i,c]),{trackPendingLaunch:nd}=wx({ides:x,conversations:$e,onOpenSession:To}),{handleBrowseMachineDirectory:ad,handleSaveMachineWorkspace:od,handleLaunchMachineIde:id,handleLaunchMachineProvider:cd,handleListMachineMeshes:ld,handleLaunchMeshCoordinator:dd,handleListMachineSavedSessions:ud,setActiveCliViewMode:md}=jx({sendDaemonCommand:e,trackPendingLaunch:nd,onOpenSession:To,activeConv:G,ides:x,setCliViewModeOverrides:ye});Sh({visibleConversations:Fe,clearedTabs:ne,setClearedTabs:de,setActionLogs:X}),Eh({ides:x,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Ce});const{isRefreshingHistory:fd,handleRefreshHistory:pd}=jl({sendDaemonCommand:e,activeConv:G,chats:(_o=x.find(Ye=>Ye.id===(G==null?void 0:G.routeId)))==null?void 0:_o.chats,updateRouteChats:y,setToasts:p,setClearedTabs:de});Jh({urlActiveTab:H&&!vr?l:null,conversations:$e,resolveConversationBySessionId:W,normalizedGroupAssignments:xt,hasHydratedStoredLayout:H&&!vr?J:!0,hydrateStoredLayout:H&&!vr?he:()=>{},focusConversationTab:ie,setSearchParams:c,historyModalOpen:Ve,activeConv:G,isRefreshingHistory:fd,ides:x,handleRefreshHistory:pd});const hd=o.useMemo(()=>!G||!tt(G)||Ze(G)?null:Ks(G),[G]),{versionMismatchDaemons:xd,hasRequiredVersionDaemons:Mo,targetVersion:bd,versionBannerDismissed:gd,setVersionBannerDismissed:yd,upgradingDaemons:vd,handleBannerUpgrade:wd}=nx({ides:x,sendDaemonCommand:e}),Ao=o.useCallback(Ye=>{Z(Ye),se(Ye)},[se,Z]),jd=o.useCallback(Ye=>{le(Ye)},[le]);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(pp,{terminalBackend:ee,isStandalone:pe,machineLabel:ue,machineKey:oe}),(!gd||Mo)&&s.jsx(ng,{daemons:xd,targetVersion:bd,required:Mo,upgradingDaemons:vd,onUpgrade:wd,onDismiss:()=>yd(!0)}),s.jsx(Jb,{showMobileChatMode:vr,isMobile:H,activeConv:G,wsStatus:k,isConnected:S,onOpenHistory:Ye=>{Ye&&Ee(Ye),xe()},onOpenRemote:Ae,onStopCli:ft,activeCliViewMode:hd,onSetActiveCliViewMode:md,mobileChatConversations:sd,ides:x,actionLogs:ge,sendDaemonCommand:e,setActionLogs:X,setCliViewModeOverrides:ye,isStandalone:pe,initialDataLoaded:C,userName:f.userName,requestedMobileTabKey:ve,onRequestedMobileTabConsumed:Ie,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:ht,isSplitMode:ze,numGroups:Ne,groupSizes:P,groupedConvs:Je,clearedTabs:ne,focusedGroup:B,focusGroup:T,moveTabToGroup:Ge,splitTabRelative:U,closeGroup:rt,handleResizeStart:O,groupActiveTabIds:D,setGroupActiveTab:L,groupTabOrders:N,setGroupTabOrder:F,toggleHiddenTab:Ye=>ke(Te.get(Ye)||{tabKey:Ye}),visibleConversations:Fe,hiddenConversations:rd,requestedDesktopTabKey:re,onRequestedDesktopTabConsumed:Ie,onDesktopActiveTabChange:Q,onRequestScrollToBottom:E,onHideConversation:jd,onShowHiddenConversation:Ao,onShowAllHiddenConversations:De,scrollToBottomRequest:Y,machineEntries:je,layoutProfile:M,onBrowseMachineDirectory:ad,onSaveMachineWorkspace:od,onLaunchMachineIde:id,onLaunchMachineProvider:cd,onListMachineMeshes:ld,onLaunchMeshCoordinator:dd,onListMachineSavedSessions:ud,notifications:Be,notificationUnreadCount:He,liveSessionInboxState:_e,onMarkNotificationRead:Xe,onMarkNotificationUnread:st,onDeleteNotification:mt}),s.jsx("style",{children:`
68
68
  body { overflow: hidden; overscroll-behavior: none; }
69
- `}),s.jsx(tg,{historyModal:{open:Ve,targetConv:Me,ides:x,isCreatingChat:ae,isRefreshingHistory:R?!1:fe,savedSessions:ot,savedHistoryFilters:Nt,missingWorkspaceResumePath:Vt||null,onSavedHistoryFiltersChange:pt,isSavedSessionsLoading:xr,isResumingSavedSessionId:br,onClose:z,onNewChat:Re,onSwitchSession:Ke,onRefreshHistory:R?gr:We,onResumeSavedSession:yr},remoteDialog:{conversation:Le,ideEntry:Se,ides:x,connectionStates:k,actionLogs:ge,sendDaemonCommand:e,setActionLogs:X,isStandalone:pe,userName:f.userName,onOpenHistory:Ye=>{Ye&&Ee(Ye),xe()},onConversationChange:Ee,onClose:qe},cliStopDialog:{open:et,targetConv:ct,onCancel:dt,onStopNow:async()=>{await gt("hard")},onSaveAndStop:async()=>{await gt("save")}},connectionBanner:{wsStatus:y,showReconnected:A,loginUrl:f.connectionLoginUrl,onReconnect:f.retryServerConnection},toastOverlay:{toasts:h,onDismiss:Ye=>p(Rt=>Rt.filter(Ws=>Ws.id!==Ye)),onClick:Ye=>{if(Ye.targetKey){const Rt=Ce(Ye.targetKey);Rt&&(ie(Rt.tabKey,xt),Mo(Rt),E(Rt.tabKey,"toast-open"))}}},onboarding:{open:j,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}}})]})}function ig({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,d]=o.useState(null),[m,u]=o.useState(null),[f,x]=o.useState(!1),[C,g]=o.useState(null),[p,j]=o.useState(!1),[b,h]=o.useState(""),y=o.useRef(null),S=o.useCallback(P=>{y.current=P},[]),k=o.useCallback((P,$,H=!1)=>{c(J=>[...J.slice(-100),{timestamp:Date.now(),level:P,message:$}]),setTimeout(()=>{var J;return(J=a.current)==null?void 0:J.scrollIntoView({behavior:"smooth"})},100),H&&at.showToast($,P==="error"||P==="warn"?"warning":"success")},[a]),A=o.useCallback(P=>{const $=P instanceof Error?P.message:String(P||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),M=o.useCallback(async(P,$)=>{var H;if(!e||l)return!1;d(P),k("info",`Launching ${it(P)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const J={ideType:P,enableCdp:!0};(H=$==null?void 0:$.workspace)!=null&&H.trim()?J.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(J.useDefaultWorkspace=!0);const he=await r(e,"launch_ide",J);return k(he!=null&&he.success?"info":"error",he!=null&&he.success?`${it(P)} launched`:`Failed: ${he==null?void 0:he.error}`,!0),!!(he!=null&&he.success)}catch(J){return k("error",`Launch error: ${J.message}`,!0),!1}finally{d(null)}},[e,l,k,r]),w=o.useCallback(async P=>{if(!e)return{success:!1};const{cliType:$,dir:H,workspaceId:J,useDefaultWorkspace:he,useHome:ie,argsStr:te,model:be,resumeSessionId:we}=P;if(!$)return k("warn","Select a CLI or ACP provider first",!0),{success:!1};const ge=te?te.split(/\s+/).filter(Boolean):void 0,X=(H==null?void 0:H.trim())||(J?"(saved id)":he?"(default workspace)":ie?"(home)":"");k("info",`Launching ${$}${X?` in ${X}`:""}${be?` (model: ${be})`:""}...`),u($);try{const ce={cliType:$,cliArgs:ge,initialModel:be||void 0};H!=null&&H.trim()?ce.dir=H.trim():J?ce.workspaceId=J:he?ce.useDefaultWorkspace=!0:ie&&(ce.useHome=!0),we&&(ce.resumeSessionId=we);const ye=await r(e,"launch_cli",ce),ne=(ye==null?void 0:ye.result)||ye;return ye!=null&&ye.success?(k("info",`${$} launched`,!0),(ne==null?void 0:ne.launchSource)==="home"?k("info","📂 Running in home directory (explicit choice)"):(ne==null?void 0:ne.launchSource)==="defaultWorkspace"&&k("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ne==null?void 0:ne.sessionId}):(k("error",`Failed: ${(ye==null?void 0:ye.error)||(ne==null?void 0:ne.error)}`,!0),(ye==null?void 0:ye.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&g({cliType:$,argsStr:te,model:be}),{success:!1,sessionId:ne==null?void 0:ne.sessionId})}catch(ce){return A(ce)?(k("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(k("error",`Launch error: ${ce.message}`,!0),{success:!1})}finally{u(null)}},[e,k,A,r]),v=o.useCallback(async(P,$,H,J)=>e?P?$.trim()?w({cliType:P,dir:$,argsStr:H,model:J}):(g({cliType:P,argsStr:H,model:J}),{success:!1}):(k("warn","Select a provider",!0),{success:!1}):{success:!1},[e,k,w]),B=o.useCallback(async(P,$,H)=>{if(e&&window.confirm(`Stop ${P}?
70
- This will terminate the process.`))try{const J=await r(e,"stop_cli",{cliType:P,dir:$,targetSessionId:H});J!=null&&J.success?k("info",`${P} stopped`,!0):k("error",`Stop failed: ${(J==null?void 0:J.error)||"Unknown error"}`,!0)}catch(J){k("error",`Stop failed: ${J.message}`,!0)}},[e,k,r]),_=o.useCallback(async P=>{try{await r(P.daemonId,"restart_ide",{ideType:P.type}),k("info",`${it(P.type)} restart initiated`,!0)}catch($){k("error",`Restart failed: ${$.message}`,!0)}},[k,r]),T=o.useCallback(async P=>{if(window.confirm(`Stop ${it(P.type)}?
71
- This will disconnect CDP and optionally kill the process.`))try{const $=await r(P.daemonId,"stop_ide",{ideType:P.type,killProcess:!0});$!=null&&$.success?k("info",`${it(P.type)} stopped`,!0):k("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){k("error",`Stop failed: ${$.message}`,!0)}},[k,r]),D=o.useCallback(async()=>{if(e)try{const P=await r(e,"detect_ides",{});k("info",`Found ${((P==null?void 0:P.result)||[]).length} IDE(s)`,!0)}catch(P){k("error",`Detection failed: ${P.message}`,!0)}},[e,k,r]),K=o.useCallback(async P=>{if(!e||!P.trim())return!1;x(!0);try{const $=await r(e,"workspace_add",{path:P.trim()});return $!=null&&$.success?(k("info",`Workspace added: ${P.trim()}`),!0):(k("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return k("error",$.message),!1}finally{x(!1)}},[e,k,r]),L=o.useCallback(async P=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){x(!0);try{const $=await r(e,"workspace_remove",{id:P});$!=null&&$.success?k("info","Workspace removed",!0):k("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){k("error",$.message,!0)}finally{x(!1)}}},[e,k,r]),N=o.useCallback(async P=>{var $;if(e){x(!0);try{const H=await r(e,"workspace_set_default",P===null?{clear:!0}:{id:P});if(H!=null&&H.success){k("info",P?"Default workspace updated":"Default workspace cleared",!0);const J=typeof H.defaultWorkspacePath=="string"?H.defaultWorkspacePath:"";J&&(($=y.current)==null||$.call(y,J))}else k("error",(H==null?void 0:H.error)||"workspace_set_default failed",!0)}catch(H){k("error",H.message,!0)}finally{x(!1)}}},[e,k,r]),I=o.useCallback(async P=>{var H;if(!e||!P.trim())return;const $=P.trim();x(!0);try{const J=await r(e,"workspace_set_default",{path:$});J!=null&&J.success?(k("info","Default workspace set from history"),(H=y.current)==null||H.call(y,$)):k("error",(J==null?void 0:J.error)||"Could not set default (path missing on disk?)")}catch(J){k("error",J.message)}finally{x(!1)}},[e,k,r]),W=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:b}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:b})}catch(P){k("warn",`Live nickname updated, but account sync failed: ${P.message}`)}k("info",`Nickname set to "${b||"(cleared)"}"`),j(!1)}catch(P){k("error",`Failed: ${P.message}`)}},[e,b,t,k,n,r]);return{logs:i,launchingIde:l,launchingAgentType:m,workspaceBusy:f,launchPick:C,setLaunchPick:g,editingNickname:p,setEditingNickname:j,nicknameInput:b,setNicknameInput:h,addLog:k,handleLaunchIde:M,runLaunchCliCore:w,handleLaunchCli:v,handleStopCli:B,handleRestartIde:_,handleStopIde:T,handleDetectIdes:D,handleWorkspaceAdd:K,handleWorkspaceRemove:L,handleWorkspaceSetDefault:N,handleWorkspaceResumePath:I,handleSaveNickname:W,setOnDefaultWorkspaceChanged:S}}function cg({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var _;const{workspaceBusy:l,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=i,[f,x]=o.useState(!1),[C,g]=o.useState(""),[p,j]=o.useState([]),[b,h]=o.useState(!1),[y,S]=o.useState(""),k=o.useCallback(async T=>{h(!0),S("");try{const D=await yn(c,e,T);g(D.path),j(D.directories)}catch(D){S(D instanceof Error?D.message:"Could not load folder")}finally{h(!1)}},[e,c]),A=o.useCallback(()=>{x(!0);const T=[...r.map(K=>K.workspace),...n.map(K=>K.workspace),...a.map(K=>K.workspace)],D=gn(t.platform,bn(T,t.defaultWorkspacePath,(t.workspaces||[]).map(K=>K.path)));k(D)},[a,n,r,k,t.defaultWorkspacePath,t.platform,t.workspaces]),M=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,w=t.availableMem??t.freeMem??t.totalMem,v=M&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-w)/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(Sr,{icon:s.jsx(nc,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?rm(t.uptime):"Waiting…"}),s.jsx(Sr,{icon:s.jsx(Mt,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(Sr,{icon:s.jsx(Oa,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(Sr,{icon:s.jsx(mu,{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(Oo,{value:M?Math.min(Math.round(B/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:M?`${B.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Oo,{value:v,max:100,label:"Memory",color:"#3b82f6",detail:M?`${Mn(t.totalMem-w)} / ${Mn(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Mn(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(ms,{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:A,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:pn(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(vn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:C,directories:p,busy:b,error:y,confirmLabel:"Add workspace",onClose:()=>x(!1),onNavigate:T=>{k(T)},onConfirm:T=>{(async()=>{if(!T)return;await d(T)&&x(!1)})()}})]})}function lg(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 dg(e,t,r){const n=[];for(const[a,i]of Object.entries(e.settings)){const c=r!=null&&r.filterSchema?r.filterSchema(i):i;if(c.length===0)continue;const l=t.find(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 ta(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 Ri(e){if(!e||typeof e!="object")return null;if(ta(e))return e;const t=e,r=t.result;return ta(r)?r:ta(t.sourceConfig)?t.sourceConfig:null}function ug(e){const t=e.trim();return t||null}const Li=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],mg=[{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 fg({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[d,m]=o.useState([]),[u,f]=o.useState(""),[x,C]=o.useState([]),[g,p]=o.useState(""),j=o.useRef(null),b=o.useRef(null),h=w=>{m(v=>v.includes(w)?v.filter(B=>B!==w):[...v,w])},y=()=>m([...Li]),S=()=>m([]);o.useEffect(()=>{var w;(w=j.current)==null||w.scrollIntoView({behavior:"smooth"})},[x]),o.useEffect(()=>()=>{b.current&&clearInterval(b.current)},[]);const k=o.useCallback(()=>{b.current&&clearInterval(b.current),b.current=setInterval(async()=>{try{const w=await r(e,"provider_auto_fix_status",{providerType:t.type});(w==null?void 0:w.running)===!1&&a==="running"&&(i("done"),C(v=>[...v,`
72
- ✅ Auto-fix completed!`]),b.current&&clearInterval(b.current))}catch{}},3e3)},[e,t.type,r,a]),A=async()=>{if(d.length!==0){i("running"),C(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${d.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),p("");try{const w=await r(e,"provider_auto_fix",{providerType:t.type,functions:d,agent:c,...u?{comment:u}:{}});w!=null&&w.success&&(w!=null&&w.started||w!=null&&w.running)?(C(v=>[...v,"✅ Agent started. Monitoring progress..."]),k()):(i("error"),p((w==null?void 0:w.error)||"Failed to start auto-fix"))}catch(w){i("error"),p((w==null?void 0:w.message)||"Connection failed")}}},M=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),C(w=>[...w,`
73
- ⚠️ Auto-fix cancelled.`]),i("done"),b.current&&clearInterval(b.current)}catch{}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:w=>w.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:t.icon||"🔧"}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",t.displayName]}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),s.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),s.jsx("div",{className:"flex gap-2",children:mg.map(w=>s.jsxs("button",{onClick:()=>l(w.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===w.value?w.color+"66":"var(--border-subtle)",background:c===w.value?w.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===w.value?w.color:"var(--text-primary)"},children:w.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:w.desc})]},w.value))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:y,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:Li.map(w=>s.jsxs("button",{onClick:()=>h(w),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(w)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(w)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(w)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(w)?"☑ ":"☐ ",w]},w))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",s.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:u,onChange:w=>f(w.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[x.map((w,v)=>s.jsx("div",{className:w.startsWith("✅")?"text-green-400":"",style:w.startsWith("❌")||w.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:w},v)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:j})]}),g&&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:g})]})]}),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:A,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:M,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{i("config"),C([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function pg({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var k;const i=t.filter(A=>A.category==="ide"),[c,l]=o.useState(((k=i[0])==null?void 0:k.type)||""),[d,m]=o.useState(""),[u,f]=o.useState(""),[x,C]=o.useState(!1),[g,p]=o.useState(""),[j,b]=o.useState(!1),h=A=>{const M=A.toLowerCase().replace(/[^a-z0-9-]/g,"");m(M),(!u||u===y(d))&&f(y(M))},y=A=>A.split("-").map(M=>M.charAt(0).toUpperCase()+M.slice(1)).join(" "),S=async()=>{if(!(!d||!u||!c)){C(!0),p("");try{const A=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:c});A!=null&&A.success||A!=null&&A.created?(b(!0),a==null||a(d)):p((A==null?void 0:A.error)||"Failed to create provider")}catch(A){p((A==null?void 0:A.message)||"Connection failed")}C(!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:A=>A.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:j?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:d})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(A=>s.jsxs("button",{onClick:()=>l(A.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===A.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===A.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:A.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===A.type?"#a78bfa":"var(--text-secondary)"},children:A.displayName})]},A.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:A=>h(A.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:A=>f(A.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"})]}),g&&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:g})]})}),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:j?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||x,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||x?.4:1},children:x?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function _i(e){return e==="cli"||e==="acp"}function hg(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 xg(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 Pi(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 bg({machineId:e,providers:t,sendDaemonCommand:r}){var K;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,d]=o.useState(null),[m,u]=o.useState("all"),[f,x]=o.useState(null),[C,g]=o.useState(!1),[p,j]=o.useState(null),[b,h]=o.useState("normal"),[y,S]=o.useState(""),[k,A]=o.useState(!1),M=o.useCallback(async()=>{if(e)try{const L=await r(e,"get_provider_source_config",{}),N=Ri(L);N&&(j(N),h(N.sourceMode),S(N.explicitProviderDir||""))}catch{}},[e,r]),w=o.useCallback(async()=>{if(e){c(!0);try{const L=await r(e,"get_provider_settings",{}),N=lg(L);if(N){const I=dg(N,t,{filterSchema:W=>W.filter(P=>P.key!=="enabled")});I.sort((W,P)=>W.category.localeCompare(P.category)||W.displayName.localeCompare(P.displayName)),a(I)}}catch{}c(!1)}},[e,t,r]);o.useEffect(()=>{n.length===0&&w(),p||M()},[]);const v=async(L,N,I)=>{d(`${L}.${N}`),a(W=>W.map(P=>P.type===L?{...P,values:{...P.values,[N]:I}}:P));try{const W=await r(e,"set_provider_setting",{providerType:L,key:N,value:I});W!=null&&W.success||w()}catch{w()}d(null)},B=async(L,N)=>{await v(L,"enabled",N),await w()},_=async L=>{d(`${L}.detect`);try{await r(e,"detect_provider",{providerType:L})}finally{await w(),d(null)}},T=async L=>{await v(L,"executablePath",""),await v(L,"executableArgs",""),await w()},D=async()=>{A(!0);try{const L=await r(e,"set_provider_source_config",{providerSourceMode:b,providerDir:ug(y)}),N=Ri(L);N?(j(N),h(N.sourceMode),S(N.explicitProviderDir||"")):await M(),await w()}catch{await M()}A(!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(L=>s.jsx("button",{onClick:()=>u(L),className:`machine-btn text-[10px] px-2 py-0.5 ${m===L?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:L.toUpperCase()},L))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>g(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),s.jsx("button",{onClick:w,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Running CLI sessions refresh provider scripts/config; process binary changes still apply on next launch."})]}),s.jsx("button",{onClick:M,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:b,onChange:L=>h(L.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:y,onChange:L=>S(L.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void D(),disabled:k,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:k?"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:"})," ",((K=p==null?void 0:p.providerRoots)==null?void 0:K.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(L=>L.category===m).length>1&&(()=>{const L=n.filter(P=>P.category===m),N=new Map;for(const P of L)for(const $ of P.schema){if($.type!=="boolean")continue;const H=N.get($.key),J=!!(P.values[$.key]??$.default);H?(H.onCount+=J?1:0,H.total+=1):N.set($.key,{label:$.label||$.key,onCount:J?1:0,total:1})}const I=[...N.entries()].filter(([,P])=>P.total===L.length);if(I.length===0)return null;const W=async(P,$)=>{for(const H of L)await v(H.type,P,$)};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 (",L.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:I.map(([P,$])=>{const H=$.onCount===$.total,J=$.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:$.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",$.onCount,"/",$.total,")"]}),s.jsx("button",{onClick:()=>void W(P,!0),disabled:H,className:`machine-btn text-[9px] px-1.5 py-px ${H?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void W(P,!1),disabled:J,className:`machine-btn text-[9px] px-1.5 py-px ${J?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},P)})})]})})(),i&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):s.jsx("div",{className:"flex flex-col gap-2",children:n.filter(L=>m==="all"||L.category===m).map(L=>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:L.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:L.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:L.category==="acp"?"rgba(139,92,246,0.08)":L.category==="cli"?"rgba(59,130,246,0.08)":L.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:L.category==="acp"?"#a78bfa":L.category==="cli"?"#60a5fa":L.category==="ide"?"#86efac":"var(--status-warning)"},children:L.category}),_i(L.category)&&(()=>{const N=t.find(P=>P.type===L.type),I=(N==null?void 0:N.enabled)===!0||L.values.enabled===!0,W=(N==null?void 0:N.machineStatus)||(I?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${xg(W)}`,children:hg(W)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void B(L.type,!I),disabled:l===`${L.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${I?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:I?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void _(L.type),disabled:!I||l===`${L.type}.detect`,title:I?"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 ${I?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void T(L.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),L.category==="ide"&&s.jsx("button",{onClick:()=>x(t.find(N=>N.type===L.type)||{type:L.type,name:L.displayName,displayName:L.displayName,icon:L.icon,category:L.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"})]}),_i(L.category)&&(()=>{const N=t.find(I=>I.type===L.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:"})," ",Pi(N==null?void 0:N.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Pi(N==null?void 0:N.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:L.schema.map(N=>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:[N.label||N.key,l===`${L.type}.${N.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),N.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:N.description})]}),s.jsx("div",{className:"shrink-0",children:N.type==="boolean"?s.jsx("button",{onClick:()=>v(L.type,N.key,!(L.values[N.key]??N.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:L.values[N.key]??N.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:L.values[N.key]??N.default?21:3}})}):N.type==="number"?s.jsx("input",{type:"number",value:Number(L.values[N.key]??N.default??0)||0,min:N.min,max:N.max,onChange:I=>{const W=parseInt(I.target.value)||0;N.min!==void 0&&W<N.min||N.max!==void 0&&W>N.max||v(L.type,N.key,W)},className:"machine-input w-20 text-center text-[11px]"}):N.type==="select"&&N.options?s.jsx("select",{value:String(L.values[N.key]??N.default??""),onChange:I=>v(L.type,N.key,I.target.value),className:"machine-input text-[11px]",children:N.options.map(I=>s.jsx("option",{value:I,children:I},I))}):s.jsx("input",{type:"text",value:String(L.values[N.key]??N.default??""),onBlur:I=>v(L.type,N.key,I.target.value),className:"machine-input w-[120px] text-[11px]"})})]},N.key))})]},L.type))}),f&&s.jsx(fg,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>x(null)}),C&&s.jsx(pg,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>g(!1),onCreated:()=>{g(!1),w()}})]})}const gg=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function yg({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function vg(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function wg(e){return e.trim().toLowerCase()}function jn(e,t){const r=wg(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function ko(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Es(e,t=220){const r=ko(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function jg(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 kg(e,t){return e.filter(r=>jn([r.level,r.message],t))}function Di(e){return`${e.timestamp}:${e.level}:${e.message}`}function Sg(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const c of e.entries)n.set(Di(c),c);for(const c of t.entries)n.set(Di(c),c);const a=Array.from(n.values()).sort((c,l)=>c.timestamp-l.timestamp).slice(-r),i=a.reduce((c,l)=>Math.max(c,Number(l.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:i}}return t.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:t.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function Ng(e,t,r=120){if(t.length===0)return e;const n=new Map;for(const a of e)n.set(a.id,a);for(const a of t)n.set(a.id,a);return Array.from(n.values()).sort((a,i)=>a.ts-i.ts).slice(-r)}function Cg(e,t){return e.split(`
74
- `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>jn([r],t))}function Tg(e,t){return e.filter(r=>jn([r.level,r.category,r.stage,r.interactionId,ko(r.payload)],t))}function Mg(e,t){return e.filter(r=>jn([r.kind,r.topic,r.interactionId,ko(r.payload)],t))}function Ei(e){return e==="warn"||e==="error"}function Ag({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=>Ei(a.level)).length+r.filter(a=>Ei(a.level)).length}}function Ig({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(i=>`${new Date(i.timestamp).toISOString()} ${i.level.toUpperCase()} ${i.message}`)].join(`
69
+ `}),s.jsx(rg,{historyModal:{open:Ve,targetConv:Me,ides:x,isCreatingChat:ae,isRefreshingHistory:R?!1:fe,savedSessions:ot,savedHistoryFilters:Nt,missingWorkspaceResumePath:Vt||null,onSavedHistoryFiltersChange:pt,isSavedSessionsLoading:xr,isResumingSavedSessionId:br,onClose:z,onNewChat:Re,onSwitchSession:Ke,onRefreshHistory:R?gr:We,onResumeSavedSession:yr},remoteDialog:{conversation:Le,ideEntry:Se,ides:x,connectionStates:j,actionLogs:ge,sendDaemonCommand:e,setActionLogs:X,isStandalone:pe,userName:f.userName,onOpenHistory:Ye=>{Ye&&Ee(Ye),xe()},onConversationChange:Ee,onClose:qe},cliStopDialog:{open:et,targetConv:ct,onCancel:dt,onStopNow:async()=>{await yt("hard")},onSaveAndStop:async()=>{await yt("save")}},connectionBanner:{wsStatus:k,showReconnected:A,loginUrl:f.connectionLoginUrl,onReconnect:f.retryServerConnection},toastOverlay:{toasts:h,onDismiss:Ye=>p(Rt=>Rt.filter(Ws=>Ws.id!==Ye)),onClick:Ye=>{if(Ye.targetKey){const Rt=Ce(Ye.targetKey);Rt&&(ie(Rt.tabKey,xt),Ao(Rt),E(Rt.tabKey,"toast-open"))}}},onboarding:{open:g,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}}})]})}function lg({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,d]=o.useState(null),[m,u]=o.useState(null),[f,x]=o.useState(!1),[C,y]=o.useState(null),[p,g]=o.useState(!1),[b,h]=o.useState(""),k=o.useRef(null),S=o.useCallback(P=>{k.current=P},[]),j=o.useCallback((P,$,H=!1)=>{c(J=>[...J.slice(-100),{timestamp:Date.now(),level:P,message:$}]),setTimeout(()=>{var J;return(J=a.current)==null?void 0:J.scrollIntoView({behavior:"smooth"})},100),H&&at.showToast($,P==="error"||P==="warn"?"warning":"success")},[a]),A=o.useCallback(P=>{const $=P instanceof Error?P.message:String(P||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),M=o.useCallback(async(P,$)=>{var H;if(!e||l)return!1;d(P),j("info",`Launching ${it(P)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const J={ideType:P,enableCdp:!0};(H=$==null?void 0:$.workspace)!=null&&H.trim()?J.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(J.useDefaultWorkspace=!0);const he=await r(e,"launch_ide",J);return j(he!=null&&he.success?"info":"error",he!=null&&he.success?`${it(P)} launched`:`Failed: ${he==null?void 0:he.error}`,!0),!!(he!=null&&he.success)}catch(J){return j("error",`Launch error: ${J.message}`,!0),!1}finally{d(null)}},[e,l,j,r]),w=o.useCallback(async P=>{if(!e)return{success:!1};const{cliType:$,dir:H,workspaceId:J,useDefaultWorkspace:he,useHome:ie,argsStr:te,model:be,resumeSessionId:we}=P;if(!$)return j("warn","Select a CLI or ACP provider first",!0),{success:!1};const ge=te?te.split(/\s+/).filter(Boolean):void 0,X=(H==null?void 0:H.trim())||(J?"(saved id)":he?"(default workspace)":ie?"(home)":"");j("info",`Launching ${$}${X?` in ${X}`:""}${be?` (model: ${be})`:""}...`),u($);try{const ce={cliType:$,cliArgs:ge,initialModel:be||void 0};H!=null&&H.trim()?ce.dir=H.trim():J?ce.workspaceId=J:he?ce.useDefaultWorkspace=!0:ie&&(ce.useHome=!0),we&&(ce.resumeSessionId=we);const ye=await r(e,"launch_cli",ce),ne=(ye==null?void 0:ye.result)||ye;return ye!=null&&ye.success?(j("info",`${$} launched`,!0),(ne==null?void 0:ne.launchSource)==="home"?j("info","📂 Running in home directory (explicit choice)"):(ne==null?void 0:ne.launchSource)==="defaultWorkspace"&&j("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ne==null?void 0:ne.sessionId}):(j("error",`Failed: ${(ye==null?void 0:ye.error)||(ne==null?void 0:ne.error)}`,!0),(ye==null?void 0:ye.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&y({cliType:$,argsStr:te,model:be}),{success:!1,sessionId:ne==null?void 0:ne.sessionId})}catch(ce){return A(ce)?(j("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(j("error",`Launch error: ${ce.message}`,!0),{success:!1})}finally{u(null)}},[e,j,A,r]),v=o.useCallback(async(P,$,H,J)=>e?P?$.trim()?w({cliType:P,dir:$,argsStr:H,model:J}):(y({cliType:P,argsStr:H,model:J}),{success:!1}):(j("warn","Select a provider",!0),{success:!1}):{success:!1},[e,j,w]),B=o.useCallback(async(P,$,H)=>{if(e&&window.confirm(`Stop ${P}?
70
+ This will terminate the process.`))try{const J=await r(e,"stop_cli",{cliType:P,dir:$,targetSessionId:H});J!=null&&J.success?j("info",`${P} stopped`,!0):j("error",`Stop failed: ${(J==null?void 0:J.error)||"Unknown error"}`,!0)}catch(J){j("error",`Stop failed: ${J.message}`,!0)}},[e,j,r]),_=o.useCallback(async P=>{try{await r(P.daemonId,"restart_ide",{ideType:P.type}),j("info",`${it(P.type)} restart initiated`,!0)}catch($){j("error",`Restart failed: ${$.message}`,!0)}},[j,r]),T=o.useCallback(async P=>{if(window.confirm(`Stop ${it(P.type)}?
71
+ This will disconnect CDP and optionally kill the process.`))try{const $=await r(P.daemonId,"stop_ide",{ideType:P.type,killProcess:!0});$!=null&&$.success?j("info",`${it(P.type)} stopped`,!0):j("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){j("error",`Stop failed: ${$.message}`,!0)}},[j,r]),D=o.useCallback(async()=>{if(e)try{const P=await r(e,"detect_ides",{});j("info",`Found ${((P==null?void 0:P.result)||[]).length} IDE(s)`,!0)}catch(P){j("error",`Detection failed: ${P.message}`,!0)}},[e,j,r]),K=o.useCallback(async P=>{if(!e||!P.trim())return!1;x(!0);try{const $=await r(e,"workspace_add",{path:P.trim()});return $!=null&&$.success?(j("info",`Workspace added: ${P.trim()}`),!0):(j("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return j("error",$.message),!1}finally{x(!1)}},[e,j,r]),L=o.useCallback(async P=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){x(!0);try{const $=await r(e,"workspace_remove",{id:P});$!=null&&$.success?j("info","Workspace removed",!0):j("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){j("error",$.message,!0)}finally{x(!1)}}},[e,j,r]),N=o.useCallback(async P=>{var $;if(e){x(!0);try{const H=await r(e,"workspace_set_default",P===null?{clear:!0}:{id:P});if(H!=null&&H.success){j("info",P?"Default workspace updated":"Default workspace cleared",!0);const J=typeof H.defaultWorkspacePath=="string"?H.defaultWorkspacePath:"";J&&(($=k.current)==null||$.call(k,J))}else j("error",(H==null?void 0:H.error)||"workspace_set_default failed",!0)}catch(H){j("error",H.message,!0)}finally{x(!1)}}},[e,j,r]),I=o.useCallback(async P=>{var H;if(!e||!P.trim())return;const $=P.trim();x(!0);try{const J=await r(e,"workspace_set_default",{path:$});J!=null&&J.success?(j("info","Default workspace set from history"),(H=k.current)==null||H.call(k,$)):j("error",(J==null?void 0:J.error)||"Could not set default (path missing on disk?)")}catch(J){j("error",J.message)}finally{x(!1)}},[e,j,r]),F=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:b}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:b})}catch(P){j("warn",`Live nickname updated, but account sync failed: ${P.message}`)}j("info",`Nickname set to "${b||"(cleared)"}"`),g(!1)}catch(P){j("error",`Failed: ${P.message}`)}},[e,b,t,j,n,r]);return{logs:i,launchingIde:l,launchingAgentType:m,workspaceBusy:f,launchPick:C,setLaunchPick:y,editingNickname:p,setEditingNickname:g,nicknameInput:b,setNicknameInput:h,addLog:j,handleLaunchIde:M,runLaunchCliCore:w,handleLaunchCli:v,handleStopCli:B,handleRestartIde:_,handleStopIde:T,handleDetectIdes:D,handleWorkspaceAdd:K,handleWorkspaceRemove:L,handleWorkspaceSetDefault:N,handleWorkspaceResumePath:I,handleSaveNickname:F,setOnDefaultWorkspaceChanged:S}}function dg({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var _;const{workspaceBusy:l,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=i,[f,x]=o.useState(!1),[C,y]=o.useState(""),[p,g]=o.useState([]),[b,h]=o.useState(!1),[k,S]=o.useState(""),j=o.useCallback(async T=>{h(!0),S("");try{const D=await vn(c,e,T);y(D.path),g(D.directories)}catch(D){S(D instanceof Error?D.message:"Could not load folder")}finally{h(!1)}},[e,c]),A=o.useCallback(()=>{x(!0);const T=[...r.map(K=>K.workspace),...n.map(K=>K.workspace),...a.map(K=>K.workspace)],D=yn(t.platform,gn(T,t.defaultWorkspacePath,(t.workspaces||[]).map(K=>K.path)));j(D)},[a,n,r,j,t.defaultWorkspacePath,t.platform,t.workspaces]),M=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,w=t.availableMem??t.freeMem??t.totalMem,v=M&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-w)/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(Sr,{icon:s.jsx(oc,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?nm(t.uptime):"Waiting…"}),s.jsx(Sr,{icon:s.jsx(Mt,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(Sr,{icon:s.jsx(Fa,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(Sr,{icon:s.jsx(fu,{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(Fo,{value:M?Math.min(Math.round(B/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:M?`${B.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Fo,{value:v,max:100,label:"Memory",color:"#3b82f6",detail:M?`${An(t.totalMem-w)} / ${An(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${An(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(ms,{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:A,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:hn(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(wn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:C,directories:p,busy:b,error:k,confirmLabel:"Add workspace",onClose:()=>x(!1),onNavigate:T=>{j(T)},onConfirm:T=>{(async()=>{if(!T)return;await d(T)&&x(!1)})()}})]})}function ug(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 mg(e,t,r){const n=[];for(const[a,i]of Object.entries(e.settings)){const c=r!=null&&r.filterSchema?r.filterSchema(i):i;if(c.length===0)continue;const l=t.find(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 sa(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 _i(e){if(!e||typeof e!="object")return null;if(sa(e))return e;const t=e,r=t.result;return sa(r)?r:sa(t.sourceConfig)?t.sourceConfig:null}function fg(e){const t=e.trim();return t||null}const Pi=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],pg=[{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 hg({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[d,m]=o.useState([]),[u,f]=o.useState(""),[x,C]=o.useState([]),[y,p]=o.useState(""),g=o.useRef(null),b=o.useRef(null),h=w=>{m(v=>v.includes(w)?v.filter(B=>B!==w):[...v,w])},k=()=>m([...Pi]),S=()=>m([]);o.useEffect(()=>{var w;(w=g.current)==null||w.scrollIntoView({behavior:"smooth"})},[x]),o.useEffect(()=>()=>{b.current&&clearInterval(b.current)},[]);const j=o.useCallback(()=>{b.current&&clearInterval(b.current),b.current=setInterval(async()=>{try{const w=await r(e,"provider_auto_fix_status",{providerType:t.type});(w==null?void 0:w.running)===!1&&a==="running"&&(i("done"),C(v=>[...v,`
72
+ ✅ Auto-fix completed!`]),b.current&&clearInterval(b.current))}catch{}},3e3)},[e,t.type,r,a]),A=async()=>{if(d.length!==0){i("running"),C(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${d.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),p("");try{const w=await r(e,"provider_auto_fix",{providerType:t.type,functions:d,agent:c,...u?{comment:u}:{}});w!=null&&w.success&&(w!=null&&w.started||w!=null&&w.running)?(C(v=>[...v,"✅ Agent started. Monitoring progress..."]),j()):(i("error"),p((w==null?void 0:w.error)||"Failed to start auto-fix"))}catch(w){i("error"),p((w==null?void 0:w.message)||"Connection failed")}}},M=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),C(w=>[...w,`
73
+ ⚠️ Auto-fix cancelled.`]),i("done"),b.current&&clearInterval(b.current)}catch{}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:w=>w.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:t.icon||"🔧"}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",t.displayName]}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),s.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),s.jsx("div",{className:"flex gap-2",children:pg.map(w=>s.jsxs("button",{onClick:()=>l(w.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===w.value?w.color+"66":"var(--border-subtle)",background:c===w.value?w.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===w.value?w.color:"var(--text-primary)"},children:w.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:w.desc})]},w.value))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:k,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:Pi.map(w=>s.jsxs("button",{onClick:()=>h(w),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(w)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(w)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(w)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(w)?"☑ ":"☐ ",w]},w))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",s.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:u,onChange:w=>f(w.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[x.map((w,v)=>s.jsx("div",{className:w.startsWith("✅")?"text-green-400":"",style:w.startsWith("❌")||w.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:w},v)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:g})]}),y&&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:y})]})]}),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:A,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:M,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{i("config"),C([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function xg({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var j;const i=t.filter(A=>A.category==="ide"),[c,l]=o.useState(((j=i[0])==null?void 0:j.type)||""),[d,m]=o.useState(""),[u,f]=o.useState(""),[x,C]=o.useState(!1),[y,p]=o.useState(""),[g,b]=o.useState(!1),h=A=>{const M=A.toLowerCase().replace(/[^a-z0-9-]/g,"");m(M),(!u||u===k(d))&&f(k(M))},k=A=>A.split("-").map(M=>M.charAt(0).toUpperCase()+M.slice(1)).join(" "),S=async()=>{if(!(!d||!u||!c)){C(!0),p("");try{const A=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:c});A!=null&&A.success||A!=null&&A.created?(b(!0),a==null||a(d)):p((A==null?void 0:A.error)||"Failed to create provider")}catch(A){p((A==null?void 0:A.message)||"Connection failed")}C(!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:A=>A.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:i.map(A=>s.jsxs("button",{onClick:()=>l(A.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===A.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===A.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:A.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===A.type?"#a78bfa":"var(--text-secondary)"},children:A.displayName})]},A.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:A=>h(A.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:A=>f(A.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"})]}),y&&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:y})]})}),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||x,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||x?.4:1},children:x?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Di(e){return e==="cli"||e==="acp"}function bg(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 gg(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 Ei(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 yg({machineId:e,providers:t,sendDaemonCommand:r}){var K;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,d]=o.useState(null),[m,u]=o.useState("all"),[f,x]=o.useState(null),[C,y]=o.useState(!1),[p,g]=o.useState(null),[b,h]=o.useState("normal"),[k,S]=o.useState(""),[j,A]=o.useState(!1),M=o.useCallback(async()=>{if(e)try{const L=await r(e,"get_provider_source_config",{}),N=_i(L);N&&(g(N),h(N.sourceMode),S(N.explicitProviderDir||""))}catch{}},[e,r]),w=o.useCallback(async()=>{if(e){c(!0);try{const L=await r(e,"get_provider_settings",{}),N=ug(L);if(N){const I=mg(N,t,{filterSchema:F=>F.filter(P=>P.key!=="enabled")});I.sort((F,P)=>F.category.localeCompare(P.category)||F.displayName.localeCompare(P.displayName)),a(I)}}catch{}c(!1)}},[e,t,r]);o.useEffect(()=>{n.length===0&&w(),p||M()},[]);const v=async(L,N,I)=>{d(`${L}.${N}`),a(F=>F.map(P=>P.type===L?{...P,values:{...P.values,[N]:I}}:P));try{const F=await r(e,"set_provider_setting",{providerType:L,key:N,value:I});F!=null&&F.success||w()}catch{w()}d(null)},B=async(L,N)=>{await v(L,"enabled",N),await w()},_=async L=>{d(`${L}.detect`);try{await r(e,"detect_provider",{providerType:L})}finally{await w(),d(null)}},T=async L=>{await v(L,"executablePath",""),await v(L,"executableArgs",""),await w()},D=async()=>{A(!0);try{const L=await r(e,"set_provider_source_config",{providerSourceMode:b,providerDir:fg(k)}),N=_i(L);N?(g(N),h(N.sourceMode),S(N.explicitProviderDir||"")):await M(),await w()}catch{await M()}A(!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(L=>s.jsx("button",{onClick:()=>u(L),className:`machine-btn text-[10px] px-2 py-0.5 ${m===L?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:L.toUpperCase()},L))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>y(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),s.jsx("button",{onClick:w,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Running CLI sessions refresh provider scripts/config; process binary changes still apply on next launch."})]}),s.jsx("button",{onClick:M,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:b,onChange:L=>h(L.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:k,onChange:L=>S(L.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void D(),disabled:j,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:j?"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:"})," ",((K=p==null?void 0:p.providerRoots)==null?void 0:K.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(L=>L.category===m).length>1&&(()=>{const L=n.filter(P=>P.category===m),N=new Map;for(const P of L)for(const $ of P.schema){if($.type!=="boolean")continue;const H=N.get($.key),J=!!(P.values[$.key]??$.default);H?(H.onCount+=J?1:0,H.total+=1):N.set($.key,{label:$.label||$.key,onCount:J?1:0,total:1})}const I=[...N.entries()].filter(([,P])=>P.total===L.length);if(I.length===0)return null;const F=async(P,$)=>{for(const H of L)await v(H.type,P,$)};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 (",L.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:I.map(([P,$])=>{const H=$.onCount===$.total,J=$.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:$.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",$.onCount,"/",$.total,")"]}),s.jsx("button",{onClick:()=>void F(P,!0),disabled:H,className:`machine-btn text-[9px] px-1.5 py-px ${H?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void F(P,!1),disabled:J,className:`machine-btn text-[9px] px-1.5 py-px ${J?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},P)})})]})})(),i&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):s.jsx("div",{className:"flex flex-col gap-2",children:n.filter(L=>m==="all"||L.category===m).map(L=>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:L.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:L.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:L.category==="acp"?"rgba(139,92,246,0.08)":L.category==="cli"?"rgba(59,130,246,0.08)":L.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:L.category==="acp"?"#a78bfa":L.category==="cli"?"#60a5fa":L.category==="ide"?"#86efac":"var(--status-warning)"},children:L.category}),Di(L.category)&&(()=>{const N=t.find(P=>P.type===L.type),I=(N==null?void 0:N.enabled)===!0||L.values.enabled===!0,F=(N==null?void 0:N.machineStatus)||(I?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${gg(F)}`,children:bg(F)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void B(L.type,!I),disabled:l===`${L.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${I?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:I?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void _(L.type),disabled:!I||l===`${L.type}.detect`,title:I?"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 ${I?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void T(L.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),L.category==="ide"&&s.jsx("button",{onClick:()=>x(t.find(N=>N.type===L.type)||{type:L.type,name:L.displayName,displayName:L.displayName,icon:L.icon,category:L.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"})]}),Di(L.category)&&(()=>{const N=t.find(I=>I.type===L.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:"})," ",Ei(N==null?void 0:N.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Ei(N==null?void 0:N.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:L.schema.map(N=>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:[N.label||N.key,l===`${L.type}.${N.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),N.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:N.description})]}),s.jsx("div",{className:"shrink-0",children:N.type==="boolean"?s.jsx("button",{onClick:()=>v(L.type,N.key,!(L.values[N.key]??N.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:L.values[N.key]??N.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:L.values[N.key]??N.default?21:3}})}):N.type==="number"?s.jsx("input",{type:"number",value:Number(L.values[N.key]??N.default??0)||0,min:N.min,max:N.max,onChange:I=>{const F=parseInt(I.target.value)||0;N.min!==void 0&&F<N.min||N.max!==void 0&&F>N.max||v(L.type,N.key,F)},className:"machine-input w-20 text-center text-[11px]"}):N.type==="select"&&N.options?s.jsx("select",{value:String(L.values[N.key]??N.default??""),onChange:I=>v(L.type,N.key,I.target.value),className:"machine-input text-[11px]",children:N.options.map(I=>s.jsx("option",{value:I,children:I},I))}):s.jsx("input",{type:"text",value:String(L.values[N.key]??N.default??""),onBlur:I=>v(L.type,N.key,I.target.value),className:"machine-input w-[120px] text-[11px]"})})]},N.key))})]},L.type))}),f&&s.jsx(hg,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>x(null)}),C&&s.jsx(xg,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>y(!1),onCreated:()=>{y(!1),w()}})]})}const vg=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function wg({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function jg(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function kg(e){return e.trim().toLowerCase()}function kn(e,t){const r=kg(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function So(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Es(e,t=220){const r=So(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function Sg(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 Ng(e,t){return e.filter(r=>kn([r.level,r.message],t))}function $i(e){return`${e.timestamp}:${e.level}:${e.message}`}function Cg(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const c of e.entries)n.set($i(c),c);for(const c of t.entries)n.set($i(c),c);const a=Array.from(n.values()).sort((c,l)=>c.timestamp-l.timestamp).slice(-r),i=a.reduce((c,l)=>Math.max(c,Number(l.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:i}}return t.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:t.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function Tg(e,t,r=120){if(t.length===0)return e;const n=new Map;for(const a of e)n.set(a.id,a);for(const a of t)n.set(a.id,a);return Array.from(n.values()).sort((a,i)=>a.ts-i.ts).slice(-r)}function Mg(e,t){return e.split(`
74
+ `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>kn([r],t))}function Ag(e,t){return e.filter(r=>kn([r.level,r.category,r.stage,r.interactionId,So(r.payload)],t))}function Ig(e,t){return e.filter(r=>kn([r.kind,r.topic,r.interactionId,So(r.payload)],t))}function Bi(e){return e==="warn"||e==="error"}function Rg({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=>Bi(a.level)).length+r.filter(a=>Bi(a.level)).length}}function Lg({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(i=>`${new Date(i.timestamp).toISOString()} ${i.level.toUpperCase()} ${i.message}`)].join(`
75
75
  `)):t.length>0&&a.push(["[daemon logs]",...t].join(`
76
76
  `)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${Es(i.payload,500)}`.trim())].join(`
77
77
  `)),n.length>0&&a.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${Es(i.payload,500)}`.trim())].join(`
78
78
  `)),a.join(`
79
79
 
80
- `)}function Rg({machineId:e,sendDaemonCommand:t}){const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[d,m]=o.useState([]),[u,f]=o.useState([]),[x,C]=o.useState(null),[g,p]=o.useState(!0),[j,b]=o.useState("info"),[h,y]=o.useState("all"),[S,k]=o.useState(!0),[A,M]=o.useState(!0),[w,v]=o.useState(""),[B,_]=o.useState(""),[T,D]=o.useState(0),K=o.useRef(0),L=o.useRef(0),N=o.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),I=o.useRef([]),W=o.useCallback(()=>{const te={entries:[],kind:"empty",rawText:"",lastTs:0};N.current=te,K.current=0,n([]),l(""),i("empty"),k(!0)},[]),P=o.useCallback(()=>{I.current=[],L.current=0,m([]),M(!0)},[]),$=o.useCallback(te=>{te!==j&&(W(),b(te))},[j,W]),H=o.useCallback(te=>{y(be=>be===te?be:te)},[]),J=o.useCallback(()=>{W(),P(),f([]),C(null),v(""),_(""),Ms.clear()},[W,P]),he=o.useCallback(()=>{D(te=>te+1)},[]),ie=o.useCallback(async()=>{if(!e)return;const te=K.current,be=L.current,[we,ge]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:j,since:te}),t(e,"get_debug_trace",yg({count:120,since:be,category:h}))]);if(we.status==="fulfilled"){const X=we.value,ce=(X==null?void 0:X.result)||X,ye=jg(ce),ne=Sg(N.current,ye,300);N.current=ne,K.current=ne.lastTs,k(!1),v((X==null?void 0:X.success)===!1?String((X==null?void 0:X.error)||"Could not load daemon logs"):""),i(ne.kind),l(ne.rawText),n(ne.entries)}else k(!1),v(we.reason instanceof Error?we.reason.message:"Could not load daemon logs");if(ge.status==="fulfilled"){const X=ge.value,ce=(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(ce==null?void 0:ce.trace)){const ye=ce.trace,ne=Ng(I.current,ye,120),de=ye.reduce((je,me)=>Math.max(je,Number(me.ts||0)),be);I.current=ne,de>be&&(L.current=de),_(""),m(ne)}else _("");M(!1)}else M(!1),_(ge.reason instanceof Error?ge.reason.message:"Could not load daemon trace");f(Ms.list({limit:120})),C(Date.now())},[j,e,t,h]);return o.useEffect(()=>{P()},[P,h]),o.useEffect(()=>{if(!e||(ie(),!g))return;const te=setInterval(()=>{ie()},3e3);return()=>clearInterval(te)},[g,ie,e,T]),{daemonLogs:r,daemonLogKind:a,daemonRawText:c,debugTrace:d,webEvents:u,lastUpdatedAt:x,autoRefresh:g,logLevel:j,traceCategory:h,daemonLoading:S,traceLoading:A,daemonFetchError:w,traceFetchError:B,setAutoRefresh:p,setLogLevel:$,setTraceCategory:H,refresh:he,clear:J}}function Lg({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:i,daemonRawLineCount:c,traceCount:l,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":i>0||c>0?"ok":"empty",detail:r||(a==="text"?`${c} raw file-fallback line(s)`:`${i} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":t?"loading":l>0?"ok":"empty",detail:n||`${l} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function $i(e){return e==="warn"||e==="error"}function _g(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 Pg(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 Bi(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function Dg(e){const t=Es(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function Eg(e){const t=Es(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function $g({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.forEach((i,c)=>{a.push({id:`daemon-log-${i.timestamp}-${c}`,source:"daemon_log",ts:Number(i.timestamp||0),severity:i.level,message:i.message,raw:i.message})}),n.forEach(i=>{a.push({id:`browser-event-${i.id}`,source:"browser_event",ts:Number(i.ts||0),severity:"info",message:Eg(i),topic:i.topic,interactionId:i.interactionId,payload:i.payload})}),r.forEach(i=>{a.push({id:`daemon-trace-${i.id}`,source:"daemon_trace",ts:Number(i.ts||0),severity:i.level,message:Dg(i),category:i.category,stage:i.stage,interactionId:i.interactionId,payload:i.payload})}),t.forEach((i,c)=>{a.push({id:`raw-file-${c}`,source:"raw_file",ts:Pg(i,c),severity:_g(i),message:i,raw:i})}),a.sort((i,c)=>i.ts!==c.ts?i.ts-c.ts:Bi(i.source)-Bi(c.source))}function Bg(e){return`${e.source}:${e.severity}:${e.message}`}function Kg(e){const t=e.filter(n=>$i(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!$i(n.severity))continue;const a=Bg(n),i=r.get(a);i?(i.count+=1,i.firstTs=Math.min(i.firstTs,n.ts),i.lastTs=Math.max(i.lastTs,n.ts)):r.set(a,{key:a,source:n.source,severity:n.severity,message:n.message,count:1,firstTs:n.ts,lastTs:n.ts})}return{totalCount:e.length,issueCount:t.length,latestIssue:t[0]||null,repeatedPatterns:Array.from(r.values()).filter(n=>n.count>1).sort((n,a)=>a.count!==n.count?a.count-n.count:a.lastTs-n.lastTs).slice(0,5)}}function Wg(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Ki(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${Wg(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function Og({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
80
+ `)}function _g({machineId:e,sendDaemonCommand:t}){const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[d,m]=o.useState([]),[u,f]=o.useState([]),[x,C]=o.useState(null),[y,p]=o.useState(!0),[g,b]=o.useState("info"),[h,k]=o.useState("all"),[S,j]=o.useState(!0),[A,M]=o.useState(!0),[w,v]=o.useState(""),[B,_]=o.useState(""),[T,D]=o.useState(0),K=o.useRef(0),L=o.useRef(0),N=o.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),I=o.useRef([]),F=o.useCallback(()=>{const te={entries:[],kind:"empty",rawText:"",lastTs:0};N.current=te,K.current=0,n([]),l(""),i("empty"),j(!0)},[]),P=o.useCallback(()=>{I.current=[],L.current=0,m([]),M(!0)},[]),$=o.useCallback(te=>{te!==g&&(F(),b(te))},[g,F]),H=o.useCallback(te=>{k(be=>be===te?be:te)},[]),J=o.useCallback(()=>{F(),P(),f([]),C(null),v(""),_(""),Ms.clear()},[F,P]),he=o.useCallback(()=>{D(te=>te+1)},[]),ie=o.useCallback(async()=>{if(!e)return;const te=K.current,be=L.current,[we,ge]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:g,since:te}),t(e,"get_debug_trace",wg({count:120,since:be,category:h}))]);if(we.status==="fulfilled"){const X=we.value,ce=(X==null?void 0:X.result)||X,ye=Sg(ce),ne=Cg(N.current,ye,300);N.current=ne,K.current=ne.lastTs,j(!1),v((X==null?void 0:X.success)===!1?String((X==null?void 0:X.error)||"Could not load daemon logs"):""),i(ne.kind),l(ne.rawText),n(ne.entries)}else j(!1),v(we.reason instanceof Error?we.reason.message:"Could not load daemon logs");if(ge.status==="fulfilled"){const X=ge.value,ce=(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(ce==null?void 0:ce.trace)){const ye=ce.trace,ne=Tg(I.current,ye,120),de=ye.reduce((je,me)=>Math.max(je,Number(me.ts||0)),be);I.current=ne,de>be&&(L.current=de),_(""),m(ne)}else _("");M(!1)}else M(!1),_(ge.reason instanceof Error?ge.reason.message:"Could not load daemon trace");f(Ms.list({limit:120})),C(Date.now())},[g,e,t,h]);return o.useEffect(()=>{P()},[P,h]),o.useEffect(()=>{if(!e||(ie(),!y))return;const te=setInterval(()=>{ie()},3e3);return()=>clearInterval(te)},[y,ie,e,T]),{daemonLogs:r,daemonLogKind:a,daemonRawText:c,debugTrace:d,webEvents:u,lastUpdatedAt:x,autoRefresh:y,logLevel:g,traceCategory:h,daemonLoading:S,traceLoading:A,daemonFetchError:w,traceFetchError:B,setAutoRefresh:p,setLogLevel:$,setTraceCategory:H,refresh:he,clear:J}}function Pg({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:i,daemonRawLineCount:c,traceCount:l,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":i>0||c>0?"ok":"empty",detail:r||(a==="text"?`${c} raw file-fallback line(s)`:`${i} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":t?"loading":l>0?"ok":"empty",detail:n||`${l} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function Ki(e){return e==="warn"||e==="error"}function Dg(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 Eg(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 Wi(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function $g(e){const t=Es(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function Bg(e){const t=Es(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function Kg({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.forEach((i,c)=>{a.push({id:`daemon-log-${i.timestamp}-${c}`,source:"daemon_log",ts:Number(i.timestamp||0),severity:i.level,message:i.message,raw:i.message})}),n.forEach(i=>{a.push({id:`browser-event-${i.id}`,source:"browser_event",ts:Number(i.ts||0),severity:"info",message:Bg(i),topic:i.topic,interactionId:i.interactionId,payload:i.payload})}),r.forEach(i=>{a.push({id:`daemon-trace-${i.id}`,source:"daemon_trace",ts:Number(i.ts||0),severity:i.level,message:$g(i),category:i.category,stage:i.stage,interactionId:i.interactionId,payload:i.payload})}),t.forEach((i,c)=>{a.push({id:`raw-file-${c}`,source:"raw_file",ts:Eg(i,c),severity:Dg(i),message:i,raw:i})}),a.sort((i,c)=>i.ts!==c.ts?i.ts-c.ts:Wi(i.source)-Wi(c.source))}function Wg(e){return`${e.source}:${e.severity}:${e.message}`}function Og(e){const t=e.filter(n=>Ki(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!Ki(n.severity))continue;const a=Wg(n),i=r.get(a);i?(i.count+=1,i.firstTs=Math.min(i.firstTs,n.ts),i.lastTs=Math.max(i.lastTs,n.ts)):r.set(a,{key:a,source:n.source,severity:n.severity,message:n.message,count:1,firstTs:n.ts,lastTs:n.ts})}return{totalCount:e.length,issueCount:t.length,latestIssue:t[0]||null,repeatedPatterns:Array.from(r.values()).filter(n=>n.count>1).sort((n,a)=>a.count!==n.count?a.count-n.count:a.lastTs-n.lastTs).slice(0,5)}}function Fg(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Oi(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${Fg(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function Hg({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
81
81
  `)),a.push(["[source status]",...r.map(c=>`${c.label}: ${c.status} - ${c.detail}`)].join(`
82
- `)),t.latestIssue&&a.push(["[latest issue]",Ki(t.latestIssue)].join(`
82
+ `)),t.latestIssue&&a.push(["[latest issue]",Oi(t.latestIssue)].join(`
83
83
  `)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(c=>`${c.count}x ${c.severity.toUpperCase()} ${c.source} ${c.message}`)].join(`
84
- `));const i=e.slice(-n);return a.push(["[timeline]",...i.length>0?i.map(Ki):["No diagnostic events captured."]].join(`
84
+ `));const i=e.slice(-n);return a.push(["[timeline]",...i.length>0?i.map(Oi):["No diagnostic events captured."]].join(`
85
85
  `)),a.join(`
86
86
 
87
- `)}function Fg(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Hg(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Ug({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:i,quickFilter:c,searchQuery:l,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f}){const x=vg(n,i),C=kg(e,l),g=Cg(t,l),p=Tg(x,l),j=Mg(a,l),b=Fg(C,c),h=c==="all"?g:[],y=Hg(p,c),S=c==="issues"?[]:j,k=Ag({daemonLogs:C,daemonRawLines:g,trace:p,webEvents:j}),A=$g({daemonLogs:b,daemonRawLines:h,trace:y,webEvents:S}),M=Kg(A),w=Lg({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f,daemonLogKind:r,daemonLogsCount:C.length,daemonRawLineCount:g.length,traceCount:p.length,webEventCount:j.length});return{filteredDaemonLogs:C,filteredDaemonRawLines:g,filteredTraceEntries:p,filteredWebEvents:j,visibleDaemonLogs:b,visibleDaemonRawLines:h,visibleTraceEntries:y,visibleWebEvents:S,quickFilterCounts:k,diagnosticEvents:A,diagnosticsSummary:M,sourceStates:w}}function zg(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Jl(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function La(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 sa(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 So(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function Vg({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${La(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Jl(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:So(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 Gg({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:i,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=>i(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 qg({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:gg.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 Yg({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:i,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":i?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${sa(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 ${sa(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:[So(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:Jl(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 ${sa(m)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:c||l?"Needs attention":i?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",zg(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(x=>s.jsxs("div",{children:[x.label,": ",x.status]},x.id))})]})]})}function Xg({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()," · ",So(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function Jg({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:i,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(Vg,{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"?`${i.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&i.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&i.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children: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"&&i.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 ${La(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 ${La(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:Es(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:Es(u.payload,360)||"No payload"})]},u.id))]})]})]})}function Qg({machineId:e,sendDaemonCommand:t}){const r=Rg({machineId:e,sendDaemonCommand:t}),[n,a]=o.useState("info"),[i,c]=o.useState(""),[l,d]=o.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=o.useRef(null),u=o.useRef(!1),f=o.useMemo(()=>Ug({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:i,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,i,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);o.useEffect(()=>{if(r.autoRefresh&&f.diagnosticEvents.length>0){const g=u.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:g}),u.current=!0},50)}},[f.diagnosticEvents.length,r.autoRefresh]);const x=o.useCallback(async()=>{var p;const g=Ig({daemonLogs:f.visibleDaemonLogs,daemonRawLines:f.visibleDaemonRawLines,trace:f.visibleTraceEntries,webEvents:f.visibleWebEvents});if(!g.trim()){at.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(g)),at.showToast("Copied visible logs to clipboard.","success")}catch(j){at.showToast(j instanceof Error?j.message:"Could not copy visible logs","warning")}},[f.visibleDaemonLogs,f.visibleDaemonRawLines,f.visibleTraceEntries,f.visibleWebEvents]),C=o.useCallback(async()=>{var p;const g=Og({events:f.diagnosticEvents,summary:f.diagnosticsSummary,sources:f.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(g)),at.showToast("Copied diagnostic bundle to clipboard.","success")}catch(j){at.showToast(j instanceof Error?j.message:"Could not copy diagnostic bundle","warning")}},[f.diagnosticEvents,f.diagnosticsSummary,f.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(Gg,{quickFilter:n,quickFilterCounts:f.quickFilterCounts,searchQuery:i,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{C()},onCopyVisible:()=>{x()},onToggleAutoRefresh:()=>r.setAutoRefresh(g=>!g),onRefresh:r.refresh,onClear:r.clear}),s.jsx(qg,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(Yg,{diagnosticsSummary:f.diagnosticsSummary,diagnosticEventsCount:f.diagnosticEvents.length,sourceStates:f.sourceStates,searchQuery:i,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(Xg,{patterns:f.diagnosticsSummary.repeatedPatterns}),s.jsx(Jg,{streams:r,sectionsOpen:l,setSectionsOpen:d,diagnosticEvents:f.diagnosticEvents,visibleDaemonLogs:f.visibleDaemonLogs,visibleDaemonRawLines:f.visibleDaemonRawLines,visibleTraceEntries:f.visibleTraceEntries,visibleWebEvents:f.visibleWebEvents,quickFilter:n,searchQuery:i}),s.jsx("div",{ref:m})]})}function Zg(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 Ql(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 ey(e){var a;const t=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=Ql((i==null?void 0:i.meta)||void 0),d=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?t.push(i):(c==="stopped"||c==="failed")&&(d||l)?r.push(i):n.push(i)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function ty(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function ra(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 na(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function aa(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Wi(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 sy(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function ry(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 ny(e){var r;const t=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const i=`${n.providerType}::${n.workspace}::${a}`;t.set(i,(t.get(i)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function ay({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,d]=o.useState(!1),m=xh(e,{enabled:!!e,includeSessions:!0,limit:Xo,intervalMs:bf}),u=m.diagnostics,f=m.loading,x=m.applyDiagnostics,C=o.useMemo(()=>Zg({diagnostics:u,loading:f,refreshing:l,error:n}),[u,f,l,n]),g=o.useMemo(()=>new Map(t.map(_=>[_.sessionId||_.id,_])),[t]),p=o.useCallback(async()=>{if(e){d(!0);try{const _=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Xo}),T=na(_);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");x(T.diagnostics||T.result||null),a("")}catch(_){const T=_ instanceof Error?_.message:"Could not load hosted runtime diagnostics";a(T)}finally{d(!1)}}},[x,e,r]);o.useEffect(()=>{!e||u||f||l||p()},[u,f,e,p,l]);const j=o.useCallback(async(_,T)=>{const D=`${_}:${T.sessionId}`;if(!(_==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
88
- This will terminate the hosted runtime.`))){c(D);try{const K=await r(e,_,{sessionId:T.sessionId}),L=na(K);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Session host action failed");const N=_==="session_host_resume_session"?"resumed":_==="session_host_restart_session"?"restarted":"stopped";at.showToast(`Session host ${N}: ${T.displayName}`,"success"),await p()}catch(K){const L=K instanceof Error?K.message:"Session host action failed";at.showToast(L,"warning"),a(L)}finally{c(K=>K===D?null:K)}}},[e,p,r]),b=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
89
- 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",{}),D=na(T);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Duplicate prune failed");const K=D.result||{},L=Array.isArray(K.prunedSessionIds)?K.prunedSessionIds.length:0,N=typeof K.duplicateGroupCount=="number"?K.duplicateGroupCount:0;at.showToast(`Pruned ${L} duplicate runtime(s) across ${N} group(s)`,"success"),await p()}catch(T){const D=T instanceof Error?T.message:"Duplicate prune failed";at.showToast(D,"warning"),a(D)}finally{c(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,p,r]),h=o.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((_,T)=>(T.lastActivityAt||0)-(_.lastActivityAt||0)),[u==null?void 0:u.sessions]),y=o.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:ey(h),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,h]),S=y.liveRuntimes,k=y.recoverySnapshots,A=y.inactiveRecords,M=o.useMemo(()=>ny(S),[S]),w=o.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),v=o.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(_=>_.level==="warn"||_.level==="error")||null,[u==null?void 0:u.recentLogs]),B=(_,T)=>{var H;const D=i===`session_host_resume_session:${_.sessionId}`,K=i===`session_host_restart_session:${_.sessionId}`,L=i===`session_host_stop_session:${_.sessionId}`,N=Ql(_.meta),I=g.get(_.sessionId),W=_.attachedClients.length===1?"1 client":`${_.attachedClients.length} clients`,P=T==="recovery"?"Recover":"Resume",$=ty(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||(I==null?void 0:I.cliName)||_.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${ry(_.lifecycle)}`,children:_.lifecycle}),N&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:N})]}),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||(I==null?void 0:I.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:((H=_.writeOwner)==null?void 0:H.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:sy(_.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(ec,{size:11})," ",W]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Wi(_.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",$]})]})]}),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:!!i,onClick:()=>{j("session_host_resume_session",_)},children:D?`${P}ing…`:P}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{j("session_host_restart_session",_)},children:K?"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:!!i,onClick:()=>{j("session_host_stop_session",_)},children:L?"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(Yt,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:jp()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[M>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{b()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${M})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${C.toneClass}`,children:C.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:f||l,children:[s.jsx(dr,{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(ir,{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:k.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:Wi(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:aa(u.hostStartedAt)})]})]}),v&&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(ir,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:v.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[aa(v.timestamp),v.sessionId?` · ${v.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(Oa,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ra("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(Yt,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ra("recovery")}),k.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:k.map(_=>B(_,"recovery"))})]}),A.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:ra("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:A.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"}),w.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:w.map(_=>{var D;const T=h.find(K=>K.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)||((D=g.get(_.sessionId))==null?void 0:D.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:aa(_.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 oy({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function oa({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 ia({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 iy({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),d=r.slice(0,4),m="0.9.75",u=jl(e),f=js(e,m),x=sr(e,f),C=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(oa,{icon:s.jsx(Ut,{size:13}),children:"Current Chats"}),s.jsx(ia,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(g=>{const p=Ma(g);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(g),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:lt(g)}),p>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:mn(p)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ps(g)})]},g.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(oa,{icon:s.jsx(nc,{size:13}),children:"Recent Launches"}),s.jsx(ia,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(g=>{const{metaText:p,updatedLabel:j}=Rl(g);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(g),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:g.label}),j&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:j})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:p})]},g.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(oa,{icon:s.jsx(ir,{size:13}),children:"Daemon Update"}),s.jsx(ia,{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:x?"Daemon update required":"Version mismatch detected"}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[x?"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(dr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:C})]})]})})]})]})}function cy(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function ly({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:i,onCustomPathChange:c,onOpenBrowseDialog:l}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,onChange:d=>{const m=d.target.value;if(i(m),m==="__custom__"&&a){l();return}m!=="__custom__"&&c("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(e.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(d=>s.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",pn(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 dy={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 $r(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ca({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const f=$s(),{handleLaunchIde:x,handleStopCli:C,handleRestartIde:g,handleStopIde:p,handleDetectIdes:j,launchingIde:b,launchingAgentType:h,addLog:y}=c,[S,k]=o.useState(null),A=o.useCallback(R=>{R&&f(Jt(R))},[f]),M=dy[e],w=e==="ide",v=e==="acp",B=o.useMemo(()=>n.filter(R=>hs(R,e)),[e,n]),_=o.useMemo(()=>new Map(B.map(R=>[R.type,R.displayName||R.type])),[B]),[T,D]=o.useState(""),[K,L]=o.useState(""),[N,I]=o.useState([]),[W,P]=o.useState(""),[$,H]=o.useState(""),[J,he]=o.useState([]),[ie,te]=o.useState(!1),[be,we]=o.useState(!1),[ge,X]=o.useState(""),[ce,ye]=o.useState(!1),[ne,de]=o.useState(()=>vt()),[je,me]=o.useState(null),[pe,ee]=o.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[ue,oe]=o.useState(m||""),[q,V]=o.useState([]),[le,ke]=o.useState(!1),[Z,De]=o.useState(""),[$e,Fe]=o.useState([]),[Ue,O]=o.useState(!1),[Ce,Te]=o.useState(""),_e=o.useRef(null),[Be,He]=o.useState(null),Xe=o.useRef("__home__"),[st,mt]=o.useState("__home__"),[ht,xt]=o.useState(!1),Ne=o.useRef(0),ze=q.filter(R=>!a.some(ae=>ae.type===R&&jt(ae.status)!=="stopped")),Je=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!pe&&ee(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(m){ee("__custom__"),oe(m);return}d&&(ee(d),oe(""))},[d,m]),o.useEffect(()=>{w||T&&(B.some(R=>R.type===T)||(D(""),H("")))},[B,w,T]);const Ge=(()=>{if(pe==="__custom__")return ue.trim();if(!pe)return"";const R=(t.workspaces||[]).find(ae=>ae.id===pe);return(R==null?void 0:R.path)||""})(),rt=o.useCallback(R=>{const ae=Je.current[R];ae&&(clearTimeout(ae),delete Je.current[R]),V(fe=>fe.includes(R)?fe.filter(Ke=>Ke!==R):fe)},[]),F=o.useRef(new Set),U=o.useCallback(async R=>{if(l){O(!0),Te("");try{const ae=await yn(l,r,R);De(ae.path),oe(ae.path),Fe(ae.directories)}catch(ae){Te(ae instanceof Error?ae.message:"Could not load folder")}finally{O(!1)}}},[r,l]),G=o.useCallback(()=>{if(!l)return;ee("__custom__"),ke(!0);const R=a.map(fe=>fe.workspace),ae=gn(t.platform,bn(ue.trim(),Ge,m,R,t.defaultWorkspacePath,(t.workspaces||[]).map(fe=>fe.path)));U(ae)},[ue,m,U,t.defaultWorkspacePath,t.platform,t.workspaces,a,Ge,l]),se=o.useCallback(R=>{const ae=String(R.workspace||"").trim();if(!ae)return;const fe=(t.workspaces||[]).find(Ke=>$r(Ke.path)===$r(ae));if(fe){ee(fe.id),oe("");return}ee("__custom__"),oe(ae)},[t.workspaces]),E=o.useCallback(R=>{const ae=String(R.workspace||"").trim();if(!ae)return{workspaceId:null,workspacePath:"",useHome:!0};const fe=(t.workspaces||[]).find(Ke=>$r(Ke.path)===$r(ae));return fe?{workspaceId:fe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ae,useHome:!1}},[t.workspaces]),Y=o.useCallback(async R=>{if(!l||!R||e!=="cli"){he([]),te(!1),we(!1),X("");return}const ae=Ne.current+1;Ne.current=ae,te(!0),X("");try{const fe=await l(r,"list_saved_sessions",{providerType:R,kind:"cli",limit:30});if(Ne.current!==ae)return;const Ke=(fe==null?void 0:fe.result)??fe;he(Array.isArray(Ke==null?void 0:Ke.sessions)?Ke.sessions:[])}catch(fe){if(Ne.current!==ae)return;he([]),X(fe instanceof Error?fe.message:"Could not load saved sessions")}finally{Ne.current===ae&&(te(!1),we(!0))}},[e,r,l]),Q=o.useMemo(()=>{if(e!=="cli"||!T)return null;const R=_.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:$||void 0,transport:"pty",mode:"chat",agentName:R,agentType:T,status:"idle",title:R,messages:[],ideType:T,workspaceName:Ge,workspacePath:Ge,displayPrimary:R,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,_,Ge,$,T]),re=o.useCallback(R=>{if(e==="ide"||!R){I([]);return}I(Ra(r,R))},[e,r]),ve=o.useCallback((R,ae)=>{e==="ide"||!R||(Nb(r,R,ae),I(Ra(r,R)))},[e,r]);o.useEffect(()=>{Ne.current+=1,H(""),re(T),we(!1),he([]),X(""),te(!1)},[e,re,Y,T]);const Ie=o.useMemo(()=>J.find(R=>R.providerSessionId===$)||null,[J,$]);o.useEffect(()=>{if(!$)return;const R=J.find(ae=>ae.providerSessionId===$);R!=null&&R.canResume||H("")},[J,$]);const Le=o.useCallback((R,ae)=>{_e.current=ae,Xe.current=R.selectedWorkspaceKey||"__home__",mt(R.selectedWorkspaceKey||"__home__"),He(R)},[]),Se=o.useCallback(()=>{_e.current&&(xt(!0),_e.current().finally(()=>{_e.current=null,xt(!1),He(null)}))},[]),Pe=o.useCallback(R=>{if(!R)return;V(fe=>fe.includes(R)?fe:[...fe,R]);const ae=Je.current[R];ae&&clearTimeout(ae),Je.current[R]=setTimeout(()=>{V(fe=>fe.includes(R)?fe.filter(Ke=>Ke!==R):fe),delete Je.current[R]},2e4)},[]);o.useEffect(()=>{for(const ae of a)jt(ae.status)!=="stopped"&&(q.includes(ae.type)&&!F.current.has(ae.type)&&(F.current.add(ae.type),y("info",`${_.get(ae.type)||ae.type} launched`,!0)),rt(ae.type));const R=new Set(a.filter(ae=>jt(ae.status)!=="stopped").map(ae=>ae.type));F.current.forEach(ae=>{!q.includes(ae)&&!R.has(ae)&&F.current.delete(ae)})},[y,rt,a,q,_]),o.useEffect(()=>()=>{Object.values(Je.current).forEach(clearTimeout),Je.current={}},[]);const[Ee,Ae]=o.useState({}),[qe,et]=o.useState(null);o.useEffect(()=>{if(!w||!r||!l)return;(async()=>{try{const ae=await l(r,"get_ide_extensions",{}),fe=(ae==null?void 0:ae.result)||ae;fe!=null&&fe.success&&(fe!=null&&fe.ideExtensions)&&Ae(fe.ideExtensions)}catch{}})()},[w,r,l]);const ct=R=>w?it(R.type):e==="cli"?R.cliName:R.acpName,ft=w?t.detectedIdes||[]:[],dt=o.useCallback(async R=>{const ae=(R==null?void 0:R.type)||T,fe=(R==null?void 0:R.workspacePath)??Ge;if(w){await x(ae,fe?{workspace:fe}:void 0)&&Pe(ae);return}const Ke=await c.runLaunchCliCore({cliType:ae,dir:R!=null&&R.workspaceId?void 0:fe||void 0,workspaceId:(R==null?void 0:R.workspaceId)||void 0,useHome:(R==null?void 0:R.useHome)||!(R!=null&&R.workspaceId)&&!fe,argsStr:(R==null?void 0:R.argsStr)??(K||void 0),model:(R==null?void 0:R.model)??(v&&W||void 0),resumeSessionId:(R==null?void 0:R.resumeSessionId)||!v&&e==="cli"&&ae===T&&$||void 0});if(Ke.success||Ke.pending){const Re=(R==null?void 0:R.argsStr)??K;!w&&(Re!=null&&Re.trim())&&(zl(r,ae,Re),re(ae)),Pe(ae),Ke.success&&Ke.sessionId&&A(Ke.sessionId)}},[c,x,v,w,K,W,re,Pe,r,A,Ge,$,T]),gt=qc(w?"ide":v?"acp":"cli",!w&&!v&&!!$),Ve=Yc(w?"ide":v?"acp":"cli",!w&&!v&&!!$),xe=()=>{var Re;const R=w?it(T):_.get(T)||T,ae=!w&&!v&&!!$,{options:fe,selectedKey:Ke}=ds({machine:t,currentWorkspaceId:pe&&pe!=="__custom__"?pe:null,currentWorkspacePath:Ge});Le({title:ae?no(R):as("start-fresh",R),description:ae?ao():os("start-fresh"),confirmLabel:gt,busyLabel:Ve,workspaceOptions:fe,selectedWorkspaceKey:Ke,details:[{label:"Mode",value:M.label},{label:"Provider",value:R},...!w&&e==="cli"&&$?[{label:"Resume",value:((Re=J.find(We=>We.providerSessionId===$))==null?void 0:Re.title)||$}]:[],...!w&&K.trim()?[{label:"Arguments",value:K.trim()}]:[],...v&&W.trim()?[{label:"Model",value:W.trim()}]:[]]},async()=>{const We=fe.find(ot=>ot.key===Xe.current);We!=null&&We.workspaceId?(ee(We.workspaceId),oe("")):We!=null&&We.workspacePath?(ee("__custom__"),oe(We.workspacePath)):(ee(""),oe("")),await dt({workspaceId:(We==null?void 0:We.workspaceId)??null,workspacePath:(We==null?void 0:We.workspacePath)??"",useHome:!(We!=null&&We.workspaceId)&&!(We!=null&&We.workspacePath)})})},z=R=>{w?p(R):C(R.type,R.workspace,R.id)},Me=o.useCallback(async(R,ae,fe=!1)=>{if(R.mode===ae){fe&&R.sessionId&&A(R.sessionId);return}if(!l||!R.sessionId){fe&&R.sessionId&&A(R.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:R.sessionId,cliType:R.type,mode:ae}),fe&&A(R.sessionId)}catch(Ke){const Re=fl(Ke);ml(Ke)?console.warn(Re?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ke instanceof Error?Ke.message:String(Ke)):console.error("Failed to switch CLI view mode:",Ke)}},[r,A,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${M.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",M.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:w?ft.length>0?ft.map(R=>{const ae=a.find(ot=>(ot.type||"").toLowerCase()===(R.type||"").toLowerCase()&&jt(ot.status)!=="stopped"),fe=R.running||!!ae,Ke=!!ae&&ae.cdpConnected,Re=q.includes(R.type||R.id||""),We=T===(R.type||"");return s.jsxs("button",{onClick:()=>{if(Ke&&ae){const ot=ae.sessionId;ot?f(Jt(ot),{state:{openRemoteForTabKey:ot}}):f("/dashboard",{state:{openRemoteForTabKey:ae.id}});return}Re||D(ot=>ot===(R.type||"")?"":R.type||"")},disabled:!!b||Re,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ke?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":We?"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:b&&b!==R.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(R.type)}),fe&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ke?"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:R.name||it(R.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ke?"text-green-400":Re?"text-orange-400":We?"text-accent-primary":"text-text-muted"}`,children:Ke?"Open Session":Re?"Starting...":We?"Configure":"Select"})]})]},R.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:j,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(cu,{size:14})," Scan System"]})]}):B.length>0?B.map(R=>{const ae=T===R.type,fe=q.includes(R.type),Re=!!a.find(We=>We.type===R.type&&jt(We.status)!=="stopped");return s.jsxs("button",{onClick:()=>D(We=>We===R.type?"":R.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ae?"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:R.icon}),Re&&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:R.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${fe?"text-orange-400":ae?"text-accent-primary":"text-text-muted"}`,children:fe?"Starting...":ae?"Configure":"Select"})]})]},R.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&&(w?ft.find(R=>R.type===T):B.find(R=>R.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:w?it(T):_.get(T)||T})]}),s.jsx(ly,{machine:t,selectedWorkspace:pe,resolvedWorkspacePath:Ge,customPath:ue,canBrowse:!!l,onWorkspaceChange:ee,onCustomPathChange:oe,onOpenBrowseDialog:G}),!w&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&s.jsx(Gl,{busy:!!h||!!b||q.includes(T),savedSessionsLoading:ie,savedSessionsError:ge,savedSessionsLoaded:be,savedSessionsCount:J.length,selectedSession:Ie,onRefresh:()=>void Y(T),onOpenHistory:()=>{T&&(ye(!0),Vl({hasLoadedInitialResults:be,isLoading:ie})&&Y(T))},onClearSelection:()=>H("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value:W,onChange:R=>P(R.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:K,onChange:R=>L(R.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"}),N.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:N.map(R=>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:R,children:[s.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>L(R),children:R}),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:()=>ve(T,R),"aria-label":`Remove startup arguments: ${R}`,title:"Remove startup arguments",children:s.jsx(yt,{size:12})})]},R))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:xe,disabled:!!h||!!b||q.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:h===T||b===T?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+q.filter(R=>!a.some(ae=>ae.type===R&&jt(ae.status)!=="stopped")).length,")"]}),a.length===0&&ze.length===0?s.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",M.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[ze.map(R=>s.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(R)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:w?it(R):_.get(R)||R}),s.jsx("div",{className:"text-[11px] text-text-muted",children:h===R?"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:${R}`)),a.map(R=>{const ae=w?R:null,fe=!w&&!v?R:null,Ke=jt(R.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(R.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[ct(R),(ae==null?void 0:ae.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ae.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:R.workspace||"—"}),u&&R.git&&R.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:Re=>{Re.stopPropagation(),u(R.daemonId??r,R.workspace)},children:s.jsx(_s,{git:R.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(_s,{git:R.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(fe==null?void 0:fe.mode)&&s.jsx("span",{className:fe.mode==="chat"?"text-violet-400":"text-text-secondary",children:fe.mode==="chat"?"Chat view":"Terminal view"})]}),fe&&(fe.runtimeKey||fe.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[fe.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 ",fe.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 Re;(Re=navigator.clipboard)==null||Re.writeText(`adhdev attach ${fe.runtimeKey}`),k(fe.runtimeKey||null),window.setTimeout(()=>{k(We=>We===fe.runtimeKey?null:We)},1200)},children:S===fe.runtimeKey?"Copied":"Copy"})]}),fe.runtimeWriteOwner&&s.jsx("span",{style:{color:fe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:fe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:cy(fe.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 ${Ke==="stopped"?"bg-red-500/[0.08] text-red-500":Ke==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ke}),w&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Re=R.sessionId;if(Re){f(Jt(Re),{state:{openRemoteForTabKey:Re}});return}f("/dashboard",{state:{openRemoteForTabKey:R.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(Mt,{size:13})}),s.jsx("button",{onClick:()=>{const Re=R.workspace||"",{options:We,selectedKey:ot}=ds({machine:t,currentWorkspacePath:Re});Le({title:as("restart-ide",it(R.type)),description:os("restart-ide"),confirmLabel:Ps("restart-ide"),busyLabel:Ds("restart-ide"),workspaceOptions:We,selectedWorkspaceKey:ot,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:it(R.type)}]},async()=>{const Nt=We.find(Vt=>Vt.key===Xe.current),pt=(Nt==null?void 0:Nt.workspacePath)??"";if(pt&&pt!==Re){await dt({type:R.type,workspacePath:pt});return}await g(R)})},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(dr,{size:14})})]}),v&&s.jsx("button",{onClick:()=>{const Re=R.sessionId;Re&&A(Re)},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:!R.sessionId,children:s.jsx(Ut,{size:14})}),fe&&Ke!=="stopped"&&s.jsxs(s.Fragment,{children:[fe.mode&&s.jsx(to,{mode:fe.mode,onChange:Re=>void Me(fe,Re,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Re=R.sessionId;Re&&A(Re)},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:!R.sessionId,children:fe.mode==="chat"?s.jsx(Ut,{size:14}):s.jsx(Mt,{size:13})})]}),Ke==="stopped"?s.jsx("button",{onClick:()=>{const Re=R.workspace||"",We=w?it(R.type):ct(R),{options:ot,selectedKey:Nt}=ds({machine:t,currentWorkspacePath:Re});Le({title:as("restart-stopped",We),description:os("restart-stopped"),confirmLabel:Ps("restart-stopped"),busyLabel:Ds("restart-stopped"),workspaceOptions:ot,selectedWorkspaceKey:Nt,details:[{label:"Mode",value:M.label},{label:"Provider",value:We}]},async()=>{const pt=ot.find(Vt=>Vt.key===Xe.current);await dt({type:R.type,workspaceId:(pt==null?void 0:pt.workspaceId)??null,workspacePath:(pt==null?void 0:pt.workspacePath)??"",useHome:!(pt!=null&&pt.workspaceId)&&!(pt!=null&&pt.workspacePath)})})},disabled:q.includes(R.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:q.includes(R.type)?"⏳":s.jsx(Fa,{size:14})}):s.jsx("button",{onClick:()=>z(R),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(yt,{size:14})})]})]}),ae&&ae.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ae.aiAgents.map(Re=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${pc(Re.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Re.name," · ",jt(Re.status)]},Re.id))}),ae&&(Ee[ae.type]||[]).length>0&&l&&s.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[s.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(Ee[ae.type]||[]).map(Re=>s.jsxs("button",{disabled:qe===`${ae.type}.${Re.type}`,onClick:async()=>{const We=`${ae.type}.${Re.type}`;et(We);try{await l(r,"set_ide_extension",{ideType:ae.type,extensionType:Re.type,enabled:!Re.enabled}),Ae(ot=>({...ot,[ae.type]:(ot[ae.type]||[]).map(Nt=>Nt.type===Re.type?{...Nt,enabled:!Nt.enabled}:Nt)}))}catch(ot){console.error("Extension toggle failed:",ot)}finally{et(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 ${Re.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 ${Re.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Re.name,s.jsx("span",{className:"text-[9px] font-normal",children:Re.enabled?"ON":"OFF"})]},Re.type))})]})]},R.id)})]}),le&&l&&s.jsx(vn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:Z,directories:$e,busy:Ue,error:Ce,confirmLabel:"Use this folder",onClose:()=>ke(!1),onNavigate:R=>{U(R)},onConfirm:R=>{oe(R),ee("__custom__"),ke(!1)}}),Be&&s.jsx(go,{title:Be.title,description:Be.description,details:Be.details,workspaceOptions:Be.workspaceOptions,selectedWorkspaceKey:st,onWorkspaceChange:R=>{Xe.current=R,mt(R)},confirmLabel:Be.confirmLabel,busyLabel:Be.busyLabel,busy:ht,onConfirm:Se,onCancel:()=>{_e.current=null,He(null)}}),ce&&Q&&s.jsx(oo,{activeConv:Q,ides:[],isCreatingChat:!1,isRefreshingHistory:ie,savedSessions:J,isSavedSessionsLoading:ie,isResumingSavedSessionId:je,savedHistoryFilters:ne,missingWorkspaceResumePath:Ge||null,onSavedHistoryFiltersChange:de,onClose:()=>ye(!1),onNewChat:()=>{H(""),ye(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Y(T)},onResumeSavedSession:R=>{if(!R.canResume||je)return;const ae=E(R);H(R.providerSessionId),se(R),me(R.providerSessionId),ye(!1),dt({type:R.providerType,workspaceId:ae.workspaceId,workspacePath:ae.workspacePath,useHome:ae.useHome,resumeSessionId:R.providerSessionId}).finally(()=>{me(fe=>fe===R.providerSessionId?null:fe)})}})]})}const Oi=[{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 uy({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:f,onOpenGitDialog:x}){var j;const[C,g]=o.useState(d);o.useEffect(()=>{g(d)},[d]);const p=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Oi.map(b=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${C===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>g(b.id),children:[s.jsx("span",{children:b.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${C===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:p[b.id]})]},b.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(j=Oi.find(b=>b.id===C))==null?void 0:j.helper})]}),C==="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:x}),C==="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:x}),C==="acp"&&s.jsx(ca,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x})]})}function my({onNicknameSynced:e}={}){var oe,q,V,le,ke,Z,De,$e,Fe,Ue;const{id:t}=Rd(),r=$s(),n=Ea(),{sendCommand:a}=bt(),i=fr(),c=cl(),l=Wc(),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"),x=t?(oe=l.connectionRetryStatuses)==null?void 0:oe[t]:void 0,C=!!(x!=null&&x.blocked),[g,p]=o.useState("workspace"),[j,b]=o.useState(null),h=o.useCallback((O,Ce)=>{b({daemonId:O,workspace:Ce})},[]),[y,S]=o.useState("ide"),k=o.useRef(null),[A,M]=o.useState(null),w=o.useRef("__home__"),[v,B]=o.useState("__home__"),[_,T]=o.useState(!1),D=o.useRef(null);o.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||i(t,{minFreshMs:3e4}).catch(()=>{})},[i,u,t]),o.useEffect(()=>{if(!t||!u||g!=="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(()=>{})},[g,c,u,t]),hh(t&&g==="overview"?[t]:[],{enabled:g==="overview",intervalMs:ff});const K=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},L=ig({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:D});o.useEffect(()=>at.onToast(Ce=>{l.setToasts(_e=>{if(_e.some(Xe=>Xe.message===Ce.message&&Ce.timestamp-Xe.timestamp<3e3))return _e;const He={id:Ce.id,message:Ce.message,type:Ce.type,timestamp:Ce.timestamp,targetKey:Ce.targetKey,actions:Ce.actions};return[..._e.slice(-4),He]});const Te=Ce.duration||5e3;setTimeout(()=>l.setToasts(_e=>_e.filter(Be=>Be.id!==Ce.id)),Te)}),[l]);const N=(u==null?void 0:u.availableProviders)||[],I={};for(const O of N)I[O.type]=O.icon;const W=O=>I[O]||"",P=u?{id:u.id,hostname:hc(u,{fallbackId:u.id}),platform:((q=u.machine)==null?void 0:q.platform)||"unknown",arch:((V=u.machine)==null?void 0:V.arch)||"",cpus:((le=u.machine)==null?void 0:le.cpus)||0,totalMem:((ke=u.machine)==null?void 0:ke.totalMem)||0,freeMem:(Z=u.machine)==null?void 0:Z.freeMem,availableMem:(De=u.machine)==null?void 0:De.availableMem,loadavg:($e=u.machine)==null?void 0:$e.loadavg,uptime:(Fe=u.machine)==null?void 0:Fe.uptime,release:((Ue=u.machine)==null?void 0:Ue.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,$=d.filter(O=>O.daemonId===t&&O.type!=="adhdev-daemon").filter(O=>!cr(O)&&!Ns(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:dm(O.aiAgents||(O.agents||[]).map(Ce=>({id:Ce.name,name:Ce.name,status:Ce.status,version:Ce.version}))),activeChat:O.activeChat||null,chats:O.chats||[],childSessions:O.childSessions||[],cdpConnected:O.cdpConnected||!1,daemonId:t})),H=d.filter(O=>O.daemonId===t&&cr(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})),J=d.filter(O=>O.daemonId===t&&Ns(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})),he=u?Tt(u,{fallbackId:t}):"",ie="workspace",te=n.state,be=te==null?void 0:te.initialMachineTab,we=te==null?void 0:te.initialWorkspaceCategory,ge=te==null?void 0:te.initialWorkspaceId,X=te==null?void 0:te.initialWorkspacePath,ce=be==="ides"||be==="clis"||be==="acps"?"workspace":be||ie,ye=be==="ides"?"ide":be==="clis"?"cli":be==="acps"?"acp":we,ne=[...$.map(O=>{var Ce,Te,_e,Be,He;return{id:`ide:${O.type}:${O.workspace||""}`,label:((Ce=O.activeChat)==null?void 0:Ce.title)||O.type,kind:"ide",providerType:O.type,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:((He=(Be=(_e=(Te=O.activeChat)==null?void 0:Te.messages)==null?void 0:_e.at)==null?void 0:Be.call(_e,-1))==null?void 0:He.timestamp)||0}}),...H.map(O=>{var Ce,Te,_e,Be,He;return{id:`cli:${O.type}:${O.workspace||""}`,label:((Ce=O.activeChat)==null?void 0:Ce.title)||O.cliName,kind:"cli",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:((He=(Be=(_e=(Te=O.activeChat)==null?void 0:Te.messages)==null?void 0:_e.at)==null?void 0:Be.call(_e,-1))==null?void 0:He.timestamp)||0}}),...J.map(O=>{var Ce,Te,_e,Be,He;return{id:`acp:${O.type}:${O.workspace||""}`,label:((Ce=O.activeChat)==null?void 0:Ce.title)||O.acpName,kind:"acp",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:fs(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:((He=(Be=(_e=(Te=O.activeChat)==null?void 0:Te.messages)==null?void 0:_e.at)==null?void 0:Be.call(_e,-1))==null?void 0:He.timestamp)||0}})].sort((O,Ce)=>(Ce.lastLaunchedAt||0)-(O.lastLaunchedAt||0)),de=((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:fs(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace,summaryMetadata:O.summaryMetadata,lastLaunchedAt:O.lastLaunchedAt})):ne,je=o.useMemo(()=>{var Ce;const O=((Ce=l.connectionStates)==null?void 0:Ce[t||""])||void 0;return d.filter(Te=>Te.daemonId===t&&Te.type!=="adhdev-daemon").flatMap(Te=>io(Te,{connectionStates:t&&O?{[t]:O}:void 0,defaultConnectionState:O})).filter(Te=>!(Te.transport==="pty"&&Te.mode==="terminal")).sort((Te,_e)=>Ma(_e)-Ma(Te))},[d,l.connectionStates,t]),me=o.useCallback(O=>{const Ce=xo(O);Ce&&r(Jt(Ce))},[r]),pe=o.useCallback(()=>{k.current&&(T(!0),k.current().finally(()=>{k.current=null,T(!1),M(null)}))},[]),ee=o.useCallback(O=>{if(!P)return;const{options:Ce,selectedKey:Te}=ds({machine:P,currentWorkspacePath:O.workspace}),_e=async()=>{S(O.kind),p("workspace")};k.current=async()=>{const Be=Ce.find(st=>st.key===w.current),He=(Be==null?void 0:Be.workspacePath)??null,Xe=(Be==null?void 0:Be.workspaceId)??null;if(O.kind==="ide"&&O.providerType){await L.handleLaunchIde(O.providerType,He?{workspace:He}:void 0);return}if((O.kind==="cli"||O.kind==="acp")&&O.providerType){await L.runLaunchCliCore({cliType:O.providerType,dir:Xe?void 0:He||"",workspaceId:Xe||void 0,model:O.kind==="acp"&&bc(O.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:O.providerSessionId});return}await _e()},w.current=Te,B(Te),M({title:O.kind==="ide"?as("restart-ide",O.label):O.providerSessionId?no(O.label):as("start-fresh",O.label),description:O.kind==="ide"?os("restart-ide"):O.providerSessionId?ao():os("start-fresh"),confirmLabel:O.kind==="ide"?Ps("restart-ide"):O.providerSessionId?rn(!0):Ps("start-fresh"),busyLabel:O.kind==="ide"?Ds("restart-ide"):O.providerSessionId?so(!0):Ds("start-fresh"),workspaceOptions:Ce,details:[{label:"Mode",value:O.kind.toUpperCase()},...O.providerType?[{label:"Provider",value:O.providerType}]:[]]})},[L,P]);if(o.useEffect(()=>{p(ce)},[ie,ce,t]),o.useEffect(()=>{ye&&S(ye)},[ye,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:K,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 ue=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Mt,{size:14})," Workspace"]}),count:$.length+H.length+J.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Yt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(dn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(lu,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ou,{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:K,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:[L.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:L.nicknameInput,onChange:O=>L.setNicknameInput(O.target.value),onKeyDown:O=>{O.key==="Enter"&&L.handleSaveNickname(),O.key==="Escape"&&L.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:L.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:()=>L.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:()=>{L.setEditingNickname(!0),L.setNicknameInput(P.machineNickname||"")},title:"Click to set nickname",children:he}),C?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:ue.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 ${g===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 ${g===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:[g==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(iy,{machineEntry:u,providers:N,recentLaunches:de,currentConversations:je,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",kl(u))}catch{}},onOpenRecent:ee,onOpenConversation:me}),s.jsx(uy,{machine:P,machineId:t,providers:N,ideSessions:$,cliSessions:H,acpSessions:J,actions:L,getIcon:W,initialCategory:y,initialWorkspaceId:ge,initialWorkspacePath:X,sendDaemonCommand:a,onOpenGitDialog:h})]}),g==="providers"&&s.jsx(bg,{machineId:t,providers:N,sendDaemonCommand:a}),g==="overview"&&s.jsx(cg,{machineId:t,machine:P,ideSessions:$,cliSessions:H,acpSessions:J,actions:L,sendDaemonCommand:a}),g==="session-host"&&s.jsx(ay,{machineId:t,cliSessions:H,sendDaemonCommand:a}),g==="logs"&&s.jsx(Qg,{machineId:t,sendDaemonCommand:a})]})})}),L.launchPick&&P&&s.jsx(oy,{machine:P,launchPick:L.launchPick,actions:L}),A&&s.jsx(go,{title:A.title,description:A.description,details:A.details,workspaceOptions:A.workspaceOptions,selectedWorkspaceKey:v,onWorkspaceChange:O=>{w.current=O,B(O)},confirmLabel:A.confirmLabel,busyLabel:A.busyLabel,busy:_,onConfirm:pe,onCancel:()=>{k.current=null,M(null)}}),j&&s.jsx(Xl,{daemonId:j.daemonId,workspace:j.workspace,onClose:()=>b(null)}),s.jsx(Xc,{toasts:l.toasts||[],onDismiss:O=>l.setToasts(Ce=>Ce.filter(Te=>Te.id!==O)),onClickToast:O=>{O.targetKey&&r(Jt(O.targetKey))}}),s.jsx("style",{children:`
87
+ `)}function Ug(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function zg(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Vg({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:i,quickFilter:c,searchQuery:l,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f}){const x=jg(n,i),C=Ng(e,l),y=Mg(t,l),p=Ag(x,l),g=Ig(a,l),b=Ug(C,c),h=c==="all"?y:[],k=zg(p,c),S=c==="issues"?[]:g,j=Rg({daemonLogs:C,daemonRawLines:y,trace:p,webEvents:g}),A=Kg({daemonLogs:b,daemonRawLines:h,trace:k,webEvents:S}),M=Og(A),w=Pg({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f,daemonLogKind:r,daemonLogsCount:C.length,daemonRawLineCount:y.length,traceCount:p.length,webEventCount:g.length});return{filteredDaemonLogs:C,filteredDaemonRawLines:y,filteredTraceEntries:p,filteredWebEvents:g,visibleDaemonLogs:b,visibleDaemonRawLines:h,visibleTraceEntries:k,visibleWebEvents:S,quickFilterCounts:j,diagnosticEvents:A,diagnosticsSummary:M,sourceStates:w}}function Gg(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Ql(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function _a(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 ra(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 No(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function qg({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${_a(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Ql(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:No(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 Yg({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:i,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=>i(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 Xg({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:vg.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 Jg({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:i,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":i?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${ra(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 ${ra(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:[No(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:Ql(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 ${ra(m)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:c||l?"Needs attention":i?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",Gg(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(x=>s.jsxs("div",{children:[x.label,": ",x.status]},x.id))})]})]})}function Qg({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()," · ",No(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function Zg({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:i,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(qg,{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"?`${i.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&i.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&i.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children: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"&&i.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 ${_a(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 ${_a(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:Es(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:Es(u.payload,360)||"No payload"})]},u.id))]})]})]})}function ey({machineId:e,sendDaemonCommand:t}){const r=_g({machineId:e,sendDaemonCommand:t}),[n,a]=o.useState("info"),[i,c]=o.useState(""),[l,d]=o.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=o.useRef(null),u=o.useRef(!1),f=o.useMemo(()=>Vg({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:i,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,i,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);o.useEffect(()=>{if(r.autoRefresh&&f.diagnosticEvents.length>0){const y=u.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:y}),u.current=!0},50)}},[f.diagnosticEvents.length,r.autoRefresh]);const x=o.useCallback(async()=>{var p;const y=Lg({daemonLogs:f.visibleDaemonLogs,daemonRawLines:f.visibleDaemonRawLines,trace:f.visibleTraceEntries,webEvents:f.visibleWebEvents});if(!y.trim()){at.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(y)),at.showToast("Copied visible logs to clipboard.","success")}catch(g){at.showToast(g instanceof Error?g.message:"Could not copy visible logs","warning")}},[f.visibleDaemonLogs,f.visibleDaemonRawLines,f.visibleTraceEntries,f.visibleWebEvents]),C=o.useCallback(async()=>{var p;const y=Hg({events:f.diagnosticEvents,summary:f.diagnosticsSummary,sources:f.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(y)),at.showToast("Copied diagnostic bundle to clipboard.","success")}catch(g){at.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(Yg,{quickFilter:n,quickFilterCounts:f.quickFilterCounts,searchQuery:i,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{C()},onCopyVisible:()=>{x()},onToggleAutoRefresh:()=>r.setAutoRefresh(y=>!y),onRefresh:r.refresh,onClear:r.clear}),s.jsx(Xg,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(Jg,{diagnosticsSummary:f.diagnosticsSummary,diagnosticEventsCount:f.diagnosticEvents.length,sourceStates:f.sourceStates,searchQuery:i,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(Qg,{patterns:f.diagnosticsSummary.repeatedPatterns}),s.jsx(Zg,{streams:r,sectionsOpen:l,setSectionsOpen:d,diagnosticEvents:f.diagnosticEvents,visibleDaemonLogs:f.visibleDaemonLogs,visibleDaemonRawLines:f.visibleDaemonRawLines,visibleTraceEntries:f.visibleTraceEntries,visibleWebEvents:f.visibleWebEvents,quickFilter:n,searchQuery:i}),s.jsx("div",{ref:m})]})}function ty(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 Zl(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 sy(e){var a;const t=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=Zl((i==null?void 0:i.meta)||void 0),d=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?t.push(i):(c==="stopped"||c==="failed")&&(d||l)?r.push(i):n.push(i)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function ry(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function na(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 aa(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function oa(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Fi(e){if(!e)return"unknown";const t=Date.now()-e,r=Math.max(0,Math.round(t/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function ny(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function ay(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 oy(e){var r;const t=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const i=`${n.providerType}::${n.workspace}::${a}`;t.set(i,(t.get(i)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function iy({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,d]=o.useState(!1),m=gh(e,{enabled:!!e,includeSessions:!0,limit:Qo,intervalMs:yf}),u=m.diagnostics,f=m.loading,x=m.applyDiagnostics,C=o.useMemo(()=>ty({diagnostics:u,loading:f,refreshing:l,error:n}),[u,f,l,n]),y=o.useMemo(()=>new Map(t.map(_=>[_.sessionId||_.id,_])),[t]),p=o.useCallback(async()=>{if(e){d(!0);try{const _=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Qo}),T=aa(_);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");x(T.diagnostics||T.result||null),a("")}catch(_){const T=_ instanceof Error?_.message:"Could not load hosted runtime diagnostics";a(T)}finally{d(!1)}}},[x,e,r]);o.useEffect(()=>{!e||u||f||l||p()},[u,f,e,p,l]);const g=o.useCallback(async(_,T)=>{const D=`${_}:${T.sessionId}`;if(!(_==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
88
+ This will terminate the hosted runtime.`))){c(D);try{const K=await r(e,_,{sessionId:T.sessionId}),L=aa(K);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Session host action failed");const N=_==="session_host_resume_session"?"resumed":_==="session_host_restart_session"?"restarted":"stopped";at.showToast(`Session host ${N}: ${T.displayName}`,"success"),await p()}catch(K){const L=K instanceof Error?K.message:"Session host action failed";at.showToast(L,"warning"),a(L)}finally{c(K=>K===D?null:K)}}},[e,p,r]),b=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
89
+ 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",{}),D=aa(T);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Duplicate prune failed");const K=D.result||{},L=Array.isArray(K.prunedSessionIds)?K.prunedSessionIds.length:0,N=typeof K.duplicateGroupCount=="number"?K.duplicateGroupCount:0;at.showToast(`Pruned ${L} duplicate runtime(s) across ${N} group(s)`,"success"),await p()}catch(T){const D=T instanceof Error?T.message:"Duplicate prune failed";at.showToast(D,"warning"),a(D)}finally{c(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,p,r]),h=o.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((_,T)=>(T.lastActivityAt||0)-(_.lastActivityAt||0)),[u==null?void 0:u.sessions]),k=o.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:sy(h),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,h]),S=k.liveRuntimes,j=k.recoverySnapshots,A=k.inactiveRecords,M=o.useMemo(()=>oy(S),[S]),w=o.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),v=o.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(_=>_.level==="warn"||_.level==="error")||null,[u==null?void 0:u.recentLogs]),B=(_,T)=>{var H;const D=i===`session_host_resume_session:${_.sessionId}`,K=i===`session_host_restart_session:${_.sessionId}`,L=i===`session_host_stop_session:${_.sessionId}`,N=Zl(_.meta),I=y.get(_.sessionId),F=_.attachedClients.length===1?"1 client":`${_.attachedClients.length} clients`,P=T==="recovery"?"Recover":"Resume",$=ry(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||(I==null?void 0:I.cliName)||_.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${ay(_.lifecycle)}`,children:_.lifecycle}),N&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:N})]}),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||(I==null?void 0:I.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:((H=_.writeOwner)==null?void 0:H.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:ny(_.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(sc,{size:11})," ",F]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Fi(_.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",$]})]})]}),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:!!i,onClick:()=>{g("session_host_resume_session",_)},children:D?`${P}ing…`:P}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{g("session_host_restart_session",_)},children:K?"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:!!i,onClick:()=>{g("session_host_stop_session",_)},children:L?"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(Yt,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Sp()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[M>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{b()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${M})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${C.toneClass}`,children:C.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:f||l,children:[s.jsx(dr,{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(ir,{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:j.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Fi(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:oa(u.hostStartedAt)})]})]}),v&&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(ir,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:v.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[oa(v.timestamp),v.sessionId?` · ${v.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(Fa,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:na("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(Yt,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:na("recovery")}),j.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:j.map(_=>B(_,"recovery"))})]}),A.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:na("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:A.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"}),w.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:w.map(_=>{var D;const T=h.find(K=>K.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)||((D=y.get(_.sessionId))==null?void 0:D.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:oa(_.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 cy({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function ia({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 ca({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 ly({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),d=r.slice(0,4),m="0.9.75",u=kl(e),f=js(e,m),x=sr(e,f),C=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(ia,{icon:s.jsx(Ut,{size:13}),children:"Current Chats"}),s.jsx(ca,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(y=>{const p=Aa(y);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(y),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:lt(y)}),p>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:fn(p)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ps(y)})]},y.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ia,{icon:s.jsx(oc,{size:13}),children:"Recent Launches"}),s.jsx(ca,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(y=>{const{metaText:p,updatedLabel:g}=Ll(y);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(y),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:y.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})]},y.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(ia,{icon:s.jsx(ir,{size:13}),children:"Daemon Update"}),s.jsx(ca,{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:x?"Daemon update required":"Version mismatch detected"}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[x?"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(dr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:C})]})]})})]})]})}function dy(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function uy({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:i,onCustomPathChange:c,onOpenBrowseDialog:l}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,onChange:d=>{const m=d.target.value;if(i(m),m==="__custom__"&&a){l();return}m!=="__custom__"&&c("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(e.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(d=>s.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",hn(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 my={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 $r(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function la({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const f=$s(),{handleLaunchIde:x,handleStopCli:C,handleRestartIde:y,handleStopIde:p,handleDetectIdes:g,launchingIde:b,launchingAgentType:h,addLog:k}=c,[S,j]=o.useState(null),A=o.useCallback(R=>{R&&f(Jt(R))},[f]),M=my[e],w=e==="ide",v=e==="acp",B=o.useMemo(()=>n.filter(R=>hs(R,e)),[e,n]),_=o.useMemo(()=>new Map(B.map(R=>[R.type,R.displayName||R.type])),[B]),[T,D]=o.useState(""),[K,L]=o.useState(""),[N,I]=o.useState([]),[F,P]=o.useState(""),[$,H]=o.useState(""),[J,he]=o.useState([]),[ie,te]=o.useState(!1),[be,we]=o.useState(!1),[ge,X]=o.useState(""),[ce,ye]=o.useState(!1),[ne,de]=o.useState(()=>wt()),[je,me]=o.useState(null),[pe,ee]=o.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[ue,oe]=o.useState(m||""),[q,V]=o.useState([]),[le,ke]=o.useState(!1),[Z,De]=o.useState(""),[$e,Fe]=o.useState([]),[Ue,W]=o.useState(!1),[Ce,Te]=o.useState(""),_e=o.useRef(null),[Be,He]=o.useState(null),Xe=o.useRef("__home__"),[st,mt]=o.useState("__home__"),[ht,xt]=o.useState(!1),Ne=o.useRef(0),ze=q.filter(R=>!a.some(ae=>ae.type===R&&bt(ae.status)!=="stopped")),Je=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!pe&&ee(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(m){ee("__custom__"),oe(m);return}d&&(ee(d),oe(""))},[d,m]),o.useEffect(()=>{w||T&&(B.some(R=>R.type===T)||(D(""),H("")))},[B,w,T]);const Ge=(()=>{if(pe==="__custom__")return ue.trim();if(!pe)return"";const R=(t.workspaces||[]).find(ae=>ae.id===pe);return(R==null?void 0:R.path)||""})(),rt=o.useCallback(R=>{const ae=Je.current[R];ae&&(clearTimeout(ae),delete Je.current[R]),V(fe=>fe.includes(R)?fe.filter(Ke=>Ke!==R):fe)},[]),O=o.useRef(new Set),U=o.useCallback(async R=>{if(l){W(!0),Te("");try{const ae=await vn(l,r,R);De(ae.path),oe(ae.path),Fe(ae.directories)}catch(ae){Te(ae instanceof Error?ae.message:"Could not load folder")}finally{W(!1)}}},[r,l]),G=o.useCallback(()=>{if(!l)return;ee("__custom__"),ke(!0);const R=a.map(fe=>fe.workspace),ae=yn(t.platform,gn(ue.trim(),Ge,m,R,t.defaultWorkspacePath,(t.workspaces||[]).map(fe=>fe.path)));U(ae)},[ue,m,U,t.defaultWorkspacePath,t.platform,t.workspaces,a,Ge,l]),se=o.useCallback(R=>{const ae=String(R.workspace||"").trim();if(!ae)return;const fe=(t.workspaces||[]).find(Ke=>$r(Ke.path)===$r(ae));if(fe){ee(fe.id),oe("");return}ee("__custom__"),oe(ae)},[t.workspaces]),E=o.useCallback(R=>{const ae=String(R.workspace||"").trim();if(!ae)return{workspaceId:null,workspacePath:"",useHome:!0};const fe=(t.workspaces||[]).find(Ke=>$r(Ke.path)===$r(ae));return fe?{workspaceId:fe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ae,useHome:!1}},[t.workspaces]),Y=o.useCallback(async R=>{if(!l||!R||e!=="cli"){he([]),te(!1),we(!1),X("");return}const ae=Ne.current+1;Ne.current=ae,te(!0),X("");try{const fe=await l(r,"list_saved_sessions",{providerType:R,kind:"cli",limit:30});if(Ne.current!==ae)return;const Ke=(fe==null?void 0:fe.result)??fe;he(Array.isArray(Ke==null?void 0:Ke.sessions)?Ke.sessions:[])}catch(fe){if(Ne.current!==ae)return;he([]),X(fe instanceof Error?fe.message:"Could not load saved sessions")}finally{Ne.current===ae&&(te(!1),we(!0))}},[e,r,l]),Q=o.useMemo(()=>{if(e!=="cli"||!T)return null;const R=_.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:$||void 0,transport:"pty",mode:"chat",agentName:R,agentType:T,status:"idle",title:R,messages:[],ideType:T,workspaceName:Ge,workspacePath:Ge,displayPrimary:R,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,_,Ge,$,T]),re=o.useCallback(R=>{if(e==="ide"||!R){I([]);return}I(La(r,R))},[e,r]),ve=o.useCallback((R,ae)=>{e==="ide"||!R||(Tb(r,R,ae),I(La(r,R)))},[e,r]);o.useEffect(()=>{Ne.current+=1,H(""),re(T),we(!1),he([]),X(""),te(!1)},[e,re,Y,T]);const Ie=o.useMemo(()=>J.find(R=>R.providerSessionId===$)||null,[J,$]);o.useEffect(()=>{if(!$)return;const R=J.find(ae=>ae.providerSessionId===$);R!=null&&R.canResume||H("")},[J,$]);const Le=o.useCallback((R,ae)=>{_e.current=ae,Xe.current=R.selectedWorkspaceKey||"__home__",mt(R.selectedWorkspaceKey||"__home__"),He(R)},[]),Se=o.useCallback(()=>{_e.current&&(xt(!0),_e.current().finally(()=>{_e.current=null,xt(!1),He(null)}))},[]),Pe=o.useCallback(R=>{if(!R)return;V(fe=>fe.includes(R)?fe:[...fe,R]);const ae=Je.current[R];ae&&clearTimeout(ae),Je.current[R]=setTimeout(()=>{V(fe=>fe.includes(R)?fe.filter(Ke=>Ke!==R):fe),delete Je.current[R]},2e4)},[]);o.useEffect(()=>{for(const ae of a)bt(ae.status)!=="stopped"&&(q.includes(ae.type)&&!O.current.has(ae.type)&&(O.current.add(ae.type),k("info",`${_.get(ae.type)||ae.type} launched`,!0)),rt(ae.type));const R=new Set(a.filter(ae=>bt(ae.status)!=="stopped").map(ae=>ae.type));O.current.forEach(ae=>{!q.includes(ae)&&!R.has(ae)&&O.current.delete(ae)})},[k,rt,a,q,_]),o.useEffect(()=>()=>{Object.values(Je.current).forEach(clearTimeout),Je.current={}},[]);const[Ee,Ae]=o.useState({}),[qe,et]=o.useState(null);o.useEffect(()=>{if(!w||!r||!l)return;(async()=>{try{const ae=await l(r,"get_ide_extensions",{}),fe=(ae==null?void 0:ae.result)||ae;fe!=null&&fe.success&&(fe!=null&&fe.ideExtensions)&&Ae(fe.ideExtensions)}catch{}})()},[w,r,l]);const ct=R=>w?it(R.type):e==="cli"?R.cliName:R.acpName,ft=w?t.detectedIdes||[]:[],dt=o.useCallback(async R=>{const ae=(R==null?void 0:R.type)||T,fe=(R==null?void 0:R.workspacePath)??Ge;if(w){await x(ae,fe?{workspace:fe}:void 0)&&Pe(ae);return}const Ke=await c.runLaunchCliCore({cliType:ae,dir:R!=null&&R.workspaceId?void 0:fe||void 0,workspaceId:(R==null?void 0:R.workspaceId)||void 0,useHome:(R==null?void 0:R.useHome)||!(R!=null&&R.workspaceId)&&!fe,argsStr:(R==null?void 0:R.argsStr)??(K||void 0),model:(R==null?void 0:R.model)??(v&&F||void 0),resumeSessionId:(R==null?void 0:R.resumeSessionId)||!v&&e==="cli"&&ae===T&&$||void 0});if(Ke.success||Ke.pending){const Re=(R==null?void 0:R.argsStr)??K;!w&&(Re!=null&&Re.trim())&&(Vl(r,ae,Re),re(ae)),Pe(ae),Ke.success&&Ke.sessionId&&A(Ke.sessionId)}},[c,x,v,w,K,F,re,Pe,r,A,Ge,$,T]),yt=Yc(w?"ide":v?"acp":"cli",!w&&!v&&!!$),Ve=Xc(w?"ide":v?"acp":"cli",!w&&!v&&!!$),xe=()=>{var Re;const R=w?it(T):_.get(T)||T,ae=!w&&!v&&!!$,{options:fe,selectedKey:Ke}=ds({machine:t,currentWorkspaceId:pe&&pe!=="__custom__"?pe:null,currentWorkspacePath:Ge});Le({title:ae?ao(R):as("start-fresh",R),description:ae?oo():os("start-fresh"),confirmLabel:yt,busyLabel:Ve,workspaceOptions:fe,selectedWorkspaceKey:Ke,details:[{label:"Mode",value:M.label},{label:"Provider",value:R},...!w&&e==="cli"&&$?[{label:"Resume",value:((Re=J.find(We=>We.providerSessionId===$))==null?void 0:Re.title)||$}]:[],...!w&&K.trim()?[{label:"Arguments",value:K.trim()}]:[],...v&&F.trim()?[{label:"Model",value:F.trim()}]:[]]},async()=>{const We=fe.find(ot=>ot.key===Xe.current);We!=null&&We.workspaceId?(ee(We.workspaceId),oe("")):We!=null&&We.workspacePath?(ee("__custom__"),oe(We.workspacePath)):(ee(""),oe("")),await dt({workspaceId:(We==null?void 0:We.workspaceId)??null,workspacePath:(We==null?void 0:We.workspacePath)??"",useHome:!(We!=null&&We.workspaceId)&&!(We!=null&&We.workspacePath)})})},z=R=>{w?p(R):C(R.type,R.workspace,R.id)},Me=o.useCallback(async(R,ae,fe=!1)=>{if(R.mode===ae){fe&&R.sessionId&&A(R.sessionId);return}if(!l||!R.sessionId){fe&&R.sessionId&&A(R.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:R.sessionId,cliType:R.type,mode:ae}),fe&&A(R.sessionId)}catch(Ke){const Re=pl(Ke);fl(Ke)?console.warn(Re?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ke instanceof Error?Ke.message:String(Ke)):console.error("Failed to switch CLI view mode:",Ke)}},[r,A,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${M.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",M.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:w?ft.length>0?ft.map(R=>{const ae=a.find(ot=>(ot.type||"").toLowerCase()===(R.type||"").toLowerCase()&&bt(ot.status)!=="stopped"),fe=R.running||!!ae,Ke=!!ae&&ae.cdpConnected,Re=q.includes(R.type||R.id||""),We=T===(R.type||"");return s.jsxs("button",{onClick:()=>{if(Ke&&ae){const ot=ae.sessionId;ot?f(Jt(ot),{state:{openRemoteForTabKey:ot}}):f("/dashboard",{state:{openRemoteForTabKey:ae.id}});return}Re||D(ot=>ot===(R.type||"")?"":R.type||"")},disabled:!!b||Re,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ke?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":We?"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:b&&b!==R.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(R.type)}),fe&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ke?"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:R.name||it(R.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ke?"text-green-400":Re?"text-orange-400":We?"text-accent-primary":"text-text-muted"}`,children:Ke?"Open Session":Re?"Starting...":We?"Configure":"Select"})]})]},R.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(lu,{size:14})," Scan System"]})]}):B.length>0?B.map(R=>{const ae=T===R.type,fe=q.includes(R.type),Re=!!a.find(We=>We.type===R.type&&bt(We.status)!=="stopped");return s.jsxs("button",{onClick:()=>D(We=>We===R.type?"":R.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ae?"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:R.icon}),Re&&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:R.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${fe?"text-orange-400":ae?"text-accent-primary":"text-text-muted"}`,children:fe?"Starting...":ae?"Configure":"Select"})]})]},R.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&&(w?ft.find(R=>R.type===T):B.find(R=>R.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:w?it(T):_.get(T)||T})]}),s.jsx(uy,{machine:t,selectedWorkspace:pe,resolvedWorkspacePath:Ge,customPath:ue,canBrowse:!!l,onWorkspaceChange:ee,onCustomPathChange:oe,onOpenBrowseDialog:G}),!w&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&s.jsx(ql,{busy:!!h||!!b||q.includes(T),savedSessionsLoading:ie,savedSessionsError:ge,savedSessionsLoaded:be,savedSessionsCount:J.length,selectedSession:Ie,onRefresh:()=>void Y(T),onOpenHistory:()=>{T&&(ye(!0),Gl({hasLoadedInitialResults:be,isLoading:ie})&&Y(T))},onClearSelection:()=>H("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value:F,onChange:R=>P(R.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:K,onChange:R=>L(R.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"}),N.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:N.map(R=>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:R,children:[s.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>L(R),children:R}),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:()=>ve(T,R),"aria-label":`Remove startup arguments: ${R}`,title:"Remove startup arguments",children:s.jsx(vt,{size:12})})]},R))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:xe,disabled:!!h||!!b||q.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:h===T||b===T?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+q.filter(R=>!a.some(ae=>ae.type===R&&bt(ae.status)!=="stopped")).length,")"]}),a.length===0&&ze.length===0?s.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",M.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[ze.map(R=>s.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(R)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:w?it(R):_.get(R)||R}),s.jsx("div",{className:"text-[11px] text-text-muted",children:h===R?"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:${R}`)),a.map(R=>{const ae=w?R:null,fe=!w&&!v?R:null,Ke=bt(R.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(R.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[ct(R),(ae==null?void 0:ae.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ae.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:R.workspace||"—"}),u&&R.git&&R.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:Re=>{Re.stopPropagation(),u(R.daemonId??r,R.workspace)},children:s.jsx(_s,{git:R.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(_s,{git:R.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(fe==null?void 0:fe.mode)&&s.jsx("span",{className:fe.mode==="chat"?"text-violet-400":"text-text-secondary",children:fe.mode==="chat"?"Chat view":"Terminal view"})]}),fe&&(fe.runtimeKey||fe.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[fe.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 ",fe.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 Re;(Re=navigator.clipboard)==null||Re.writeText(`adhdev attach ${fe.runtimeKey}`),j(fe.runtimeKey||null),window.setTimeout(()=>{j(We=>We===fe.runtimeKey?null:We)},1200)},children:S===fe.runtimeKey?"Copied":"Copy"})]}),fe.runtimeWriteOwner&&s.jsx("span",{style:{color:fe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:fe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:dy(fe.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 ${Ke==="stopped"?"bg-red-500/[0.08] text-red-500":Ke==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ke}),w&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Re=R.sessionId;if(Re){f(Jt(Re),{state:{openRemoteForTabKey:Re}});return}f("/dashboard",{state:{openRemoteForTabKey:R.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(Mt,{size:13})}),s.jsx("button",{onClick:()=>{const Re=R.workspace||"",{options:We,selectedKey:ot}=ds({machine:t,currentWorkspacePath:Re});Le({title:as("restart-ide",it(R.type)),description:os("restart-ide"),confirmLabel:Ps("restart-ide"),busyLabel:Ds("restart-ide"),workspaceOptions:We,selectedWorkspaceKey:ot,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:it(R.type)}]},async()=>{const Nt=We.find(Vt=>Vt.key===Xe.current),pt=(Nt==null?void 0:Nt.workspacePath)??"";if(pt&&pt!==Re){await dt({type:R.type,workspacePath:pt});return}await y(R)})},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(dr,{size:14})})]}),v&&s.jsx("button",{onClick:()=>{const Re=R.sessionId;Re&&A(Re)},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:!R.sessionId,children:s.jsx(Ut,{size:14})}),fe&&Ke!=="stopped"&&s.jsxs(s.Fragment,{children:[fe.mode&&s.jsx(so,{mode:fe.mode,onChange:Re=>void Me(fe,Re,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Re=R.sessionId;Re&&A(Re)},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:!R.sessionId,children:fe.mode==="chat"?s.jsx(Ut,{size:14}):s.jsx(Mt,{size:13})})]}),Ke==="stopped"?s.jsx("button",{onClick:()=>{const Re=R.workspace||"",We=w?it(R.type):ct(R),{options:ot,selectedKey:Nt}=ds({machine:t,currentWorkspacePath:Re});Le({title:as("restart-stopped",We),description:os("restart-stopped"),confirmLabel:Ps("restart-stopped"),busyLabel:Ds("restart-stopped"),workspaceOptions:ot,selectedWorkspaceKey:Nt,details:[{label:"Mode",value:M.label},{label:"Provider",value:We}]},async()=>{const pt=ot.find(Vt=>Vt.key===Xe.current);await dt({type:R.type,workspaceId:(pt==null?void 0:pt.workspaceId)??null,workspacePath:(pt==null?void 0:pt.workspacePath)??"",useHome:!(pt!=null&&pt.workspaceId)&&!(pt!=null&&pt.workspacePath)})})},disabled:q.includes(R.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:q.includes(R.type)?"⏳":s.jsx(Ha,{size:14})}):s.jsx("button",{onClick:()=>z(R),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:s.jsx(vt,{size:14})})]})]}),ae&&ae.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ae.aiAgents.map(Re=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Zr(Re.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Re.name," · ",bt(Re.status)]},Re.id))}),ae&&(Ee[ae.type]||[]).length>0&&l&&s.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[s.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(Ee[ae.type]||[]).map(Re=>s.jsxs("button",{disabled:qe===`${ae.type}.${Re.type}`,onClick:async()=>{const We=`${ae.type}.${Re.type}`;et(We);try{await l(r,"set_ide_extension",{ideType:ae.type,extensionType:Re.type,enabled:!Re.enabled}),Ae(ot=>({...ot,[ae.type]:(ot[ae.type]||[]).map(Nt=>Nt.type===Re.type?{...Nt,enabled:!Nt.enabled}:Nt)}))}catch(ot){console.error("Extension toggle failed:",ot)}finally{et(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 ${Re.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 ${Re.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Re.name,s.jsx("span",{className:"text-[9px] font-normal",children:Re.enabled?"ON":"OFF"})]},Re.type))})]})]},R.id)})]}),le&&l&&s.jsx(wn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:Z,directories:$e,busy:Ue,error:Ce,confirmLabel:"Use this folder",onClose:()=>ke(!1),onNavigate:R=>{U(R)},onConfirm:R=>{oe(R),ee("__custom__"),ke(!1)}}),Be&&s.jsx(yo,{title:Be.title,description:Be.description,details:Be.details,workspaceOptions:Be.workspaceOptions,selectedWorkspaceKey:st,onWorkspaceChange:R=>{Xe.current=R,mt(R)},confirmLabel:Be.confirmLabel,busyLabel:Be.busyLabel,busy:ht,onConfirm:Se,onCancel:()=>{_e.current=null,He(null)}}),ce&&Q&&s.jsx(io,{activeConv:Q,ides:[],isCreatingChat:!1,isRefreshingHistory:ie,savedSessions:J,isSavedSessionsLoading:ie,isResumingSavedSessionId:je,savedHistoryFilters:ne,missingWorkspaceResumePath:Ge||null,onSavedHistoryFiltersChange:de,onClose:()=>ye(!1),onNewChat:()=>{H(""),ye(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Y(T)},onResumeSavedSession:R=>{if(!R.canResume||je)return;const ae=E(R);H(R.providerSessionId),se(R),me(R.providerSessionId),ye(!1),dt({type:R.providerType,workspaceId:ae.workspaceId,workspacePath:ae.workspacePath,useHome:ae.useHome,resumeSessionId:R.providerSessionId}).finally(()=>{me(fe=>fe===R.providerSessionId?null:fe)})}})]})}const Hi=[{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 fy({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:f,onOpenGitDialog:x}){var g;const[C,y]=o.useState(d);o.useEffect(()=>{y(d)},[d]);const p=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Hi.map(b=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${C===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>y(b.id),children:[s.jsx("span",{children:b.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${C===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:p[b.id]})]},b.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(g=Hi.find(b=>b.id===C))==null?void 0:g.helper})]}),C==="ide"&&s.jsx(la,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),C==="cli"&&s.jsx(la,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),C==="acp"&&s.jsx(la,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x})]})}function py({onNicknameSynced:e}={}){var oe,q,V,le,ke,Z,De,$e,Fe,Ue;const{id:t}=Ld(),r=$s(),n=$a(),{sendCommand:a}=gt(),i=fr(),c=ll(),l=Oc(),d=l.ides||[],m=l.initialLoaded??!0,u=d.find(W=>W.id===t&&W.type==="adhdev-daemon"),f=d.some(W=>W.type==="adhdev-daemon"),x=t?(oe=l.connectionRetryStatuses)==null?void 0:oe[t]:void 0,C=!!(x!=null&&x.blocked),[y,p]=o.useState("workspace"),[g,b]=o.useState(null),h=o.useCallback((W,Ce)=>{b({daemonId:W,workspace:Ce})},[]),[k,S]=o.useState("ide"),j=o.useRef(null),[A,M]=o.useState(null),w=o.useRef("__home__"),[v,B]=o.useState("__home__"),[_,T]=o.useState(!1),D=o.useRef(null);o.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||i(t,{minFreshMs:3e4}).catch(()=>{})},[i,u,t]),o.useEffect(()=>{if(!t||!u||y!=="overview")return;const W=u.machine;(typeof(W==null?void 0:W.cpus)!="number"||typeof(W==null?void 0:W.totalMem)!="number"||typeof(W==null?void 0:W.arch)!="string"||typeof(W==null?void 0:W.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[y,c,u,t]),bh(t&&y==="overview"?[t]:[],{enabled:y==="overview",intervalMs:hf});const K=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},L=lg({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:D});o.useEffect(()=>at.onToast(Ce=>{l.setToasts(_e=>{if(_e.some(Xe=>Xe.message===Ce.message&&Ce.timestamp-Xe.timestamp<3e3))return _e;const He={id:Ce.id,message:Ce.message,type:Ce.type,timestamp:Ce.timestamp,targetKey:Ce.targetKey,actions:Ce.actions};return[..._e.slice(-4),He]});const Te=Ce.duration||5e3;setTimeout(()=>l.setToasts(_e=>_e.filter(Be=>Be.id!==Ce.id)),Te)}),[l]);const N=(u==null?void 0:u.availableProviders)||[],I={};for(const W of N)I[W.type]=W.icon;const F=W=>I[W]||"",P=u?{id:u.id,hostname:xc(u,{fallbackId:u.id}),platform:((q=u.machine)==null?void 0:q.platform)||"unknown",arch:((V=u.machine)==null?void 0:V.arch)||"",cpus:((le=u.machine)==null?void 0:le.cpus)||0,totalMem:((ke=u.machine)==null?void 0:ke.totalMem)||0,freeMem:(Z=u.machine)==null?void 0:Z.freeMem,availableMem:(De=u.machine)==null?void 0:De.availableMem,loadavg:($e=u.machine)==null?void 0:$e.loadavg,uptime:(Fe=u.machine)==null?void 0:Fe.uptime,release:((Ue=u.machine)==null?void 0:Ue.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,$=d.filter(W=>W.daemonId===t&&W.type!=="adhdev-daemon").filter(W=>!cr(W)&&!Ns(W)).map(W=>({id:W.id,sessionId:W.sessionId,type:W.type,version:W.version||"",instanceId:W.instanceId||"",status:W.status,workspace:W.workspace||null,terminals:W.terminals||0,aiAgents:mm(W.aiAgents||(W.agents||[]).map(Ce=>({id:Ce.name,name:Ce.name,status:Ce.status,version:Ce.version}))),activeChat:W.activeChat||null,chats:W.chats||[],childSessions:W.childSessions||[],cdpConnected:W.cdpConnected||!1,daemonId:t})),H=d.filter(W=>W.daemonId===t&&cr(W)).map(W=>({id:W.id,sessionId:W.sessionId,type:W.type,cliName:W.cliName||W.type,status:W.status,workspace:W.workspace||"",activeChat:W.activeChat||null,providerSessionId:W.providerSessionId,mode:W.mode,runtimeKey:W.runtimeKey,runtimeDisplayName:W.runtimeDisplayName,runtimeWorkspaceLabel:W.runtimeWorkspaceLabel,runtimeWriteOwner:W.runtimeWriteOwner||null,runtimeAttachedClients:W.runtimeAttachedClients||[],daemonId:t})),J=d.filter(W=>W.daemonId===t&&Ns(W)).map(W=>({id:W.id,sessionId:W.sessionId,type:W.type,acpName:W.cliName||W.type,status:W.status,workspace:W.workspace||"",activeChat:W.activeChat||null,providerSessionId:W.providerSessionId,daemonId:t})),he=u?Tt(u,{fallbackId:t}):"",ie="workspace",te=n.state,be=te==null?void 0:te.initialMachineTab,we=te==null?void 0:te.initialWorkspaceCategory,ge=te==null?void 0:te.initialWorkspaceId,X=te==null?void 0:te.initialWorkspacePath,ce=be==="ides"||be==="clis"||be==="acps"?"workspace":be||ie,ye=be==="ides"?"ide":be==="clis"?"cli":be==="acps"?"acp":we,ne=[...$.map(W=>{var Ce,Te,_e,Be,He;return{id:`ide:${W.type}:${W.workspace||""}`,label:((Ce=W.activeChat)==null?void 0:Ce.title)||W.type,kind:"ide",providerType:W.type,subtitle:W.workspace||void 0,workspace:W.workspace||void 0,lastLaunchedAt:((He=(Be=(_e=(Te=W.activeChat)==null?void 0:Te.messages)==null?void 0:_e.at)==null?void 0:Be.call(_e,-1))==null?void 0:He.timestamp)||0}}),...H.map(W=>{var Ce,Te,_e,Be,He;return{id:`cli:${W.type}:${W.workspace||""}`,label:((Ce=W.activeChat)==null?void 0:Ce.title)||W.cliName,kind:"cli",providerType:W.type,providerSessionId:W.providerSessionId,subtitle:W.workspace||void 0,workspace:W.workspace||void 0,lastLaunchedAt:((He=(Be=(_e=(Te=W.activeChat)==null?void 0:Te.messages)==null?void 0:_e.at)==null?void 0:Be.call(_e,-1))==null?void 0:He.timestamp)||0}}),...J.map(W=>{var Ce,Te,_e,Be,He;return{id:`acp:${W.type}:${W.workspace||""}`,label:((Ce=W.activeChat)==null?void 0:Ce.title)||W.acpName,kind:"acp",providerType:W.type,providerSessionId:W.providerSessionId,subtitle:fs(W.summaryMetadata)||W.workspace||void 0,workspace:W.workspace||void 0,lastLaunchedAt:((He=(Be=(_e=(Te=W.activeChat)==null?void 0:Te.messages)==null?void 0:_e.at)==null?void 0:Be.call(_e,-1))==null?void 0:He.timestamp)||0}})].sort((W,Ce)=>(Ce.lastLaunchedAt||0)-(W.lastLaunchedAt||0)),de=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(W=>({id:W.id,label:W.title||W.providerName||W.providerType,kind:W.kind,providerType:W.providerType,providerSessionId:W.providerSessionId,subtitle:fs(W.summaryMetadata)||W.workspace||void 0,workspace:W.workspace,summaryMetadata:W.summaryMetadata,lastLaunchedAt:W.lastLaunchedAt})):ne,je=o.useMemo(()=>{var Ce;const W=((Ce=l.connectionStates)==null?void 0:Ce[t||""])||void 0;return d.filter(Te=>Te.daemonId===t&&Te.type!=="adhdev-daemon").flatMap(Te=>co(Te,{connectionStates:t&&W?{[t]:W}:void 0,defaultConnectionState:W})).filter(Te=>!(Te.transport==="pty"&&Te.mode==="terminal")).sort((Te,_e)=>Aa(_e)-Aa(Te))},[d,l.connectionStates,t]),me=o.useCallback(W=>{const Ce=bo(W);Ce&&r(Jt(Ce))},[r]),pe=o.useCallback(()=>{j.current&&(T(!0),j.current().finally(()=>{j.current=null,T(!1),M(null)}))},[]),ee=o.useCallback(W=>{if(!P)return;const{options:Ce,selectedKey:Te}=ds({machine:P,currentWorkspacePath:W.workspace}),_e=async()=>{S(W.kind),p("workspace")};j.current=async()=>{const Be=Ce.find(st=>st.key===w.current),He=(Be==null?void 0:Be.workspacePath)??null,Xe=(Be==null?void 0:Be.workspaceId)??null;if(W.kind==="ide"&&W.providerType){await L.handleLaunchIde(W.providerType,He?{workspace:He}:void 0);return}if((W.kind==="cli"||W.kind==="acp")&&W.providerType){await L.runLaunchCliCore({cliType:W.providerType,dir:Xe?void 0:He||"",workspaceId:Xe||void 0,model:W.kind==="acp"&&gc(W.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:W.providerSessionId});return}await _e()},w.current=Te,B(Te),M({title:W.kind==="ide"?as("restart-ide",W.label):W.providerSessionId?ao(W.label):as("start-fresh",W.label),description:W.kind==="ide"?os("restart-ide"):W.providerSessionId?oo():os("start-fresh"),confirmLabel:W.kind==="ide"?Ps("restart-ide"):W.providerSessionId?nn(!0):Ps("start-fresh"),busyLabel:W.kind==="ide"?Ds("restart-ide"):W.providerSessionId?ro(!0):Ds("start-fresh"),workspaceOptions:Ce,details:[{label:"Mode",value:W.kind.toUpperCase()},...W.providerType?[{label:"Provider",value:W.providerType}]:[]]})},[L,P]);if(o.useEffect(()=>{p(ce)},[ie,ce,t]),o.useEffect(()=>{ye&&S(ye)},[ye,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:K,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 ue=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Mt,{size:14})," Workspace"]}),count:$.length+H.length+J.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Yt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(un,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(du,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(iu,{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:K,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:[L.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:L.nicknameInput,onChange:W=>L.setNicknameInput(W.target.value),onKeyDown:W=>{W.key==="Enter"&&L.handleSaveNickname(),W.key==="Escape"&&L.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:L.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:()=>L.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:()=>{L.setEditingNickname(!0),L.setNicknameInput(P.machineNickname||"")},title:"Click to set nickname",children:he}),C?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:ue.map(W=>s.jsxs("button",{onClick:()=>p(W.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${y===W.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[W.label,W.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${y===W.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:W.count})]},W.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:[y==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(ly,{machineEntry:u,providers:N,recentLaunches:de,currentConversations:je,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Sl(u))}catch{}},onOpenRecent:ee,onOpenConversation:me}),s.jsx(fy,{machine:P,machineId:t,providers:N,ideSessions:$,cliSessions:H,acpSessions:J,actions:L,getIcon:F,initialCategory:k,initialWorkspaceId:ge,initialWorkspacePath:X,sendDaemonCommand:a,onOpenGitDialog:h})]}),y==="providers"&&s.jsx(yg,{machineId:t,providers:N,sendDaemonCommand:a}),y==="overview"&&s.jsx(dg,{machineId:t,machine:P,ideSessions:$,cliSessions:H,acpSessions:J,actions:L,sendDaemonCommand:a}),y==="session-host"&&s.jsx(iy,{machineId:t,cliSessions:H,sendDaemonCommand:a}),y==="logs"&&s.jsx(ey,{machineId:t,sendDaemonCommand:a})]})})}),L.launchPick&&P&&s.jsx(cy,{machine:P,launchPick:L.launchPick,actions:L}),A&&s.jsx(yo,{title:A.title,description:A.description,details:A.details,workspaceOptions:A.workspaceOptions,selectedWorkspaceKey:v,onWorkspaceChange:W=>{w.current=W,B(W)},confirmLabel:A.confirmLabel,busyLabel:A.busyLabel,busy:_,onConfirm:pe,onCancel:()=>{j.current=null,M(null)}}),g&&s.jsx(Jl,{daemonId:g.daemonId,workspace:g.workspace,onClose:()=>b(null)}),s.jsx(Jc,{toasts:l.toasts||[],onDismiss:W=>l.setToasts(Ce=>Ce.filter(Te=>Te.id!==W)),onClickToast:W=>{W.targetKey&&r(Jt(W.targetKey))}}),s.jsx("style",{children:`
90
90
  @keyframes toast-in {
91
91
  from { opacity: 0; transform: translateX(40px); }
92
92
  to { opacity: 1; transform: translateX(0); }
93
93
  }
94
- `})]})}function fy({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const i=a.id.toLowerCase(),c=a.name.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||c.includes("hermes")}),n=Nl(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(kt,{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(ql,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function py(){const{sendCommand:e}=bt(),{ides:t}=Qt(),r=t.find(D=>D.daemonMode||D.type==="adhdev-daemon"),n=(r==null?void 0:r.id)||"",a=[];if(r){const D=r.availableProviders||[];for(const K of D)K.category==="cli"&&a.push({id:K.type||K.id,name:K.displayName||K.name||K.type,meshCoordinator:K.meshCoordinator})}const[i,c]=o.useState([]),[l,d]=o.useState(null),[m,u]=o.useState(!0),[f,x]=o.useState(null),[C,g]=o.useState(!1),[p,j]=o.useState(""),[b,h]=o.useState(""),[y,S]=o.useState(!1),[k,A]=o.useState(""),M=i.find(D=>D.id===l)||null,w=o.useCallback(async()=>{if(n){u(!0);try{const D=await e(n,"list_meshes");D!=null&&D.success?(c(D.meshes||[]),x(null)):x((D==null?void 0:D.error)||"Failed to load meshes")}catch(D){x((D==null?void 0:D.message)||"Failed to load meshes")}finally{u(!1)}}},[n,e]);o.useEffect(()=>{w()},[w]);async function v(){var D;if(!(!n||!p.trim()))try{const K=await e(n,"create_mesh",{name:p.trim(),repoIdentity:b.trim()||void 0});K!=null&&K.success?(g(!1),j(""),h(""),await w(),d(((D=K.mesh)==null?void 0:D.id)||null)):x((K==null?void 0:K.error)||"Create failed")}catch(K){x((K==null?void 0:K.message)||"Create failed")}}async function B(D){if(!(!n||!confirm("Delete this mesh?")))try{await e(n,"delete_mesh",{meshId:D}),d(null),await w()}catch(K){x((K==null?void 0:K.message)||"Delete failed")}}async function _(){if(!(!n||!l||!k.trim()))try{const D=await e(n,"add_mesh_node",{meshId:l,workspace:k.trim()});D!=null&&D.success?(S(!1),A(""),await w()):x((D==null?void 0:D.error)||"Add node failed")}catch(D){x((D==null?void 0:D.message)||"Add node failed")}}async function T(D){if(!(!n||!l))try{await e(n,"remove_mesh_node",{meshId:l,nodeId:D}),await w()}catch(K){x((K==null?void 0:K.message)||"Remove node failed")}}return n?M?s.jsxs(tr,{icon:s.jsx(wr,{}),title:M.name,subtitle:M.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>d(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>B(M.id),children:"Delete"})]}),children:[f&&s.jsx(Ss,{variant:"error",className:"mb-4",children:f}),s.jsxs(kt,{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:()=>S(!0),children:"+ Add Node"})}),y&&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:()=>S(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(yt,{size:16})})]}),s.jsx(Dn,{label:"Workspace Path",children:s.jsx(En,{value:k,onChange:D=>A(D.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:D=>{D.key==="Enter"&&_()},autoFocus:!0})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:_,disabled:!k.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>S(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),M.nodes.length===0?s.jsx(nn,{icon:s.jsx(ms,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:M.nodes.map(D=>s.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium",children:D.workspace.split("/").pop()}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:D.workspace})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:()=>T(D.id),children:s.jsx(yt,{size:14})})]},D.id))})]}),s.jsx(fy,{meshId:M.id,availableCliAgents:a})]}):s.jsxs(tr,{icon:s.jsx(wr,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>g(!0),children:"+ Create Mesh"}),children:[f&&s.jsx(Ss,{variant:"error",className:"mb-4",children:f}),C&&s.jsx(kt,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Dn,{label:"Name",children:s.jsx(En,{value:p,onChange:D=>j(D.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Dn,{label:"Repo Identity (optional)",children:s.jsx(En,{value:b,onChange:D=>h(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:v,disabled:!p.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(!1),children:"Cancel"})]})]})}),m?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):i.length===0?s.jsx(nn,{icon:s.jsx(wr,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:i.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:()=>d(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))})]}):s.jsx(tr,{icon:s.jsx(wr,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function No(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function hy(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=No();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Et(e,t){return await fetch(hy(e),{credentials:"same-origin",...t})}function Zl(){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 xy{constructor(){Qe(this,"adapters",new Map);Qe(this,"states",new Map);Qe(this,"runtimeListeners",new Map);Qe(this,"screenshotCallbacks",new Map);Qe(this,"statusCallbacks",new Set)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r)}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,i,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:i,rows:c})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const i=await Et(`${a.pathname}${a.search}`);if(!i.ok){let l=`Runtime snapshot unavailable (${i.status})`;try{const d=await i.json();d!=null&&d.error&&(l=d.error)}catch{}return{success:!1,error:l}}const c=await i.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof c.seq=="number"?c.seq:0,text:typeof c.text=="string"?c.text:"",truncated:!!c.truncated,cols:typeof c.cols=="number"?c.cols:void 0,rows:typeof c.rows=="number"?c.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Wt=new xy;function by(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=No();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Br=by(),Fi=3e3,gy=3e4;let _t=null,yy=0;const ln=new Map;let es=null,nr=null;function Hi(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function qs(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function vy(e){return e==="connected"?"connected":e}async function Gr(e,t,r){const n=Zc(e,r||{}),a=_t;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++yy}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{ln.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);ln.set(i,{resolve:m=>{clearTimeout(d),c(m)},reject:m=>{clearTimeout(d),l(m)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function _a(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 wy(e,t,r){const n=_t;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Zc(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 jy{constructor(t){Qe(this,"daemonId");Qe(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 Gr(this.daemonId,t,r)}async sendInput(t,r){return Gr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,es&&(clearInterval(es),es=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Gr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Wt.emitScreenshot(this.daemonId,a)}}catch{}};r(),es=setInterval(r,2e3)}stopScreenshots(t){es&&(clearInterval(es),es=null)}}let It=null;function ky(e){return(!It||It.daemonId!==e)&&(It=new jy(e)),It}function Sy({children:e}){const t=o.useRef(or()),r=or();t.current=r;const{setUserName:n}=Qt(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),d=o.useCallback((p,j)=>{l(p),nr==null||nr(p,j)},[]),m=o.useRef(null),u=o.useRef(),f=o.useRef(Fi),x=o.useRef(!0),C=o.useRef(!1),g=o.useRef("initial_connect");return o.useEffect(()=>{x.current=!0,C.current=!1;function p(){var h,y;if(!x.current||((h=m.current)==null?void 0:h.readyState)===WebSocket.OPEN||((y=m.current)==null?void 0:y.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Br}...`),qs("connect_attempt",{url:Br,reason:g.current,delayMs:f.current});let b;try{b=new WebSocket(Br)}catch(S){console.error("[Standalone WS] Failed to create WebSocket:",S),j();return}m.current=b,b.onopen=()=>{if(!x.current){b.close();return}d("connected"),f.current=Fi,qs("open",{url:Br,reason:g.current}),Ht.resubscribeAll({sendData:_a}),console.log("[Standalone WS] Connected")},_t=b,b.onmessage=S=>{var k,A;try{const M=JSON.parse(S.data);if((M.type==="command_result"||M.type==="error")&&M.requestId){const w=ln.get(M.requestId);w&&(ln.delete(M.requestId),M.type==="error"?w.reject(new Error(((k=M.data)==null?void 0:k.message)||"Command failed")):w.resolve(M.data));return}if(M.type==="session_output"){const w=M.sessionId||M.cliId||M.cliType;w&&Wt.emitSessionOutput(w,typeof M.data=="string"?M.data:"",typeof M.seq=="number"?M.seq:void 0);return}if(M.type==="runtime_snapshot"){Wt.emitRuntimeSnapshot(M.sessionId,typeof M.text=="string"?M.text:"",typeof M.seq=="number"?M.seq:0,!!M.truncated,typeof M.cols=="number"?M.cols:void 0,typeof M.rows=="number"?M.rows:void 0);return}if(M.type==="topic_update"){const w=M.update;w&&Ht.publish(w);return}if(M.type==="status"||M.type==="initial_state"){const w=M.data;if(!w)return;const{injectEntries:v,markLoaded:B,getIdes:_}=t.current,T=w.instanceId||"standalone",D=_().find(N=>N.id===T),K=ky(T);Wt.register(T,K),Wt.setState(T,"connected"),d("connected",T),Wt.emitStatus(T,w);const L=sn(w,{daemonId:T,existingDaemon:D,existingEntries:_()});Hi("ws_status",{type:M.type,daemonId:T,sessions:(w.sessions||[]).map(N=>({id:N.id,parentId:N.parentId,providerType:N.providerType,kind:N.kind,transport:N.transport,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,title:N.title})),recentLaunches:(w.recentLaunches||[]).map(N=>({id:N.id,providerType:N.providerType,kind:N.kind,workspace:N.workspace,lastLaunchedAt:N.lastLaunchedAt}))}),Hi("entries",{daemonId:T,entries:L.filter(N=>N.type!=="adhdev-daemon").map(N=>({id:N.id,type:N.type,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,sessionId:N.sessionId}))}),L.length>0&&v(L,{authoritativeDaemonIds:[T]}),B(),c.current!==T&&((A=i.current)==null||A.call(i),c.current=T,i.current=Ht.subscribe({sendData:_a},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},N=>{if(N.topic!=="daemon.metadata")return;const I=t.current.getIdes(),W=I.find($=>$.id===T),P=sn(N.status,{daemonId:T,existingDaemon:W,existingEntries:I,timestamp:N.timestamp});P.length>0&&t.current.injectEntries(P,{authoritativeDaemonIds:[T]}),N.userName&&a.current&&a.current(N.userName)}))}}catch(M){console.error("[Standalone WS] Parse error:",M)}},b.onclose=S=>{x.current&&(It==null||It.stopScreenshots(),It&&Wt.setState(It.daemonId,"disconnected"),d("disconnected"),m.current=null,g.current=`close:${S.code}${S.wasClean?":clean":":unclean"}`,qs("close",{code:S.code,reason:S.reason||"",wasClean:S.wasClean}),j())},b.onerror=S=>{C.current||!x.current||(g.current="error",qs("error",{message:S instanceof Event?"event":String(S),readyState:b.readyState}),console.warn("[Standalone WS] Error, will reconnect:",S))}}function j(){if(!x.current)return;clearTimeout(u.current);const b=f.current;console.log(`[Standalone WS] Reconnecting in ${b}ms...`),qs("schedule_reconnect",{reason:g.current,delayMs:b}),u.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,gy),p()},b)}return p(),()=>{var b;x.current=!1,C.current=!0,(b=i.current)==null||b.call(i),i.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),It&&(It.stopScreenshots(),Wt.unregister(It.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function Ny({children:e}){const[t,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(nr=(c,l)=>{r(c),l&&a(l)},()=>{nr=null}),[]);const i=o.useMemo(()=>{const c=t==="connected",l=vy(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(Yd,{connectionOverrides:i,children:s.jsx(Sy,{children:e})})}const ed="adhdev_standalone_font_preferences",us={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"}],lr=[{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"}],Cy=new Set(kn.map(e=>e.id)),Ty=new Set(lr.map(e=>e.id));function Bt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:qr("chat",t.chat),code:qr("code",t.code),terminal:qr("terminal",t.terminal)}}function qr(e,t){const r=us[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?Cy:Ty).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Yr(e,t){var a;const r=qr(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?kn:lr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function My(e){const t=Bt(e),r=Yr("chat",t.chat),n=Yr("code",t.code),a=Yr("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function ss(e,t=document.documentElement){const r=Bt(e),n=My(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function Pa(e){const t=Bt(e);try{localStorage.setItem(ed,JSON.stringify(t))}catch{}return t}function Ay(){try{const e=localStorage.getItem(ed);if(e)return Bt(JSON.parse(e))}catch{}return us}function Iy(){return ss(Ay())}function Ys(e,t){var n;const r=e==="chat"?kn:lr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Ry=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Zi,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(Yt,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Is,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(dn,{}),label:"Settings"}];function Ly({children:e}){const t=$s(),r=Ea(),n=o.useMemo(()=>Ry.map(i=>({...i,active:r.pathname.startsWith(i.path),onSelect:()=>t(i.path)})),[r.pathname,t]),a=o.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(tc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(sc,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Op,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.75"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:i?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const _y=[{icon:s.jsx(Yt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ut,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(rc,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Mt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Is,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(tc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Py=[{icon:s.jsx(uu,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Zi,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(un,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(au,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(ec,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(iu,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Dy=[{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 Ey(){return s.jsxs(tr,{icon:s.jsx(sc,{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.75"]}),children:[s.jsx(kt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),s.jsx(kt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:_y.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(kt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:el.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:sl.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:tl.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(kt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Py.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(kt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:Dy.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(nn,{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(wu,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function la(e,t,r){return{...e,[t]:r}}function da({surface:e,title:t,description:r,value:n,options:a,onChange:i}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>i({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Yr(e,n)})]})]})]})}function $y({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:i,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(da,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:kn,onChange:u=>i(la(e,"chat",u))}),s.jsx(da,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:lr,onChange:u=>i(la(e,"code",u))}),s.jsx(da,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:lr,onChange:u=>i(la(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: ",Ys("chat",e.chat.preset)," · Code: ",Ys("code",e.code.preset)," · Terminal: ",Ys("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Ys("chat",us.chat.preset)," / ",Ys("code",us.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 By(){const{ides:e}=Qt(),t=e.find(X=>X.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=bt(),{userName:a}=Qt(),[i,c]=o.useState(a||""),[l,d]=o.useState(null),[m,u]=o.useState(null),[f,x]=o.useState(us),[C,g]=o.useState(!1),[p,j]=o.useState(""),[b,h]=o.useState(""),[y,S]=o.useState("127.0.0.1"),[k,A]=o.useState(""),[M,w]=o.useState(""),[v,B]=o.useState(""),[_,T]=o.useState(""),[D,K]=o.useState(""),[L,N]=o.useState(!1),I=async()=>{const ce=await(await Et("/auth/session")).json();d(ce)},W=async()=>{const ce=await(await Et("/api/v1/standalone/preferences")).json();u(ce),S(ce.standaloneBindHost);const ye=Bt(ce.standaloneFontPreferences);x(ye),ss(ye),Pa(ye)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([I(),W()]).catch(X=>{T(X instanceof Error?X.message:String(X))})},[]),o.useEffect(()=>{ss(f)},[f]);const P=X=>{const ce=X.target.value.trim();t!=null&&t.id&&ce!==a&&n(t.id,"set_user_name",{userName:ce}).catch(console.error)},[$,H]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=X=>{H(X);try{localStorage.setItem("adhdev_sound",X?"1":"0")}catch{}},he=async()=>{j(""),h(""),g(!0);try{const X=Bt(f),ce=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:X})}),ye=await ce.json();if(!ce.ok)throw new Error((ye==null?void 0:ye.error)||"Failed to save standalone font preferences");const ne=Bt(ye.standaloneFontPreferences);u(ye),x(ne),ss(ne),Pa(ne),h("Standalone chat fonts saved for this self-hosted dashboard.")}catch(X){j(X instanceof Error?X.message:String(X))}finally{g(!1)}},ie=()=>{const X=Bt(m==null?void 0:m.standaloneFontPreferences);j(""),h(""),x(X),ss(X)},te=()=>{j(""),h(""),x(us),ss(us)},be=async()=>{T(""),K(""),N(!0);try{const X=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:y})}),ce=await X.json();if(!X.ok)throw new Error((ce==null?void 0:ce.error)||"Failed to save standalone network preference");u(ce),S(ce.standaloneBindHost),K(ce.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{N(!1)}},we=async()=>{if(T(""),K(""),M.trim().length<4){T("Password must be at least 4 characters.");return}if(M!==v){T("New password and confirmation do not match.");return}N(!0);try{const X=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,newPassword:M})}),ce=await X.json();if(!X.ok)throw new Error((ce==null?void 0:ce.error)||"Failed to save password");d(ce),await W(),A(""),w(""),B(""),K(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Zl()}catch(X){T(X instanceof Error?X.message:String(X))}finally{N(!1)}},ge=async()=>{T(""),K(""),N(!0);try{const X=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,clear:!0})}),ce=await X.json();if(!X.ok)throw new Error((ce==null?void 0:ce.error)||"Failed to clear password");d(ce),await W(),A(""),w(""),B(""),K("Standalone password disabled.")}catch(X){T(X instanceof Error?X.message:String(X))}finally{N(!1)}};return s.jsxs(tr,{icon:s.jsx(dn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Ss,{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(Ss,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(kt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.75"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(kt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:y==="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:y==="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:()=>{be()},disabled:L,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:L?"Saving…":"Save default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(kt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),_&&s.jsx(Ss,{variant:"error",children:_}),D&&s.jsx(Ss,{variant:"success",children:D}),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:k,onChange:X=>A(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:M,onChange:X=>w(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:v,onChange:X=>B(X.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{we()},disabled:L,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:L?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ge()},disabled:L,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),s.jsx(kt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(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(kt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Xp,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(kt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(eh,{})]}),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(ch,{})]}),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($y,{value:f,savedValue:Bt(m==null?void 0:m.standaloneFontPreferences),saving:C,error:p,notice:b,onChange:x,onSave:()=>{he()},onResetToSaved:ie,onResetToDefaults:te})]}),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(uh,{})]})]})}),s.jsx(kt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Gp,{}),s.jsx(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(vu,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:$,onChange:J})]})}),s.jsx(kt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(nu,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:i,onChange:X=>c(X.target.value),onBlur:P,onKeyDown:X=>{X.key==="Enter"&&X.currentTarget.blur()}})]})})})]})}Kp();oh();Iy();const Ky=Ji({baseUrl:"",getToken:No});function Wy({children:e}){const[t,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,d]=o.useState(""),[m,u]=o.useState(!1),f=async()=>{a(!0),d("");try{const g=await(await Et("/auth/session")).json();r(g)}catch(C){d(C instanceof Error?C.message:String(C))}finally{a(!1)}};o.useEffect(()=>{f()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let C=!1;return(async()=>{try{const g=await Et("/api/v1/standalone/preferences");if(!g.ok)return;const p=await g.json();if(C)return;const j=Bt(p.standaloneFontPreferences);ss(j),Pa(j)}catch{}})(),()=>{C=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const x=async C=>{C.preventDefault(),u(!0),d("");try{const g=await Et("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),p=await g.json();if(!g.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),Zl()}catch(g){d(g instanceof Error?g.message:String(g))}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:x,children:[s.jsx("input",{type:"password",value:i,onChange:C=>c(C.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:m||!i,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:m?"Signing in…":"Unlock dashboard"})]}):s.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&s.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function Ui(){const{ides:e,initialLoaded:t}=Qt();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(fa,{to:`/machines/${r.id}`,replace:!0}):s.jsx(fa,{to:"/dashboard",replace:!0})}function Oy(){const e=o.useMemo(()=>({sendCommand:Gr,sendData:_a,sendPtyInput:wy}),[]);return s.jsx(Ld,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Qd,{client:Ky,children:s.jsx(Wy,{children:s.jsx(Ny,{children:s.jsx(eu,{value:e,children:s.jsx(Ly,{children:s.jsxs(_d,{children:[s.jsx(Gt,{path:"/dashboard",element:s.jsx(og,{})}),s.jsx(Gt,{path:"/machine",element:s.jsx(Ui,{})}),s.jsx(Gt,{path:"/machines/:id",element:s.jsx(my,{})}),s.jsx(Gt,{path:"/machines",element:s.jsx(Ui,{})}),s.jsx(Gt,{path:"/about",element:s.jsx(Ey,{})}),s.jsx(Gt,{path:"/settings",element:s.jsx(By,{})}),s.jsx(Gt,{path:"/mesh",element:s.jsx(py,{})}),s.jsx(Gt,{path:"*",element:s.jsx(fa,{to:"/dashboard",replace:!0})})]})})})})})})})}ep({connectionManager:Wt});Pd(document.getElementById("root")).render(s.jsx(Oy,{}));
94
+ `})]})}function hy({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const i=a.id.toLowerCase(),c=a.name.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||c.includes("hermes")}),n=Cl(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(kt,{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(Yl,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function xy(){const{sendCommand:e}=gt(),{ides:t}=Qt(),r=t.find(D=>D.daemonMode||D.type==="adhdev-daemon"),n=(r==null?void 0:r.id)||"",a=[];if(r){const D=r.availableProviders||[];for(const K of D)K.category==="cli"&&a.push({id:K.type||K.id,name:K.displayName||K.name||K.type,meshCoordinator:K.meshCoordinator})}const[i,c]=o.useState([]),[l,d]=o.useState(null),[m,u]=o.useState(!0),[f,x]=o.useState(null),[C,y]=o.useState(!1),[p,g]=o.useState(""),[b,h]=o.useState(""),[k,S]=o.useState(!1),[j,A]=o.useState(""),M=i.find(D=>D.id===l)||null,w=o.useCallback(async()=>{if(n){u(!0);try{const D=await e(n,"list_meshes");D!=null&&D.success?(c(D.meshes||[]),x(null)):x((D==null?void 0:D.error)||"Failed to load meshes")}catch(D){x((D==null?void 0:D.message)||"Failed to load meshes")}finally{u(!1)}}},[n,e]);o.useEffect(()=>{w()},[w]);async function v(){var D;if(!(!n||!p.trim()))try{const K=await e(n,"create_mesh",{name:p.trim(),repoIdentity:b.trim()||void 0});K!=null&&K.success?(y(!1),g(""),h(""),await w(),d(((D=K.mesh)==null?void 0:D.id)||null)):x((K==null?void 0:K.error)||"Create failed")}catch(K){x((K==null?void 0:K.message)||"Create failed")}}async function B(D){if(!(!n||!confirm("Delete this mesh?")))try{await e(n,"delete_mesh",{meshId:D}),d(null),await w()}catch(K){x((K==null?void 0:K.message)||"Delete failed")}}async function _(){if(!(!n||!l||!j.trim()))try{const D=await e(n,"add_mesh_node",{meshId:l,workspace:j.trim()});D!=null&&D.success?(S(!1),A(""),await w()):x((D==null?void 0:D.error)||"Add node failed")}catch(D){x((D==null?void 0:D.message)||"Add node failed")}}async function T(D){if(!(!n||!l))try{await e(n,"remove_mesh_node",{meshId:l,nodeId:D}),await w()}catch(K){x((K==null?void 0:K.message)||"Remove node failed")}}return n?M?s.jsxs(tr,{icon:s.jsx(wr,{}),title:M.name,subtitle:M.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>d(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>B(M.id),children:"Delete"})]}),children:[f&&s.jsx(Ss,{variant:"error",className:"mb-4",children:f}),s.jsxs(kt,{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:()=>S(!0),children:"+ Add Node"})}),k&&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:()=>S(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(vt,{size:16})})]}),s.jsx(En,{label:"Workspace Path",children:s.jsx($n,{value:j,onChange:D=>A(D.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:D=>{D.key==="Enter"&&_()},autoFocus:!0})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:_,disabled:!j.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>S(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),M.nodes.length===0?s.jsx(an,{icon:s.jsx(ms,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:M.nodes.map(D=>s.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium",children:D.workspace.split("/").pop()}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:D.workspace})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:()=>T(D.id),children:s.jsx(vt,{size:14})})]},D.id))})]}),s.jsx(hy,{meshId:M.id,availableCliAgents:a})]}):s.jsxs(tr,{icon:s.jsx(wr,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>y(!0),children:"+ Create Mesh"}),children:[f&&s.jsx(Ss,{variant:"error",className:"mb-4",children:f}),C&&s.jsx(kt,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(En,{label:"Name",children:s.jsx($n,{value:p,onChange:D=>g(D.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(En,{label:"Repo Identity (optional)",children:s.jsx($n,{value:b,onChange:D=>h(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:v,disabled:!p.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(!1),children:"Cancel"})]})]})}),m?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):i.length===0?s.jsx(an,{icon:s.jsx(wr,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:i.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:()=>d(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))})]}):s.jsx(tr,{icon:s.jsx(wr,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function Co(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function by(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=Co();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Et(e,t){return await fetch(by(e),{credentials:"same-origin",...t})}function ed(){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 gy{constructor(){Qe(this,"adapters",new Map);Qe(this,"states",new Map);Qe(this,"runtimeListeners",new Map);Qe(this,"screenshotCallbacks",new Map);Qe(this,"statusCallbacks",new Set)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r)}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,i,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:i,rows:c})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const i=await Et(`${a.pathname}${a.search}`);if(!i.ok){let l=`Runtime snapshot unavailable (${i.status})`;try{const d=await i.json();d!=null&&d.error&&(l=d.error)}catch{}return{success:!1,error:l}}const c=await i.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof c.seq=="number"?c.seq:0,text:typeof c.text=="string"?c.text:"",truncated:!!c.truncated,cols:typeof c.cols=="number"?c.cols:void 0,rows:typeof c.rows=="number"?c.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Wt=new gy;function yy(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Co();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Br=yy(),Ui=3e3,vy=3e4;let _t=null,wy=0;const dn=new Map;let es=null,nr=null;function zi(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function qs(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function jy(e){return e==="connected"?"connected":e}async function Gr(e,t,r){const n=el(e,r||{}),a=_t;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++wy}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{dn.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);dn.set(i,{resolve:m=>{clearTimeout(d),c(m)},reject:m=>{clearTimeout(d),l(m)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Pa(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 ky(e,t,r){const n=_t;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=el(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 Sy{constructor(t){Qe(this,"daemonId");Qe(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 Gr(this.daemonId,t,r)}async sendInput(t,r){return Gr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,es&&(clearInterval(es),es=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Gr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Wt.emitScreenshot(this.daemonId,a)}}catch{}};r(),es=setInterval(r,2e3)}stopScreenshots(t){es&&(clearInterval(es),es=null)}}let It=null;function Ny(e){return(!It||It.daemonId!==e)&&(It=new Sy(e)),It}function Cy({children:e}){const t=o.useRef(or()),r=or();t.current=r;const{setUserName:n}=Qt(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),d=o.useCallback((p,g)=>{l(p),nr==null||nr(p,g)},[]),m=o.useRef(null),u=o.useRef(),f=o.useRef(Ui),x=o.useRef(!0),C=o.useRef(!1),y=o.useRef("initial_connect");return o.useEffect(()=>{x.current=!0,C.current=!1;function p(){var h,k;if(!x.current||((h=m.current)==null?void 0:h.readyState)===WebSocket.OPEN||((k=m.current)==null?void 0:k.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Br}...`),qs("connect_attempt",{url:Br,reason:y.current,delayMs:f.current});let b;try{b=new WebSocket(Br)}catch(S){console.error("[Standalone WS] Failed to create WebSocket:",S),g();return}m.current=b,b.onopen=()=>{if(!x.current){b.close();return}d("connected"),f.current=Ui,qs("open",{url:Br,reason:y.current}),Ht.resubscribeAll({sendData:Pa}),console.log("[Standalone WS] Connected")},_t=b,b.onmessage=S=>{var j,A;try{const M=JSON.parse(S.data);if((M.type==="command_result"||M.type==="error")&&M.requestId){const w=dn.get(M.requestId);w&&(dn.delete(M.requestId),M.type==="error"?w.reject(new Error(((j=M.data)==null?void 0:j.message)||"Command failed")):w.resolve(M.data));return}if(M.type==="session_output"){const w=M.sessionId||M.cliId||M.cliType;w&&Wt.emitSessionOutput(w,typeof M.data=="string"?M.data:"",typeof M.seq=="number"?M.seq:void 0);return}if(M.type==="runtime_snapshot"){Wt.emitRuntimeSnapshot(M.sessionId,typeof M.text=="string"?M.text:"",typeof M.seq=="number"?M.seq:0,!!M.truncated,typeof M.cols=="number"?M.cols:void 0,typeof M.rows=="number"?M.rows:void 0);return}if(M.type==="topic_update"){const w=M.update;w&&Ht.publish(w);return}if(M.type==="status"||M.type==="initial_state"){const w=M.data;if(!w)return;const{injectEntries:v,markLoaded:B,getIdes:_}=t.current,T=w.instanceId||"standalone",D=_().find(N=>N.id===T),K=Ny(T);Wt.register(T,K),Wt.setState(T,"connected"),d("connected",T),Wt.emitStatus(T,w);const L=rn(w,{daemonId:T,existingDaemon:D,existingEntries:_()});zi("ws_status",{type:M.type,daemonId:T,sessions:(w.sessions||[]).map(N=>({id:N.id,parentId:N.parentId,providerType:N.providerType,kind:N.kind,transport:N.transport,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,title:N.title})),recentLaunches:(w.recentLaunches||[]).map(N=>({id:N.id,providerType:N.providerType,kind:N.kind,workspace:N.workspace,lastLaunchedAt:N.lastLaunchedAt}))}),zi("entries",{daemonId:T,entries:L.filter(N=>N.type!=="adhdev-daemon").map(N=>({id:N.id,type:N.type,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,sessionId:N.sessionId}))}),L.length>0&&v(L,{authoritativeDaemonIds:[T]}),B(),c.current!==T&&((A=i.current)==null||A.call(i),c.current=T,i.current=Ht.subscribe({sendData:Pa},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},N=>{if(N.topic!=="daemon.metadata")return;const I=t.current.getIdes(),F=I.find($=>$.id===T),P=rn(N.status,{daemonId:T,existingDaemon:F,existingEntries:I,timestamp:N.timestamp});P.length>0&&t.current.injectEntries(P,{authoritativeDaemonIds:[T]}),N.userName&&a.current&&a.current(N.userName)}))}}catch(M){console.error("[Standalone WS] Parse error:",M)}},b.onclose=S=>{x.current&&(It==null||It.stopScreenshots(),It&&Wt.setState(It.daemonId,"disconnected"),d("disconnected"),m.current=null,y.current=`close:${S.code}${S.wasClean?":clean":":unclean"}`,qs("close",{code:S.code,reason:S.reason||"",wasClean:S.wasClean}),g())},b.onerror=S=>{C.current||!x.current||(y.current="error",qs("error",{message:S instanceof Event?"event":String(S),readyState:b.readyState}),console.warn("[Standalone WS] Error, will reconnect:",S))}}function g(){if(!x.current)return;clearTimeout(u.current);const b=f.current;console.log(`[Standalone WS] Reconnecting in ${b}ms...`),qs("schedule_reconnect",{reason:y.current,delayMs:b}),u.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,vy),p()},b)}return p(),()=>{var b;x.current=!1,C.current=!0,(b=i.current)==null||b.call(i),i.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),It&&(It.stopScreenshots(),Wt.unregister(It.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function Ty({children:e}){const[t,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(nr=(c,l)=>{r(c),l&&a(l)},()=>{nr=null}),[]);const i=o.useMemo(()=>{const c=t==="connected",l=jy(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:c,connectionStates:d}},[t,n]);return s.jsx(Xd,{connectionOverrides:i,children:s.jsx(Cy,{children:e})})}const td="adhdev_standalone_font_preferences",us={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Sn=[{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"}],lr=[{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"}],My=new Set(Sn.map(e=>e.id)),Ay=new Set(lr.map(e=>e.id));function Bt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:qr("chat",t.chat),code:qr("code",t.code),terminal:qr("terminal",t.terminal)}}function qr(e,t){const r=us[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?My:Ay).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Yr(e,t){var a;const r=qr(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Sn:lr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function Iy(e){const t=Bt(e),r=Yr("chat",t.chat),n=Yr("code",t.code),a=Yr("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function ss(e,t=document.documentElement){const r=Bt(e),n=Iy(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function Da(e){const t=Bt(e);try{localStorage.setItem(td,JSON.stringify(t))}catch{}return t}function Ry(){try{const e=localStorage.getItem(td);if(e)return Bt(JSON.parse(e))}catch{}return us}function Ly(){return ss(Ry())}function Ys(e,t){var n;const r=e==="chat"?Sn:lr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const _y=[{id:"dashboard",path:"/dashboard",icon:s.jsx(tc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(Yt,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Is,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(un,{}),label:"Settings"}];function Py({children:e}){const t=$s(),r=$a(),n=o.useMemo(()=>_y.map(i=>({...i,active:r.pathname.startsWith(i.path),onSelect:()=>t(i.path)})),[r.pathname,t]),a=o.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(rc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(nc,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Hp,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.75"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:i?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const Dy=[{icon:s.jsx(Yt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ut,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(ac,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Mt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Is,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(rc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Ey=[{icon:s.jsx(mu,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(tc,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(mn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(ou,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(sc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(cu,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],$y=[{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 By(){return s.jsxs(tr,{icon:s.jsx(nc,{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.75"]}),children:[s.jsx(kt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),s.jsx(kt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Dy.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(kt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:tl.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:rl.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:sl.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(kt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Ey.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(kt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:$y.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(an,{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(ju,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function da(e,t,r){return{...e,[t]:r}}function ua({surface:e,title:t,description:r,value:n,options:a,onChange:i}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>i({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Yr(e,n)})]})]})]})}function Ky({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:i,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(ua,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Sn,onChange:u=>i(da(e,"chat",u))}),s.jsx(ua,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:lr,onChange:u=>i(da(e,"code",u))}),s.jsx(ua,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:lr,onChange:u=>i(da(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: ",Ys("chat",e.chat.preset)," · Code: ",Ys("code",e.code.preset)," · Terminal: ",Ys("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Ys("chat",us.chat.preset)," / ",Ys("code",us.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 Wy(){const{ides:e}=Qt(),t=e.find(X=>X.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=gt(),{userName:a}=Qt(),[i,c]=o.useState(a||""),[l,d]=o.useState(null),[m,u]=o.useState(null),[f,x]=o.useState(us),[C,y]=o.useState(!1),[p,g]=o.useState(""),[b,h]=o.useState(""),[k,S]=o.useState("127.0.0.1"),[j,A]=o.useState(""),[M,w]=o.useState(""),[v,B]=o.useState(""),[_,T]=o.useState(""),[D,K]=o.useState(""),[L,N]=o.useState(!1),I=async()=>{const ce=await(await Et("/auth/session")).json();d(ce)},F=async()=>{const ce=await(await Et("/api/v1/standalone/preferences")).json();u(ce),S(ce.standaloneBindHost);const ye=Bt(ce.standaloneFontPreferences);x(ye),ss(ye),Da(ye)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([I(),F()]).catch(X=>{T(X instanceof Error?X.message:String(X))})},[]),o.useEffect(()=>{ss(f)},[f]);const P=X=>{const ce=X.target.value.trim();t!=null&&t.id&&ce!==a&&n(t.id,"set_user_name",{userName:ce}).catch(console.error)},[$,H]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=X=>{H(X);try{localStorage.setItem("adhdev_sound",X?"1":"0")}catch{}},he=async()=>{g(""),h(""),y(!0);try{const X=Bt(f),ce=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:X})}),ye=await ce.json();if(!ce.ok)throw new Error((ye==null?void 0:ye.error)||"Failed to save standalone font preferences");const ne=Bt(ye.standaloneFontPreferences);u(ye),x(ne),ss(ne),Da(ne),h("Standalone chat fonts saved for this self-hosted dashboard.")}catch(X){g(X instanceof Error?X.message:String(X))}finally{y(!1)}},ie=()=>{const X=Bt(m==null?void 0:m.standaloneFontPreferences);g(""),h(""),x(X),ss(X)},te=()=>{g(""),h(""),x(us),ss(us)},be=async()=>{T(""),K(""),N(!0);try{const X=await Et("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:k})}),ce=await X.json();if(!X.ok)throw new Error((ce==null?void 0:ce.error)||"Failed to save standalone network preference");u(ce),S(ce.standaloneBindHost),K(ce.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{N(!1)}},we=async()=>{if(T(""),K(""),M.trim().length<4){T("Password must be at least 4 characters.");return}if(M!==v){T("New password and confirmation do not match.");return}N(!0);try{const X=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:j,newPassword:M})}),ce=await X.json();if(!X.ok)throw new Error((ce==null?void 0:ce.error)||"Failed to save password");d(ce),await F(),A(""),w(""),B(""),K(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),ed()}catch(X){T(X instanceof Error?X.message:String(X))}finally{N(!1)}},ge=async()=>{T(""),K(""),N(!0);try{const X=await Et("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:j,clear:!0})}),ce=await X.json();if(!X.ok)throw new Error((ce==null?void 0:ce.error)||"Failed to clear password");d(ce),await F(),A(""),w(""),B(""),K("Standalone password disabled.")}catch(X){T(X instanceof Error?X.message:String(X))}finally{N(!1)}};return s.jsxs(tr,{icon:s.jsx(un,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Ss,{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(Ss,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(kt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.75"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(kt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:k==="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:k==="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:()=>{be()},disabled:L,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:L?"Saving…":"Save default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(kt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),_&&s.jsx(Ss,{variant:"error",children:_}),D&&s.jsx(Ss,{variant:"success",children:D}),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:j,onChange:X=>A(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:M,onChange:X=>w(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:v,onChange:X=>B(X.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{we()},disabled:L,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:L?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ge()},disabled:L,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),s.jsx(kt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(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(kt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Qp,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(kt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(sh,{})]}),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(dh,{})]}),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(Ky,{value:f,savedValue:Bt(m==null?void 0:m.standaloneFontPreferences),saving:C,error:p,notice:b,onChange:x,onSave:()=>{he()},onResetToSaved:ie,onResetToDefaults:te})]}),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(fh,{})]})]})}),s.jsx(kt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Yp,{}),s.jsx(ts,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(wu,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:$,onChange:J})]})}),s.jsx(kt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(au,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:i,onChange:X=>c(X.target.value),onBlur:P,onKeyDown:X=>{X.key==="Enter"&&X.currentTarget.blur()}})]})})})]})}Op();ch();Ly();const Oy=Zi({baseUrl:"",getToken:Co});function Fy({children:e}){const[t,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,d]=o.useState(""),[m,u]=o.useState(!1),f=async()=>{a(!0),d("");try{const y=await(await Et("/auth/session")).json();r(y)}catch(C){d(C instanceof Error?C.message:String(C))}finally{a(!1)}};o.useEffect(()=>{f()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let C=!1;return(async()=>{try{const y=await Et("/api/v1/standalone/preferences");if(!y.ok)return;const p=await y.json();if(C)return;const g=Bt(p.standaloneFontPreferences);ss(g),Da(g)}catch{}})(),()=>{C=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const x=async C=>{C.preventDefault(),u(!0),d("");try{const y=await Et("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),p=await y.json();if(!y.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),ed()}catch(y){d(y instanceof Error?y.message:String(y))}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:x,children:[s.jsx("input",{type:"password",value:i,onChange:C=>c(C.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:m||!i,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:m?"Signing in…":"Unlock dashboard"})]}):s.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&s.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function Vi(){const{ides:e,initialLoaded:t}=Qt();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(pa,{to:`/machines/${r.id}`,replace:!0}):s.jsx(pa,{to:"/dashboard",replace:!0})}function Hy(){const e=o.useMemo(()=>({sendCommand:Gr,sendData:Pa,sendPtyInput:ky}),[]);return s.jsx(_d,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Zd,{client:Oy,children:s.jsx(Fy,{children:s.jsx(Ty,{children:s.jsx(tu,{value:e,children:s.jsx(Py,{children:s.jsxs(Pd,{children:[s.jsx(Gt,{path:"/dashboard",element:s.jsx(cg,{})}),s.jsx(Gt,{path:"/machine",element:s.jsx(Vi,{})}),s.jsx(Gt,{path:"/machines/:id",element:s.jsx(py,{})}),s.jsx(Gt,{path:"/machines",element:s.jsx(Vi,{})}),s.jsx(Gt,{path:"/about",element:s.jsx(By,{})}),s.jsx(Gt,{path:"/settings",element:s.jsx(Wy,{})}),s.jsx(Gt,{path:"/mesh",element:s.jsx(xy,{})}),s.jsx(Gt,{path:"*",element:s.jsx(pa,{to:"/dashboard",replace:!0})})]})})})})})})})}sp({connectionManager:Wt});Dd(document.getElementById("root")).render(s.jsx(Hy,{}));